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 |
---|---|---|---|---|---|---|---|---|---|---|
ManagerManager/asgi.py
|
"""
ASGI config for ManagerManager project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ManagerManager.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
solutions/EMFSolutionXtend/src/ttc2019/solutions/xtend/LiveContestDriver.java
|
package ttc2019.solutions.xtend;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import ttc2019.live.bibtex.BibtexPackage;
import ttc2019.live.changes.ChangesPackage;
import ttc2019.live.changes.ModelChangeSet;
import ttc2019.live.docbook.DocBook;
import ttc2019.live.docbook.DocbookPackage;
public class LiveContestDriver {
public static void main(String[] args) {
try {
Initialize();
Load();
Run();
} catch(Exception e) {
e.printStackTrace();
}
}
private static String Tool;
private static String MutantSet;
private static String SourcePath;
private static String Mutant;
private static String MutantPath;
private static String RunIndex;
private static long stopwatch;
private static ResourceSet repository;
private static Solution solution;
static void Load()
{
stopwatch = System.nanoTime();
repository = new ResourceSetImpl();
repository.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new Resource.Factory() {
@Override
public Resource createResource(URI uri) {
XMIResourceImpl ret = new XMIResourceImpl(uri);
ret.setIntrinsicIDToEObjectMap(new HashMap<>());
ret.getDefaultLoadOptions().put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, true);
return ret;
}
});
repository.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
repository.getPackageRegistry().put(BibtexPackage.eINSTANCE.getNsURI(), BibtexPackage.eINSTANCE);
repository.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bibtex", new XMIResourceFactoryImpl());
repository.getPackageRegistry().put(DocbookPackage.eINSTANCE.getNsURI(), DocbookPackage.eINSTANCE);
repository.getResourceFactoryRegistry().getExtensionToFactoryMap().put("docbook", new XMIResourceFactoryImpl());
repository.getPackageRegistry().put(ChangesPackage.eINSTANCE.getNsURI(), ChangesPackage.eINSTANCE);
repository.getResourceFactoryRegistry().getExtensionToFactoryMap().put("changes", new XMIResourceFactoryImpl());
String ChangePath = MutantPath.replaceAll("mutated.docbook", "applied.changes");
String TargetPath = SourcePath.replaceAll(".bibtex", ".docbook");
Boolean followingEVL = false;
if("EMFSolutionXtendFollowingEVL".contentEquals(Tool)) {
followingEVL = true;
} else {
followingEVL = false;
}
solution = new Solution(followingEVL, (DocBook)loadFile(TargetPath), (ModelChangeSet)loadFile(ChangePath));
stopwatch = System.nanoTime() - stopwatch;
Report(BenchmarkPhase.Load, null);
}
private static Object loadFile(String path) {
Resource mRes;
try {
mRes = repository.getResource(URI.createFileURI(new File(path).getCanonicalPath()), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
return mRes.getContents().get(0);
}
static void Initialize() throws Exception
{
stopwatch = System.nanoTime();
// Make sure that both metamodels are available and loaded
BibtexPackage.eINSTANCE.getName();
DocbookPackage.eINSTANCE.getName();
Tool = System.getenv("Tool");
MutantSet = System.getenv("MutantSet");
SourcePath = System.getenv("SourcePath");
Mutant = System.getenv("Mutant");
MutantPath = System.getenv("MutantPath");
RunIndex = System.getenv("RunIndex");
stopwatch = System.nanoTime() - stopwatch;
Report(BenchmarkPhase.Initialization, null);
}
static void Run() throws Exception
{
stopwatch = System.nanoTime();
int problems = solution.execute();
stopwatch = System.nanoTime() - stopwatch;
Report(BenchmarkPhase.Run, Integer.toString(problems));
}
static void Report(BenchmarkPhase phase, String result)
{
System.out.println(String.format("%s;%s;%s;%s;%s;%s;Time;%s", Tool, MutantSet, new File(SourcePath).getName(), Mutant, RunIndex, phase.toString(), Long.toString(stopwatch)));
if ("true".equals(System.getenv("NoGC"))) {
// nothing to do
} else {
Runtime.getRuntime().gc();
Runtime.getRuntime().gc();
Runtime.getRuntime().gc();
Runtime.getRuntime().gc();
Runtime.getRuntime().gc();
}
long memoryUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println(String.format("%s;%s;%s;%s;%s;%s;Memory;%s", Tool, MutantSet, new File(SourcePath).getName(), Mutant, RunIndex, phase.toString(), Long.toString(memoryUsed)));
if (result != null)
{
System.out.println(String.format("%s;%s;%s;%s;%s;%s;Problems;%s", Tool, MutantSet, new File(SourcePath).getName(), Mutant, RunIndex, phase.toString(), result));
}
}
enum BenchmarkPhase {
Initialization,
Load,
Run
}
}
|
[
"\"Tool\"",
"\"MutantSet\"",
"\"SourcePath\"",
"\"Mutant\"",
"\"MutantPath\"",
"\"RunIndex\"",
"\"NoGC\""
] |
[] |
[
"Mutant",
"NoGC",
"MutantPath",
"RunIndex",
"MutantSet",
"Tool",
"SourcePath"
] |
[]
|
["Mutant", "NoGC", "MutantPath", "RunIndex", "MutantSet", "Tool", "SourcePath"]
|
java
| 7 | 0 | |
integrationtest/vm/perf/volume/test_crt_sp_with_max_threads.py
|
'''
New Perf Test for creating snapshot operations.
The created number will depends on the environment variable: ZSTACK_TEST_NUM
The default max threads are 1000. It could be modified by env variable:
ZSTACK_THREAD_THRESHOLD
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.config_operations as con_ops
import zstackwoodpecker.operations.account_operations as acc_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.zstack_test.zstack_test_volume as test_vol_header
import time
import os
import sys
import threading
import random
_config_ = {
'timeout' : 10000,
'noparallel' : True
}
session_uuid = None
session_to = None
session_mc = None
sp_name = None
exc_info = []
def create_sp(volume_uuid):
try:
sp_option = test_util.SnapshotOption()
sp_option.set_name(sp_name)
sp_option.set_volume_uuid(volume_uuid)
sp_option.set_session_uuid(session_uuid)
sp = vol_ops.create_snapshot(sp_option)
except:
exc_info.append(sys.exc_info())
def check_thread_exception():
if exc_info:
info1 = exc_info[0][1]
info2 = exc_info[0][2]
raise info1, None, info2
def test():
global session_uuid
global session_to
global session_mc
global sp_name
thread_threshold = os.environ.get('ZSTACK_THREAD_THRESHOLD')
if not thread_threshold:
thread_threshold = 1000
else:
thread_threshold = int(thread_threshold)
sp_num = os.environ.get('ZSTACK_TEST_NUM')
if not sp_num:
sp_num = 0
else:
sp_num = int(sp_num)
#change account session timeout.
session_to = con_ops.change_global_config('identity', 'session.timeout', '720000', session_uuid)
session_mc = con_ops.change_global_config('identity', 'session.maxConcurrent', '10000', session_uuid)
session_uuid = acc_ops.login_as_admin()
cond = res_ops.gen_query_conditions('type', '=', 'Root')
vol_num = res_ops.query_resource_count(res_ops.VOLUME, cond, session_uuid)
if vol_num < thread_threshold:
test_util.test_fail('This test needs: %d VM instances for volume attaching and detaching operations. But there are only %d VMs root volumes. Please use this case: test_crt_basic_vm_with_max_threads.py to create required VMs.' % (thread_threshold, vol_num))
vols = res_ops.query_resource_fields(res_ops.VOLUME, cond, session_uuid, \
['uuid'], start = 0, limit = thread_threshold)
test_util.test_logger('ZSTACK_THREAD_THRESHOLD is %d' % thread_threshold)
test_util.test_logger('ZSTACK_TEST_NUM is %d' % sp_num)
org_num = sp_num
random_name = random.random()
sp_name = 'perf_sp_%s' % str(random_name)
vol_num = 0
while sp_num > 0:
check_thread_exception()
sp_num -= 1
if vol_num > (thread_threshold - 1):
vol_num = 0
thread = threading.Thread(target=create_sp, \
args = (vols[vol_num].uuid, ))
vol_num += 1
while threading.active_count() > thread_threshold:
time.sleep(0.1)
thread.start()
while threading.active_count() > 1:
time.sleep(0.1)
cond = res_ops.gen_query_conditions('name', '=', sp_name)
sp_num = res_ops.query_resource_count(res_ops.VOLUME_SNAPSHOT, cond, session_uuid)
con_ops.change_global_config('identity', 'session.timeout', session_to, session_uuid)
con_ops.change_global_config('identity', 'session.maxConcurrent', session_mc, session_uuid)
acc_ops.logout(session_uuid)
if sp_num == org_num:
test_util.test_pass('Create %d Volumes Snapshot Perf Test Success' % org_num)
else:
test_util.test_fail('Create %d Volumes Snapshot Perf Test Failed. Only find %d Volume Snapshots.' % (org_num, sp_num))
#Will be called only if exception happens in test().
def error_cleanup():
if session_to:
con_ops.change_global_config('identity', 'session.timeout', session_to, session_uuid)
if session_mc:
con_ops.change_global_config('identity', 'session.maxConcurrent', session_mc, session_uuid)
if session_uuid:
acc_ops.logout(session_uuid)
|
[] |
[] |
[
"ZSTACK_TEST_NUM",
"ZSTACK_THREAD_THRESHOLD"
] |
[]
|
["ZSTACK_TEST_NUM", "ZSTACK_THREAD_THRESHOLD"]
|
python
| 2 | 0 | |
vendor/github.com/rogpeppe/go-internal/testscript/testscript.go
|
// Copyright 2018 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.
// Script-driven tests.
// See testdata/script/README for an overview.
package testscript
import (
"bytes"
"context"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/rogpeppe/go-internal/imports"
"github.com/rogpeppe/go-internal/internal/os/execpath"
"github.com/rogpeppe/go-internal/par"
"github.com/rogpeppe/go-internal/testenv"
"github.com/rogpeppe/go-internal/txtar"
)
var execCache par.Cache
// If -testwork is specified, the test prints the name of the temp directory
// and does not remove it when done, so that a programmer can
// poke at the test file tree afterward.
var testWork = flag.Bool("testwork", false, "")
// Env holds the environment to use at the start of a test script invocation.
type Env struct {
// WorkDir holds the path to the root directory of the
// extracted files.
WorkDir string
// Vars holds the initial set environment variables that will be passed to the
// testscript commands.
Vars []string
// Cd holds the initial current working directory.
Cd string
// Values holds a map of arbitrary values for use by custom
// testscript commands. This enables Setup to pass arbitrary
// values (not just strings) through to custom commands.
Values map[interface{}]interface{}
ts *TestScript
}
// Value returns a value from Env.Values, or nil if no
// value was set by Setup.
func (ts *TestScript) Value(key interface{}) interface{} {
return ts.values[key]
}
// Defer arranges for f to be called at the end
// of the test. If Defer is called multiple times, the
// defers are executed in reverse order (similar
// to Go's defer statement)
func (e *Env) Defer(f func()) {
e.ts.Defer(f)
}
// Params holds parameters for a call to Run.
type Params struct {
// Dir holds the name of the directory holding the scripts.
// All files in the directory with a .txt suffix will be considered
// as test scripts. By default the current directory is used.
// Dir is interpreted relative to the current test directory.
Dir string
// Setup is called, if not nil, to complete any setup required
// for a test. The WorkDir and Vars fields will have already
// been initialized and all the files extracted into WorkDir,
// and Cd will be the same as WorkDir.
// The Setup function may modify Vars and Cd as it wishes.
Setup func(*Env) error
// Condition is called, if not nil, to determine whether a particular
// condition is true. It's called only for conditions not in the
// standard set, and may be nil.
Condition func(cond string) (bool, error)
// Cmds holds a map of commands available to the script.
// It will only be consulted for commands not part of the standard set.
Cmds map[string]func(ts *TestScript, neg bool, args []string)
// TestWork specifies that working directories should be
// left intact for later inspection.
TestWork bool
// IgnoreMissedCoverage specifies that if coverage information
// is being generated (with the -test.coverprofile flag) and a subcommand
// function passed to RunMain fails to generate coverage information
// (for example because the function invoked os.Exit), then the
// error will be ignored.
IgnoreMissedCoverage bool
}
// RunDir runs the tests in the given directory. All files in dir with a ".txt"
// are considered to be test files.
func Run(t *testing.T, p Params) {
RunT(tshim{t}, p)
}
// T holds all the methods of the *testing.T type that
// are used by testscript.
type T interface {
Skip(...interface{})
Fatal(...interface{})
Parallel()
Log(...interface{})
FailNow()
Run(string, func(T))
// Verbose is usually implemented by the testing package
// directly rather than on the *testing.T type.
Verbose() bool
}
type tshim struct {
*testing.T
}
func (t tshim) Run(name string, f func(T)) {
t.T.Run(name, func(t *testing.T) {
f(tshim{t})
})
}
func (t tshim) Verbose() bool {
return testing.Verbose()
}
// RunT is like Run but uses an interface type instead of the concrete *testing.T
// type to make it possible to use testscript functionality outside of go test.
func RunT(t T, p Params) {
files, err := filepath.Glob(filepath.Join(p.Dir, "*.txt"))
if err != nil {
t.Fatal(err)
}
testTempDir, err := ioutil.TempDir(os.Getenv("GOTMPDIR"), "go-test-script")
if err != nil {
t.Fatal(err)
}
refCount := int32(len(files))
for _, file := range files {
file := file
name := strings.TrimSuffix(filepath.Base(file), ".txt")
t.Run(name, func(t T) {
t.Parallel()
ts := &TestScript{
t: t,
testTempDir: testTempDir,
name: name,
file: file,
params: p,
ctxt: context.Background(),
deferred: func() {},
}
defer func() {
if p.TestWork {
return
}
removeAll(ts.workdir)
if atomic.AddInt32(&refCount, -1) == 0 {
// This is the last subtest to finish. Remove the
// parent directory too.
os.Remove(testTempDir)
}
}()
ts.run()
})
}
}
// A TestScript holds execution state for a single test script.
type TestScript struct {
params Params
t T
testTempDir string
workdir string // temporary work dir ($WORK)
log bytes.Buffer // test execution log (printed at end of test)
mark int // offset of next log truncation
cd string // current directory during test execution; initially $WORK/gopath/src
name string // short name of test ("foo")
file string // full file name ("testdata/script/foo.txt")
lineno int // line number currently executing
line string // line currently executing
env []string // environment list (for os/exec)
envMap map[string]string // environment mapping (matches env; on Windows keys are lowercase)
values map[interface{}]interface{} // values for custom commands
stdin string // standard input to next 'go' command; set by 'stdin' command.
stdout string // standard output from last 'go' command; for 'stdout' command
stderr string // standard error from last 'go' command; for 'stderr' command
stopped bool // test wants to stop early
start time.Time // time phase started
background []backgroundCmd // backgrounded 'exec' and 'go' commands
deferred func() // deferred cleanup actions.
ctxt context.Context // per TestScript context
}
type backgroundCmd struct {
cmd *exec.Cmd
wait <-chan struct{}
neg bool // if true, cmd should fail
}
// setup sets up the test execution temporary directory and environment.
// It returns the comment section of the txtar archive.
func (ts *TestScript) setup() string {
ts.workdir = filepath.Join(ts.testTempDir, "script-"+ts.name)
ts.Check(os.MkdirAll(filepath.Join(ts.workdir, "tmp"), 0777))
env := &Env{
Vars: []string{
"WORK=" + ts.workdir, // must be first for ts.abbrev
"PATH=" + os.Getenv("PATH"),
homeEnvName() + "=/no-home",
tempEnvName() + "=" + filepath.Join(ts.workdir, "tmp"),
"devnull=" + os.DevNull,
":=" + string(os.PathListSeparator),
},
WorkDir: ts.workdir,
Values: make(map[interface{}]interface{}),
Cd: ts.workdir,
ts: ts,
}
// Must preserve SYSTEMROOT on Windows: https://github.com/golang/go/issues/25513 et al
if runtime.GOOS == "windows" {
env.Vars = append(env.Vars,
"SYSTEMROOT="+os.Getenv("SYSTEMROOT"),
"exe=.exe",
)
} else {
env.Vars = append(env.Vars,
"exe=",
)
}
ts.cd = env.Cd
// Unpack archive.
a, err := txtar.ParseFile(ts.file)
ts.Check(err)
for _, f := range a.Files {
name := ts.MkAbs(ts.expand(f.Name))
ts.Check(os.MkdirAll(filepath.Dir(name), 0777))
ts.Check(ioutil.WriteFile(name, f.Data, 0666))
}
// Run any user-defined setup.
if ts.params.Setup != nil {
ts.Check(ts.params.Setup(env))
}
ts.cd = env.Cd
ts.env = env.Vars
ts.values = env.Values
ts.envMap = make(map[string]string)
for _, kv := range ts.env {
if i := strings.Index(kv, "="); i >= 0 {
ts.envMap[envvarname(kv[:i])] = kv[i+1:]
}
}
return string(a.Comment)
}
// run runs the test script.
func (ts *TestScript) run() {
// Truncate log at end of last phase marker,
// discarding details of successful phase.
rewind := func() {
if !ts.t.Verbose() {
ts.log.Truncate(ts.mark)
}
}
// Insert elapsed time for phase at end of phase marker
markTime := func() {
if ts.mark > 0 && !ts.start.IsZero() {
afterMark := append([]byte{}, ts.log.Bytes()[ts.mark:]...)
ts.log.Truncate(ts.mark - 1) // cut \n and afterMark
fmt.Fprintf(&ts.log, " (%.3fs)\n", time.Since(ts.start).Seconds())
ts.log.Write(afterMark)
}
ts.start = time.Time{}
}
defer func() {
// On a normal exit from the test loop, background processes are cleaned up
// before we print PASS. If we return early (e.g., due to a test failure),
// don't print anything about the processes that were still running.
for _, bg := range ts.background {
interruptProcess(bg.cmd.Process)
}
for _, bg := range ts.background {
<-bg.wait
}
ts.background = nil
markTime()
// Flush testScript log to testing.T log.
ts.t.Log("\n" + ts.abbrev(ts.log.String()))
}()
defer func() {
ts.deferred()
}()
script := ts.setup()
// With -v or -testwork, start log with full environment.
if *testWork || ts.t.Verbose() {
// Display environment.
ts.cmdEnv(false, nil)
fmt.Fprintf(&ts.log, "\n")
ts.mark = ts.log.Len()
}
// Run script.
// See testdata/script/README for documentation of script form.
Script:
for script != "" {
// Extract next line.
ts.lineno++
var line string
if i := strings.Index(script, "\n"); i >= 0 {
line, script = script[:i], script[i+1:]
} else {
line, script = script, ""
}
// # is a comment indicating the start of new phase.
if strings.HasPrefix(line, "#") {
// If there was a previous phase, it succeeded,
// so rewind the log to delete its details (unless -v is in use).
// If nothing has happened at all since the mark,
// rewinding is a no-op and adding elapsed time
// for doing nothing is meaningless, so don't.
if ts.log.Len() > ts.mark {
rewind()
markTime()
}
// Print phase heading and mark start of phase output.
fmt.Fprintf(&ts.log, "%s\n", line)
ts.mark = ts.log.Len()
ts.start = time.Now()
continue
}
// Parse input line. Ignore blanks entirely.
args := ts.parse(line)
if len(args) == 0 {
continue
}
// Echo command to log.
fmt.Fprintf(&ts.log, "> %s\n", line)
// Command prefix [cond] means only run this command if cond is satisfied.
for strings.HasPrefix(args[0], "[") && strings.HasSuffix(args[0], "]") {
cond := args[0]
cond = cond[1 : len(cond)-1]
cond = strings.TrimSpace(cond)
args = args[1:]
if len(args) == 0 {
ts.Fatalf("missing command after condition")
}
want := true
if strings.HasPrefix(cond, "!") {
want = false
cond = strings.TrimSpace(cond[1:])
}
ok, err := ts.condition(cond)
if err != nil {
ts.Fatalf("bad condition %q: %v", cond, err)
}
if ok != want {
// Don't run rest of line.
continue Script
}
}
// Command prefix ! means negate the expectations about this command:
// go command should fail, match should not be found, etc.
neg := false
if args[0] == "!" {
neg = true
args = args[1:]
if len(args) == 0 {
ts.Fatalf("! on line by itself")
}
}
// Run command.
cmd := scriptCmds[args[0]]
if cmd == nil {
cmd = ts.params.Cmds[args[0]]
}
if cmd == nil {
ts.Fatalf("unknown command %q", args[0])
}
cmd(ts, neg, args[1:])
// Command can ask script to stop early.
if ts.stopped {
// Break instead of returning, so that we check the status of any
// background processes and print PASS.
break
}
}
for _, bg := range ts.background {
interruptProcess(bg.cmd.Process)
}
ts.cmdWait(false, nil)
// Final phase ended.
rewind()
markTime()
if !ts.stopped {
fmt.Fprintf(&ts.log, "PASS\n")
}
}
// condition reports whether the given condition is satisfied.
func (ts *TestScript) condition(cond string) (bool, error) {
switch cond {
case "short":
return testing.Short(), nil
case "net":
return testenv.HasExternalNetwork(), nil
case "link":
return testenv.HasLink(), nil
case "symlink":
return testenv.HasSymlink(), nil
case runtime.GOOS, runtime.GOARCH:
return true, nil
default:
if imports.KnownArch[cond] || imports.KnownOS[cond] {
return false, nil
}
if strings.HasPrefix(cond, "exec:") {
prog := cond[len("exec:"):]
ok := execCache.Do(prog, func() interface{} {
_, err := execpath.Look(prog, ts.Getenv)
return err == nil
}).(bool)
return ok, nil
}
if ts.params.Condition != nil {
return ts.params.Condition(cond)
}
ts.Fatalf("unknown condition %q", cond)
panic("unreachable")
}
}
// Helpers for command implementations.
// abbrev abbreviates the actual work directory in the string s to the literal string "$WORK".
func (ts *TestScript) abbrev(s string) string {
s = strings.Replace(s, ts.workdir, "$WORK", -1)
if *testWork {
// Expose actual $WORK value in environment dump on first line of work script,
// so that the user can find out what directory -testwork left behind.
s = "WORK=" + ts.workdir + "\n" + strings.TrimPrefix(s, "WORK=$WORK\n")
}
return s
}
// Defer arranges for f to be called at the end
// of the test. If Defer is called multiple times, the
// defers are executed in reverse order (similar
// to Go's defer statement)
func (ts *TestScript) Defer(f func()) {
old := ts.deferred
ts.deferred = func() {
defer old()
f()
}
}
// Check calls ts.Fatalf if err != nil.
func (ts *TestScript) Check(err error) {
if err != nil {
ts.Fatalf("%v", err)
}
}
// Logf appends the given formatted message to the test log transcript.
func (ts *TestScript) Logf(format string, args ...interface{}) {
format = strings.TrimSuffix(format, "\n")
fmt.Fprintf(&ts.log, format, args...)
ts.log.WriteByte('\n')
}
// exec runs the given command line (an actual subprocess, not simulated)
// in ts.cd with environment ts.env and then returns collected standard output and standard error.
func (ts *TestScript) exec(command string, args ...string) (stdout, stderr string, err error) {
cmd, err := ts.buildExecCmd(command, args...)
if err != nil {
return "", "", err
}
cmd.Dir = ts.cd
cmd.Env = append(ts.env, "PWD="+ts.cd)
cmd.Stdin = strings.NewReader(ts.stdin)
var stdoutBuf, stderrBuf strings.Builder
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
if err = cmd.Start(); err == nil {
err = ctxWait(ts.ctxt, cmd)
}
ts.stdin = ""
return stdoutBuf.String(), stderrBuf.String(), err
}
// execBackground starts the given command line (an actual subprocess, not simulated)
// in ts.cd with environment ts.env.
func (ts *TestScript) execBackground(command string, args ...string) (*exec.Cmd, error) {
cmd, err := ts.buildExecCmd(command, args...)
if err != nil {
return nil, err
}
cmd.Dir = ts.cd
cmd.Env = append(ts.env, "PWD="+ts.cd)
var stdoutBuf, stderrBuf strings.Builder
cmd.Stdin = strings.NewReader(ts.stdin)
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
ts.stdin = ""
return cmd, cmd.Start()
}
func (ts *TestScript) buildExecCmd(command string, args ...string) (*exec.Cmd, error) {
if filepath.Base(command) == command {
if lp, err := execpath.Look(command, ts.Getenv); err != nil {
return nil, err
} else {
command = lp
}
}
return exec.Command(command, args...), nil
}
// BackgroundCmds returns a slice containing all the commands that have
// been started in the background since the most recent wait command, or
// the start of the script if wait has not been called.
func (ts *TestScript) BackgroundCmds() []*exec.Cmd {
cmds := make([]*exec.Cmd, len(ts.background))
for i, b := range ts.background {
cmds[i] = b.cmd
}
return cmds
}
// ctxWait is like cmd.Wait, but terminates cmd with os.Interrupt if ctx becomes done.
//
// This differs from exec.CommandContext in that it prefers os.Interrupt over os.Kill.
// (See https://golang.org/issue/21135.)
func ctxWait(ctx context.Context, cmd *exec.Cmd) error {
errc := make(chan error, 1)
go func() { errc <- cmd.Wait() }()
select {
case err := <-errc:
return err
case <-ctx.Done():
interruptProcess(cmd.Process)
return <-errc
}
}
// interruptProcess sends os.Interrupt to p if supported, or os.Kill otherwise.
func interruptProcess(p *os.Process) {
if err := p.Signal(os.Interrupt); err != nil {
// Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on
// Windows; using it with os.Process.Signal will return an error.”
// Fall back to Kill instead.
p.Kill()
}
}
// Exec runs the given command and saves its stdout and stderr so
// they can be inspected by subsequent script commands.
func (ts *TestScript) Exec(command string, args ...string) error {
var err error
ts.stdout, ts.stderr, err = ts.exec(command, args...)
if ts.stdout != "" {
ts.Logf("[stdout]\n%s", ts.stdout)
}
if ts.stderr != "" {
ts.Logf("[stderr]\n%s", ts.stderr)
}
return err
}
// expand applies environment variable expansion to the string s.
func (ts *TestScript) expand(s string) string {
return os.Expand(s, func(key string) string {
if key1 := strings.TrimSuffix(key, "@R"); len(key1) != len(key) {
return regexp.QuoteMeta(ts.Getenv(key1))
}
return ts.Getenv(key)
})
}
// fatalf aborts the test with the given failure message.
func (ts *TestScript) Fatalf(format string, args ...interface{}) {
fmt.Fprintf(&ts.log, "FAIL: %s:%d: %s\n", ts.file, ts.lineno, fmt.Sprintf(format, args...))
ts.t.FailNow()
}
// MkAbs interprets file relative to the test script's current directory
// and returns the corresponding absolute path.
func (ts *TestScript) MkAbs(file string) string {
if filepath.IsAbs(file) {
return file
}
return filepath.Join(ts.cd, file)
}
// Setenv sets the value of the environment variable named by the key.
func (ts *TestScript) Setenv(key, value string) {
ts.env = append(ts.env, key+"="+value)
ts.envMap[envvarname(key)] = value
}
// Getenv gets the value of the environment variable named by the key.
func (ts *TestScript) Getenv(key string) string {
return ts.envMap[envvarname(key)]
}
// parse parses a single line as a list of space-separated arguments
// subject to environment variable expansion (but not resplitting).
// Single quotes around text disable splitting and expansion.
// To embed a single quote, double it: 'Don''t communicate by sharing memory.'
func (ts *TestScript) parse(line string) []string {
ts.line = line
var (
args []string
arg string // text of current arg so far (need to add line[start:i])
start = -1 // if >= 0, position where current arg text chunk starts
quoted = false // currently processing quoted text
)
for i := 0; ; i++ {
if !quoted && (i >= len(line) || line[i] == ' ' || line[i] == '\t' || line[i] == '\r' || line[i] == '#') {
// Found arg-separating space.
if start >= 0 {
arg += ts.expand(line[start:i])
args = append(args, arg)
start = -1
arg = ""
}
if i >= len(line) || line[i] == '#' {
break
}
continue
}
if i >= len(line) {
ts.Fatalf("unterminated quoted argument")
}
if line[i] == '\'' {
if !quoted {
// starting a quoted chunk
if start >= 0 {
arg += ts.expand(line[start:i])
}
start = i + 1
quoted = true
continue
}
// 'foo''bar' means foo'bar, like in rc shell and Pascal.
if i+1 < len(line) && line[i+1] == '\'' {
arg += line[start:i]
start = i + 1
i++ // skip over second ' before next iteration
continue
}
// ending a quoted chunk
arg += line[start:i]
start = i + 1
quoted = false
continue
}
// found character worth saving; make sure we're saving
if start < 0 {
start = i
}
}
return args
}
func removeAll(dir string) error {
// module cache has 0444 directories;
// make them writable in order to remove content.
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil // ignore errors walking in file system
}
if info.IsDir() {
os.Chmod(path, 0777)
}
return nil
})
return os.RemoveAll(dir)
}
func homeEnvName() string {
switch runtime.GOOS {
case "windows":
return "USERPROFILE"
case "plan9":
return "home"
default:
return "HOME"
}
}
func tempEnvName() string {
switch runtime.GOOS {
case "windows":
return "TMP"
case "plan9":
return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
default:
return "TMPDIR"
}
}
|
[
"\"GOTMPDIR\"",
"\"PATH\"",
"\"SYSTEMROOT\""
] |
[] |
[
"SYSTEMROOT",
"GOTMPDIR",
"PATH"
] |
[]
|
["SYSTEMROOT", "GOTMPDIR", "PATH"]
|
go
| 3 | 0 | |
rak/functionals/utils.py
|
import json
import logging
import os
import subprocess
import time
from dataclasses import MISSING
logger = logging.getLogger("krake.test_utils.run")
KRAKE_HOMEDIR = "/home/krake"
ROK_INSTALL_DIR = f"{KRAKE_HOMEDIR}/.local/bin"
STICKINESS_WEIGHT = 0.1
_ETCD_STATIC_PROVIDER_KEY = "/core/globalmetricsproviders/static_provider"
_ETCDCTL_ENV = {"ETCDCTL_API": "3"}
def kubectl_cmd(kubeconfig):
"""Builds the kubectl command to communicate with the cluster that can be reached by
the provided kubeconfig file.
Args:
kubeconfig (str): path to the kubeconfig file.
Returns:
str: the base kubectl command to use for communicating with the cluster.
"""
return f"kubectl --kubeconfig {kubeconfig}"
class Response(object):
"""The response of a command
Attributes:
output (str): Output of the command
returncode (int): Return code of the command
"""
def __init__(self, output, returncode):
self.output = output
self.returncode = returncode
self._json = MISSING # Cache parsed JSON output
@property
def json(self):
"""str: Deserialized JSON of the command's output"""
if self._json is MISSING:
self._json = json.loads(self.output)
return self._json
def run(command, retry=10, interval=1, condition=None, input=None, env_vars=None):
"""Runs a subprocess
This function runs the provided ``command`` in a subprocess.
Tests are typically subjects to race conditions. We frequently have to
wait for an object to reach a certain state (RUNNING, DELETED, ...)
Therefore, this function implements a retry logic:
- The ``condition`` callable takes the command's response as argument and
checks if it suits a certain format.
- The ``retry`` and ``interval`` arguments control respectively the number
of retries the function should attempt before raising an
`AssertionError`, and the number of seconds to wait between each retry.
The signature of ``condition`` is:
.. function:: my_condition(response)
:param Response response: The command response.
:raises AssertionError: Raised when the condition is not met.
Note that is doesn't make sense to provide a ``condition`` without a
``retry``. One should rather test this condition in the calling function.
Args:
command (list): The command to run
retry (int, optional): Number of retry to perform. Defaults to 10
interval (int, optional): Interval in seconds between two retries
condition (callable, optional): Condition that has to be met.
input (str, optional): input given through stdin to the command.
env_vars (dict[str, str], optional): key-value pairs of additional environment
variables that need to be set. ROK_INSTALL_DIR will always be added
to the PATH.
Returns:
Response: The output and return code of the provided command
Raises:
AssertionError: Raise an exception if the ``condition`` is not met.
Example:
.. code:: python
import util
# This condition will check if the command has a null return
# value
def check_return_code(error_message):
def validate(response):
assert response.returncode == 0, error_message
return validate
# This command has a risk of race condition
some_command = "..."
# The command will be retried 10 time until the command is
# successful or will raise an AssertionError
util.run(
some_command,
condition=check_return_code("error message"),
retry=10,
interval=1,
)
"""
if isinstance(command, str):
command = command.split()
logger.debug(f"Running: {command}")
env = os.environ.copy()
if env_vars:
env.update(env_vars)
env["PATH"] = f"{ROK_INSTALL_DIR}:{env['PATH']}"
while True:
process = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
input=input,
)
response = Response(process.stdout.decode(), process.returncode)
# If no condition has been given to check, simply return the response
if condition is None:
logger.debug(f"Response from the command: \n{response.output}")
return response
try:
condition(response)
# If condition is met, return the response
logger.debug(f"Response from the command: \n{response.output}")
return response
except AssertionError:
# If condition is not met, decrease the amount of retries and sleep
logger.debug("Provided condition is not met")
retry -= 1
if retry <= 0:
# All retries have failed
raise
logger.debug("Going to sleep... will retry")
time.sleep(interval)
def check_app_state(state, error_message, reason=None):
"""Create a callable to verify the state of an Application obtained as response.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the state of the Application is different from the given
one.
Args:
state (str): the state of the answered Application will be compared with this
one.
error_message (str): the message that will be displayed if the check fails.
reason (str): if given, the reason of the Application (in case of FAILED state)
will be compared to this one.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
try:
app_details = response.json
assert app_details["status"]["state"] == state, error_message
if reason:
assert app_details["status"]["reason"]["code"] == reason, error_message
except (KeyError, json.JSONDecodeError):
raise AssertionError(error_message)
return validate
def check_app_created_and_up(error_message=""):
if not error_message:
error_message = "App was not up and running."
err_msg_fmt = error_message + " Error: {details}"
def validate(response):
try:
app_details = response.json
expected_state = "RUNNING"
observed_state = app_details["status"]["state"]
observed_running_on = app_details["status"]["running_on"]
observed_scheduled_to = app_details["status"]["scheduled_to"]
details = (
f"Unable to observe application in a {expected_state} state. "
f"Observed: {observed_state}."
)
assert observed_state == expected_state, err_msg_fmt.format(details=details)
details = (
f"App was in {expected_state} state but its running_on "
f"was {observed_running_on}."
)
assert observed_running_on, err_msg_fmt % {"details": details}
details = (
f"App was in {expected_state} state but its scheduled_to "
f"was {observed_scheduled_to}."
)
assert observed_scheduled_to, err_msg_fmt % {"details": details}
except (KeyError, json.JSONDecodeError) as e:
raise AssertionError(err_msg_fmt % {"details": str(e)})
return validate
def check_metrics_provider_content(error_message, name, type, type_details=None):
"""Create a callable to verify the content of a metrics provider in a response
from the krake API.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the content of the metrics provider in the
response is different from the given one.
Args:
error_message (str): the message that will be displayed if the check fails.
name (str): the expected name of the metrics provider
type (str): the expected type of the metrics provider
type_details (str): the expected details of the metrics provider, i.e.,
the value of spec.<type>.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
Raises:
AssertionError: if the content of the metrics provider in the response is
different from the given one.
"""
assert type in ["prometheus", "static", "kafka"], (
error_message + f" Invalid mp type '{type}'."
)
assert type_details, error_message + " No type_details were provided."
expected_mp = {
"api": "core",
"kind": "GlobalMetricsProvider",
"metadata": {"name": name},
"spec": {"type": type, type: type_details},
}
def validate(response):
observed_mp = response.json
details = (
f"\nExpected spec: {expected_mp['spec']}.\n"
f"Observed: {observed_mp['spec']}."
)
assert observed_mp["spec"] == expected_mp["spec"], error_message + details
details = (
f"\nExpected name: {name}.\nObserved: {observed_mp['metadata']['name']}."
)
assert observed_mp["metadata"]["name"] == name, error_message + details
return validate
def check_metric_content(error_message, name, mp_name, min, max, mp_metric_name=None):
"""Create a callable to verify the content of a metric in a response from the
krake API.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the content of the metric in the response is different
from the given one.
Args:
error_message (str): message that will be displayed if the check fails.
name (str): expected name of the metric
mp_name (str): expected name of the metric's metrics provider
mp_metric_name (str): expected name of the metric's metrics provider's metric
min (float): expected minimum value of the metric
max (float): expected maximum value of the metric
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
Raises:
AssertionError: if the content of the metric in the response is different
from the given one.
"""
if not mp_metric_name:
mp_metric_name = name
expected_metric = {
"api": "core",
"kind": "GlobalMetric",
"metadata": {"name": name},
"spec": {
"max": float(max),
"min": float(min),
"provider": {"metric": mp_metric_name, "name": mp_name},
},
}
def validate(response):
observed_metric = response.json
details = (
f"\nExpected spec: {expected_metric['spec']}.\n"
f"Observed: {observed_metric['spec']}."
)
assert observed_metric["spec"] == expected_metric["spec"], (
error_message + details
)
details = (
f"\nExpected name: {name}."
f"\nObserved: {observed_metric['metadata']['name']}."
)
assert observed_metric["metadata"]["name"] == name, error_message + details
return validate
def check_return_code(error_message, expected_code=0):
"""Create a callable to verify the return code of a response.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the return code of the response is different from the
given one.
Args:
error_message (str): the message that will be displayed if the check fails.
expected_code (int, optional): a bash return code, to check against the one of
the given response.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
details = (
f" Expected return code: {expected_code}."
f" Observed return code: {response.returncode}."
)
assert response.returncode == expected_code, error_message + details
return validate
def check_status_code(response, expected_code=200):
"""Presents a function to validate the status code of a requests response object.
Args:
response (requests.Response): the response object, that will be checked.
expected_code (int, optional): a http return code, to check against the one of
the given response.
"""
error_message = (
f" Expected return code: {expected_code}."
f" Observed return code: {response.status_code}."
)
assert response.status_code == expected_code, error_message
def check_empty_list(error_message):
"""Create a callable to verify that a response is empty.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the response is not an empty list.
Args:
error_message (str): the message that will be displayed if the check fails.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
try:
assert response.json == [], error_message
except json.JSONDecodeError:
raise AssertionError(error_message)
return validate
def check_resource_exists(error_message=""):
"""Create a callable to verify that a resource exists.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the chosen resource does not exist.
Args:
error_message (str, optional): the message that will be displayed on failure.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
assert response.returncode == 0
assert "Error 404" not in response.output, error_message
assert "not found" not in response.output, error_message
return validate
def check_resource_deleted(error_message):
"""Create a callable to verify that a resource is deleted.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the chosen resource is shown as existing in the response
given to the callable
Args:
error_message (str): the message that will be displayed if the check fails.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
assert "not found" in response.output, error_message
assert response.returncode == 1
return validate
def check_spec_container_image(expected_image, error_message):
"""Create a callable to verify that a resource has the right container image.
To be used with the :meth:`run` function and a kubectl request. The callable will
raise an :class:`AssertionError` if the response's image is not the given one. This
image corresponds to the image name of the first container of the spec of the
template of a deployment.
Args:
expected_image (str): name of the image that should be defined in the response.
error_message (str): the message that will be displayed if the check fails.
Returns:
"""
def validate(response):
try:
image = response.json["spec"]["template"]["spec"]["containers"][0]["image"]
assert image == expected_image, error_message
except json.JSONDecodeError:
raise AssertionError(error_message)
return validate
def check_spec_replicas(expected_replicas, error_message):
"""Create a callable to verify that a resource has the correct number of replicas.
To be used with the :meth:`run` function and a kubectl request. The callable will
raise an :class:`AssertionError` if the response's number of replicas is not
the given one. The number of replicas corresponds to the replicas in the spec
of the deployment.
Args:
expected_replicas (int): number of replicas expected to be defined in the
response.
error_message (str): the message that will be displayed if the check fails.
Returns:
"""
def validate(response):
try:
replicas = response.json["spec"]["replicas"]
assert replicas == expected_replicas, error_message
except json.JSONDecodeError:
raise AssertionError(error_message)
return validate
def check_app_running_on(expected_cluster, error_message):
"""Create a callable to verify the cluster on which an Application is
running obtained as a response.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the state of the Application is different
from the given one.
Args:
expected_cluster (str): the name of the cluster on which the
Application is expected to be running.
error_message (str): the message that will be displayed if the
check fails.
Returns:
callable: a condition that will check its given response against
the parameters of the current function.
"""
def validate(response):
try:
app_details = response.json
running_on_dict = app_details["status"]["running_on"] or {}
running_on = running_on_dict.get("name", None)
scheduled_to_dict = app_details["status"]["scheduled_to"] or {}
scheduled_to = scheduled_to_dict.get("name", None)
msg = (
error_message + f" App state: {app_details['status']['state']}, "
f"App scheduled_to: {scheduled_to}, "
f"App running_on: {running_on}"
)
assert running_on == expected_cluster, msg
except (KeyError, json.JSONDecodeError):
raise AssertionError(error_message)
return validate
def allow_404(response):
"""Check that the response given succeeded, or if it did not succeed, that the
output shows a "404" HTTP error.
Args:
response (Response): the response to check
Raises:
AssertionError: if the response failed, but not from a "404" error.
"""
error_message = (
f"The response got an error code different from 404: {response.output}"
)
if response.returncode != 0:
assert "404" in response.output, error_message
def check_http_code_in_output(http_code, error_message=None):
"""Create a callable to ensure that the given HTTP error code is present in the
output of the response.
Args:
http_code (int): the HTTP error code to check.
error_message (str, optional): the message that will be displayed if the check
fails.
Returns:
callable: a condition that will check its given response against the parameters
of the current function.
"""
def validate(response):
message = error_message
if message is None:
message = (
f"The response got an HTTP code different"
f"from {http_code}: {response.output}"
)
assert str(http_code) in response.output, message
return validate
def get_scheduling_score(cluster, values, weights, scheduled_to=None):
"""Get the scheduling cluster score for the cluster (including stickiness).
Args:
cluster (str): cluster name
values (dict[str, float]): Dictionary of the metric values. The dictionary keys
are the names of the metrics and the dictionary values the metric values.
weights (dict[str, dict[str, float]]): Dictionary of cluster weights.
The keys are the names of the clusters and each value is a dictionary in
itself, with the metric names as keys and the cluster's weights as values.
scheduled_to (str): name of the cluster to which the application being
scheduled has been scheduled.
Returns:
float: The score of the given cluster.
"""
# Sanity check: Check that the metrics (i.e., the keys) are the same in both lists
assert len(values) == len(weights[cluster])
assert all(metric in weights[cluster] for metric in values)
rank = sum(values[metric] * weights[cluster][metric] for metric in values)
norm = sum(weights[cluster][metric] for metric in weights[cluster])
if scheduled_to == cluster:
stickiness_value = 1
rank += STICKINESS_WEIGHT * stickiness_value
norm += STICKINESS_WEIGHT
return rank / norm
def _put_etcd_entry(data, key):
"""Put `data` as the value of the key `key` in the etcd store.
Args:
data (object): The data to put
key (str): the key to update.
"""
data_str = json.dumps(data)
put_cmd = ["etcdctl", "put", key, "--", data_str]
run(command=put_cmd, env_vars=_ETCDCTL_ENV)
def _get_etcd_entry(key, condition=None):
"""Retrieve the value of the key `key` from the etcd store.
This method calls run to perform the actual command.
Args:
key (str): the key to retrieve from the db.
condition (callable, optional): a callable. This will be passed to run()
as its `condition` parameter.
Returns:
object: Value of the key `key` in the etcd database, parsed by json.
"""
get_cmd = ["etcdctl", "get", key, "--print-value-only"]
resp = run(command=get_cmd, condition=condition, env_vars=_ETCDCTL_ENV)
try:
return resp.json
except Exception as e:
msg = f"Failed to load response '{resp}'. Error: {e}"
raise AssertionError(msg)
def get_static_metrics():
"""Retrieve metrics from the etcd database.
Returns:
dict[str, float]
Dict with the metrics names as keys and metric values as values.
"""
static_provider = _get_etcd_entry(_ETCD_STATIC_PROVIDER_KEY)
return static_provider["spec"]["static"]["metrics"]
def set_static_metrics(values):
"""Modify the database entry for the static metrics provider by setting its
values to the provided metrics.
Args:
values (dict[str, float]): Dictionary with the metrics names as keys and
metric values as values.
"""
static_provider = _get_etcd_entry(_ETCD_STATIC_PROVIDER_KEY)
# sanity check that we are only modifying existing metrics
old_metrics = static_provider["spec"]["static"]["metrics"]
assert all([metric in old_metrics for metric in values])
# set the new values
static_provider["spec"]["static"]["metrics"].update(values)
# update database with the updated static_provider
_put_etcd_entry(static_provider, key=_ETCD_STATIC_PROVIDER_KEY)
# make sure the changing of the values took place
_get_etcd_entry(_ETCD_STATIC_PROVIDER_KEY, condition=check_static_metrics(values))
def check_static_metrics(expected_metrics, error_message=""):
"""Create a callable to verify that the static provider response contains
the expected values.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the static metrics in the response are different
from the given ones.
Args:
expected_metrics (dict[str, float]): Dictionary with the metrics names as
keys and metric values as values.
error_message (str): the message that will be displayed if the
check fails.
Returns:
callable: a condition that will check its given response against
the parameters of the current function.
"""
if not error_message:
error_message = (
f"The static provider did not provide the expected "
f"metrics. Expected metrics: {expected_metrics}"
)
def validate(response):
try:
observed_metrics = response.json["spec"]["static"]["metrics"]
msg = error_message + f" Provided metrics: {observed_metrics}"
for m, val in expected_metrics.items():
assert val == observed_metrics.get(m), msg
except Exception as e:
raise AssertionError(error_message + f"Error: {e}")
return validate
def get_other_cluster(this_cluster, clusters):
"""Return the cluster in clusters, which is not this_cluster.
Args:
this_cluster (str): name of this_cluster
clusters (list): list of two cluster names.
Returns:
the name of the other cluster.
"""
return clusters[0] if clusters[1] == this_cluster else clusters[1]
def create_cluster_info(cluster_names, sub_keys, values):
"""
Convenience method for preparing the input parameters cluster_labels and metrics
of `create_default_environment()`.
The sub-keys can for example be thought of as
metric names (and `values` their weights) or
cluster label names (and `values` their values).
Example:
Sample input:
cluster_names = ["cluster1", "cluster2", "cluster3"]
sub_keys = ["m1", "m2"]
values = [3, 4]
Return value:
{
"cluster1": {
"m1": 3,
},
"cluster2": {
"m2": 4,
},
"cluster3": {},
}
If sub_keys is not a list, the list will be constructed as follows:
sub_keys = [sub_keys] * len(values)
This is useful when the sub-key should be the same for all clusters.
The ith cluster will get the ith sub-key with the ith value.
Caveat: If there are fewer sub-keys and values than clusters,
the last cluster(s) will not become any <sub-key, value> pairs at all.
Limitation:
Each cluster can only have one <sub-key, value> pair using this method.
Args:
cluster_names (list[str]): The keys in the return dict.
sub_keys: The keys in the second level dicts in the return dict.
If type(sub_keys) isn't list, a list will be created as such:
sub_keys = [sub_keys] * len(values)
values (list): The values in the second level dicts in the return dict.
Returns:
dict[str, dict] with same length as cluster_names.
The first `len(values)` <key, value> pairs will be:
cluster_names[i]: {sub_keys[i]: values[i]}
The last `len(cluster_names) - len(values)` <key: value> pairs will be:
cluster_names[i]: {}
Asserts:
len(cluster_names) >= len(values)
len(sub_keys) == len(values) if type(sub_keys) is list
"""
if not type(sub_keys) is list:
sub_keys = [sub_keys] * len(values)
assert len(cluster_names) >= len(values)
assert len(sub_keys) == len(values)
cluster_dicts = [{sub_keys[i]: values[i]} for i in range(len(values))]
cluster_dicts += [{}] * (len(cluster_names) - len(values))
return dict(zip(cluster_names, cluster_dicts))
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
logger.go
|
package golambda
import (
"io"
"os"
"strings"
"github.com/rs/zerolog"
)
// LambdaLogger provides basic logging features for Lambda function. golambda.Logger is configured by default as global variable of golambda.
type LambdaLogger struct {
zeroLogger zerolog.Logger
}
// NewLambdaLogger returns a new LambdaLogger.
// NOTE: golambda.Logger is recommended for general usage.
func NewLambdaLogger(logLevel string) *LambdaLogger {
var zeroLogLevel zerolog.Level
switch strings.ToLower(logLevel) {
case "trace":
zeroLogLevel = zerolog.TraceLevel
case "debug":
zeroLogLevel = zerolog.DebugLevel
case "info":
zeroLogLevel = zerolog.InfoLevel
case "warn":
zeroLogLevel = zerolog.WarnLevel
case "error":
zeroLogLevel = zerolog.ErrorLevel
default:
zeroLogLevel = zerolog.InfoLevel
}
var writer io.Writer = zerolog.ConsoleWriter{Out: os.Stdout}
if _, ok := os.LookupEnv("AWS_LAMBDA_FUNCTION_NAME"); ok {
// If running on AWS Lambda
writer = os.Stdout
}
logger := zerolog.New(writer).Level(zeroLogLevel).With().Timestamp().Logger()
return &LambdaLogger{
zeroLogger: logger,
}
}
// LogEntry is one record of logging. Trace, Debug, Info and Error methods emit message and values
type LogEntry struct {
logger *LambdaLogger
values map[string]interface{}
}
// Entry returns a new LogEntry
func (x *LambdaLogger) Entry() *LogEntry {
return &LogEntry{
logger: x,
values: make(map[string]interface{}),
}
}
// Trace output log as Trace level message
func (x *LambdaLogger) Trace(msg string) { x.Entry().Trace(msg) }
// Debug output log as Debug level message
func (x *LambdaLogger) Debug(msg string) { x.Entry().Debug(msg) }
// Info output log as Info level message
func (x *LambdaLogger) Info(msg string) { x.Entry().Info(msg) }
// Warn output log as Warning level message
func (x *LambdaLogger) Warn(msg string) { x.Entry().Warn(msg) }
// Error output log as Error level message
func (x *LambdaLogger) Error(msg string) { x.Entry().Error(msg) }
// Set saves key and value to logger. The key and value are output permanently
func (x *LambdaLogger) Set(key string, value interface{}) {
x.zeroLogger = x.zeroLogger.With().Interface(key, value).Logger()
}
// With adds key and value to log message. Value will be represented by zerolog.Interface
func (x *LambdaLogger) With(key string, value interface{}) *LogEntry {
entry := x.Entry()
entry.values[key] = value
return entry
}
// With saves key and value into own and return own pointer.
func (x *LogEntry) With(key string, value interface{}) *LogEntry {
x.values[key] = value
return x
}
func (x *LogEntry) bind(ev *zerolog.Event) {
for k, v := range x.values {
ev.Interface(k, v)
}
}
// Trace emits log message as trace level.
func (x *LogEntry) Trace(msg string) {
ev := x.logger.zeroLogger.Trace()
x.bind(ev)
ev.Msg(msg)
}
// Debug emits log message as debug level.
func (x *LogEntry) Debug(msg string) {
ev := x.logger.zeroLogger.Debug()
x.bind(ev)
ev.Msg(msg)
}
// Info emits log message as info level.
func (x *LogEntry) Info(msg string) {
ev := x.logger.zeroLogger.Info()
x.bind(ev)
ev.Msg(msg)
}
// Warn emits log message as Warn level.
func (x *LogEntry) Warn(msg string) {
ev := x.logger.zeroLogger.Warn()
x.bind(ev)
ev.Msg(msg)
}
// Error emits log message as error level.
func (x *LogEntry) Error(msg string) {
ev := x.logger.zeroLogger.Error()
x.bind(ev)
ev.Msg(msg)
}
// Logger is common logging interface
var Logger *LambdaLogger
// InitLogger configures logger
func initLogger() {
logLevel := os.Getenv("LOG_LEVEL")
Logger = NewLambdaLogger(logLevel)
}
|
[
"\"LOG_LEVEL\""
] |
[] |
[
"LOG_LEVEL"
] |
[]
|
["LOG_LEVEL"]
|
go
| 1 | 0 | |
store/redis/redis.go
|
package redis
import (
"context"
"fmt"
"os"
redis "github.com/go-redis/redis/v8"
)
const localhost = "127.0.0.1:6379"
// New returns a checkpoint that uses Redis for underlying storage
func New(appName string, opts ...Option) (*Checkpoint, error) {
if appName == "" {
return nil, fmt.Errorf("must provide app name")
}
c := &Checkpoint{
appName: appName,
}
// override defaults
for _, opt := range opts {
opt(c)
}
// default client if none provided
if c.client == nil {
addr := os.Getenv("REDIS_URL")
if addr == "" {
addr = localhost
}
client := redis.NewClient(&redis.Options{Addr: addr})
c.client = client
}
// verify we can ping server
_, err := c.client.Ping(context.Background()).Result()
if err != nil {
return nil, err
}
return c, nil
}
// Checkpoint stores and retreives the last evaluated key from a DDB scan
type Checkpoint struct {
appName string
client *redis.Client
}
// GetCheckpoint fetches the checkpoint for a particular Shard.
func (c *Checkpoint) GetCheckpoint(streamName, shardID string) (string, error) {
ctx := context.Background()
val, _ := c.client.Get(ctx, c.key(streamName, shardID)).Result()
return val, nil
}
// SetCheckpoint stores a checkpoint for a shard (e.g. sequence number of last record processed by application).
// Upon failover, record processing is resumed from this point.
func (c *Checkpoint) SetCheckpoint(streamName, shardID, sequenceNumber string) error {
if sequenceNumber == "" {
return fmt.Errorf("sequence number should not be empty")
}
ctx := context.Background()
err := c.client.Set(ctx, c.key(streamName, shardID), sequenceNumber, 0).Err()
if err != nil {
return err
}
return nil
}
// key generates a unique Redis key for storage of Checkpoint.
func (c *Checkpoint) key(streamName, shardID string) string {
return fmt.Sprintf("%v:checkpoint:%v:%v", c.appName, streamName, shardID)
}
|
[
"\"REDIS_URL\""
] |
[] |
[
"REDIS_URL"
] |
[]
|
["REDIS_URL"]
|
go
| 1 | 0 | |
pkg/gateway/api/oauth2/oauth2.go
|
package oauth2
import (
"context"
"errors"
"fmt"
"github.com/ShuzZzle/cortex-gateway/pkg/gateway/api/v1/models"
"github.com/ShuzZzle/cortex-gateway/pkg/gateway/database"
"github.com/ShuzZzle/cortex-gateway/pkg/gateway/util"
"github.com/coreos/go-oidc"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/oauth2"
"net/http"
"net/url"
"os"
"strings"
)
type Configuration struct {
providerURL string
oauth2Config oauth2.Config
oidcConfig *oidc.Config
verifier *oidc.IDTokenVerifier
database *database.Database
}
type JWTClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
}
func GetAccessToken(ctx *gin.Context) (string, error){
header := ctx.GetHeader("Authorization")
if header != "" {
parts := strings.Split(header, " ")
if len(parts) != 2 {
ctx.Writer.WriteHeader(http.StatusBadRequest)
return "", errors.New("invalid token")
}
return parts[1], nil
}
cookie, err := ctx.Cookie("key")
return cookie, err
}
func SetAccessToken(ctx *gin.Context, token string) {
ctx.SetCookie("key", token, 180, "/", "localhost", true, true)
}
func PushRedirect(uri string, redirect string) string {
return fmt.Sprintf("%s?redirect_uri=%s", uri, url.QueryEscape(redirect))
}
func PopRedirect(uri string) (string, error) {
from, err := url.Parse(uri)
if err != nil {
return "", err
}
return from.Query().Get("redirect_uri"), nil
}
func (config *Configuration) Authenticate() gin.HandlerFunc {
return func(ctx *gin.Context) {
redirectUri := ctx.Request.RequestURI
accessToken, err := GetAccessToken(ctx)
if err != nil {
ctx.Redirect(http.StatusFound, PushRedirect("/api/login", redirectUri))
ctx.Abort()
return
}
_, err = config.verifier.Verify(ctx, accessToken)
if err != nil {
fmt.Println(err)
ctx.Redirect(http.StatusFound, PushRedirect("/api/login", redirectUri))
ctx.Abort()
return
}
ctx.Next()
}
}
func (config *Configuration) Metadata(ctx *gin.Context) {
logoutUrl := fmt.Sprintf("%s/.well-known/openid-configuration", config.providerURL)
ctx.Redirect(http.StatusFound, logoutUrl)
}
func (config *Configuration) Login(ctx *gin.Context) {
accessToken, err := GetAccessToken(ctx)
state := util.RandStringRunes(16)
ctx.SetCookie("oauth2_state", state, 180, "/", "localhost", true, true)
redirectUri := ctx.Query("redirect_uri")
config.oauth2Config.RedirectURL = PushRedirect("http://localhost:8080/api/callback", redirectUri)
if accessToken == "" {
ctx.Redirect(http.StatusFound, config.oauth2Config.AuthCodeURL(state))
return
}
_, err = config.verifier.Verify(ctx, accessToken)
if err != nil {
ctx.Redirect(http.StatusFound, config.oauth2Config.AuthCodeURL(state))
return
}
ctx.Redirect(http.StatusFound, ctx.Request.Referer())
}
func (config *Configuration) Logout(ctx *gin.Context) {
redirectUri := ctx.Query("redirect_uri")
if redirectUri == "" {
redirectUri = "http://localhost:8080/ui"
}
logoutUrl := fmt.Sprintf("%s/protocol/openid-connect/logout?redirect_uri=%s", config.providerURL, url.QueryEscape(redirectUri))
ctx.Redirect(http.StatusFound, logoutUrl)
}
func (config *Configuration) GetUser(ctx *gin.Context, email string) {
session := sessions.Default(ctx)
// Try to find User by email
userEntity := models.NewUserEntity(config.database.MongoDatabase)
user, err := userEntity.Read(email)
if err == mongo.ErrNoDocuments {
// Create User
user, err = userEntity.Create(email)
if err != nil {
// Error creating User
fmt.Println(err)
}
} else {
// Something bad happened
fmt.Println(err)
}
session.Set("user", user)
session.Save()
}
func (config *Configuration) Callback(ctx *gin.Context) {
r := ctx.Request
w := ctx.Writer
// Verify State
// SEE: https://datatracker.ietf.org/doc/html/rfc6819
// OR: https://datatracker.ietf.org/doc/html/rfc6749#section-10.12
// Prevents CSRF Attacks
cookie, err := ctx.Cookie("oauth2_state")
if err != nil {
http.Error(w, "error extracting cookie oauth2_state", http.StatusInternalServerError)
return
}
if r.URL.Query().Get("state") != cookie {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
oauth2Token, err := config.oauth2Config.Exchange(ctx, r.URL.Query().Get("code"))
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
return
}
idToken, err := config.verifier.Verify(ctx, rawIDToken)
if err != nil {
http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
return
}
idtokenClaims := JWTClaims{}
resp := struct {
OAuth2Token *oauth2.Token
IDTokenClaims *JWTClaims // ID Token payload is just JSON.
}{oauth2Token, &idtokenClaims}
if err = idToken.Claims(&resp.IDTokenClaims); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println(idtokenClaims.Email)
session := sessions.Default(ctx)
if _, userCookieFound := session.Get("user").(models.User); !userCookieFound {
//TODO: Do this everytime?!
config.GetUser(ctx, "")
}
SetAccessToken(ctx, oauth2Token.AccessToken)
redirectUri := ctx.Query("redirect_uri")
ctx.Redirect(http.StatusFound, redirectUri)
}
func NewAuthConfiguration(db *database.Database) *Configuration {
ctx := context.Background()
providerURL := fmt.Sprintf("%s/auth/realms/cortex-gateway", os.Getenv("KEYCLOAK_PROVIDER_URL"))
provider, err := oidc.NewProvider(ctx, providerURL)
if err != nil {
panic(err)
}
oidcConfig := &oidc.Config{ClientID: "cortex-gateway"}
verifier := provider.Verifier(oidcConfig)
return &Configuration{
providerURL: providerURL,
oidcConfig: oidcConfig,
verifier: verifier,
database: db,
oauth2Config: struct {
ClientID string
ClientSecret string
Endpoint oauth2.Endpoint
RedirectURL string
Scopes []string
}{ClientID: oidcConfig.ClientID, ClientSecret: os.Getenv("CLIENT_SECRET"), Endpoint: provider.Endpoint(), RedirectURL: "http://localhost:8080/api/callback", Scopes: []string{oidc.ScopeOpenID, "email", "profile"}},
}
}
|
[
"\"KEYCLOAK_PROVIDER_URL\"",
"\"CLIENT_SECRET\""
] |
[] |
[
"KEYCLOAK_PROVIDER_URL",
"CLIENT_SECRET"
] |
[]
|
["KEYCLOAK_PROVIDER_URL", "CLIENT_SECRET"]
|
go
| 2 | 0 | |
napari/__main__.py
|
"""
napari command line viewer.
"""
import argparse
import logging
import os
import runpy
import sys
import warnings
from ast import literal_eval
from pathlib import Path
from textwrap import wrap
from typing import Any, Dict, List
class InfoAction(argparse.Action):
def __call__(self, *args, **kwargs):
# prevent unrelated INFO logs when doing "napari --info"
from napari.utils import sys_info
logging.basicConfig(level=logging.WARNING)
print(sys_info())
from .plugins import plugin_manager
plugin_manager.discover_widgets()
errors = plugin_manager.get_errors()
if errors:
names = {e.plugin_name for e in errors}
print("\n‼️ Errors were detected in the following plugins:")
print("(Run 'napari --plugin-info -v' for more details)")
print("\n".join(f" - {n}" for n in names))
sys.exit()
class PluginInfoAction(argparse.Action):
def __call__(self, *args, **kwargs):
# prevent unrelated INFO logs when doing "napari --info"
logging.basicConfig(level=logging.WARNING)
from .plugins import plugin_manager
plugin_manager.discover_widgets()
print(plugin_manager)
errors = plugin_manager.get_errors()
if errors:
print("‼️ Some errors occurred:")
verbose = '-v' in sys.argv or '--verbose' in sys.argv
if not verbose:
print(" (use '-v') to show full tracebacks")
print("-" * 38)
for err in errors:
print(err.plugin_name)
print(f" error: {err!r}")
print(f" cause: {err.__cause__!r}")
if verbose:
print(" traceback:")
import traceback
from textwrap import indent
tb = traceback.format_tb(err.__cause__.__traceback__)
print(indent("".join(tb), ' '))
sys.exit()
class CitationAction(argparse.Action):
def __call__(self, *args, **kwargs):
# prevent unrelated INFO logs when doing "napari --citation"
from napari.utils import citation_text
logging.basicConfig(level=logging.WARNING)
print(citation_text)
sys.exit()
def validate_unknown_args(unknown: List[str]) -> Dict[str, Any]:
"""Convert a list of strings into a dict of valid kwargs for add_* methods.
Will exit program if any of the arguments are unrecognized, or are
malformed. Converts string to python type using literal_eval.
Parameters
----------
unknown : List[str]
a list of strings gathered as "unknown" arguments in argparse.
Returns
-------
kwargs : Dict[str, Any]
{key: val} dict suitable for the viewer.add_* methods where ``val``
is a ``literal_eval`` result, or string.
"""
from napari.components.viewer_model import valid_add_kwargs
out: Dict[str, Any] = dict()
valid = set.union(*valid_add_kwargs().values())
for i, arg in enumerate(unknown):
if not arg.startswith("--"):
continue
if "=" in arg:
key, value = arg.split("=", maxsplit=1)
else:
key = arg
key = key.lstrip('-').replace("-", "_")
if key not in valid:
sys.exit(f"error: unrecognized arguments: {arg}")
if "=" not in arg:
try:
value = unknown[i + 1]
if value.startswith("--"):
raise IndexError()
except IndexError:
sys.exit(f"error: argument {arg} expected one argument")
try:
value = literal_eval(value)
except Exception:
value = value
out[key] = value
return out
def parse_sys_argv():
"""Parse command line arguments."""
from napari import __version__, layers
from napari.components.viewer_model import valid_add_kwargs
kwarg_options = []
for layer_type, keys in valid_add_kwargs().items():
kwarg_options.append(f" {layer_type.title()}:")
keys = {k.replace('_', '-') for k in keys}
lines = wrap(", ".join(sorted(keys)), break_on_hyphens=False)
kwarg_options.extend([f" {line}" for line in lines])
parser = argparse.ArgumentParser(
usage=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="optional layer-type-specific arguments (precede with '--'):\n"
+ "\n".join(kwarg_options),
)
parser.add_argument('paths', nargs='*', help='path(s) to view.')
parser.add_argument(
'-v',
'--verbose',
action='count',
default=0,
help="increase output verbosity",
)
parser.add_argument(
'-w',
'--with',
dest='with_',
nargs='+',
metavar=('PLUGIN_NAME', 'WIDGET_NAME'),
help=(
"open napari with dock widget from specified plugin name."
"(If plugin provides multiple dock widgets, widget name must also "
"be provided)"
),
)
parser.add_argument(
'--version',
action='version',
version=f'napari version {__version__}',
)
parser.add_argument(
'--info',
action=InfoAction,
nargs=0,
help='show system information and exit',
)
parser.add_argument(
'--plugin-info',
action=PluginInfoAction,
nargs=0,
help='show information about plugins and exit',
)
parser.add_argument(
'--citation',
action=CitationAction,
nargs=0,
help='show citation information and exit',
)
parser.add_argument(
'--stack',
action='store_true',
help='concatenate multiple input files into a single stack.',
)
parser.add_argument(
'--plugin',
help='specify plugin name when opening a file',
)
parser.add_argument(
'--layer-type',
metavar="TYPE",
choices=set(layers.NAMES),
help=(
'force file to be interpreted as a specific layer type. '
f'one of {set(layers.NAMES)}'
),
)
parser.add_argument(
'--reset',
action='store_true',
help='reset settings to default values.',
)
parser.add_argument(
'--settings-path',
type=Path,
help='use specific path to store and load settings.',
)
args, unknown = parser.parse_known_args()
# this is a hack to allow using "=" as a key=value separator while also
# allowing nargs='*' on the "paths" argument...
for idx, item in enumerate(reversed(args.paths)):
if item.startswith("--"):
unknown.append(args.paths.pop(len(args.paths) - idx - 1))
kwargs = validate_unknown_args(unknown) if unknown else {}
return args, kwargs
def _run():
from napari import run, view_path
from napari.settings import get_settings
"""Main program."""
args, kwargs = parse_sys_argv()
# parse -v flags and set the appropriate logging level
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
level = levels[min(2, args.verbose)] # prevent index error
logging.basicConfig(
level=level,
format="%(asctime)s %(levelname)s %(message)s",
datefmt='%H:%M:%S',
)
if args.reset:
if args.settings_path:
settings = get_settings(path=args.settings_path)
else:
settings = get_settings()
settings.reset()
settings.save()
sys.exit("Resetting settings to default values.\n")
if args.plugin:
# make sure plugin is only used when files are specified
if not args.paths:
sys.exit(
"error: The '--plugin' argument is only valid "
"when providing a file name"
)
# I *think* that Qt is looking in sys.argv for a flag `--plugins`,
# which emits "WARNING: No such plugin for spec 'builtins'"
# so remove --plugin from sys.argv to prevent that warningz
sys.argv.remove('--plugin')
if any(p.endswith('.py') for p in args.paths):
# we're running a script
if len(args.paths) > 1:
sys.exit(
'When providing a python script, only a '
'single positional argument may be provided'
)
# run the file
mod = runpy.run_path(args.paths[0])
from napari_plugin_engine.markers import HookImplementationMarker
# if this file had any hook implementations, register and run as plugin
if any(isinstance(i, HookImplementationMarker) for i in mod.values()):
_run_plugin_module(mod, os.path.basename(args.paths[0]))
else:
if args.with_:
from .plugins import plugin_manager
# if a plugin widget has been requested, this will fail immediately
# if the requested plugin/widget is not available.
plugin_manager.discover_widgets()
pname, *wnames = args.with_
if wnames:
for wname in wnames:
plugin_manager.get_widget(pname, wname)
else:
plugin_manager.get_widget(pname)
from napari._qt.widgets.qt_splash_screen import NapariSplashScreen
splash = NapariSplashScreen()
splash.close() # will close once event loop starts
# viewer is unused but _must_ be kept around.
# it will be referenced by the global window only
# once napari has finished starting
# but in the meantime if the garbage collector runs;
# it will collect it and hang napari at start time.
# in a way that is machine, os, time (and likely weather dependant).
viewer = view_path( # noqa: F841
args.paths,
stack=args.stack,
plugin=args.plugin,
layer_type=args.layer_type,
**kwargs,
)
if args.with_:
pname, *wnames = args.with_
if wnames:
for wname in wnames:
viewer.window.add_plugin_dock_widget(pname, wname)
else:
viewer.window.add_plugin_dock_widget(pname)
run(gui_exceptions=True)
def _run_plugin_module(mod, plugin_name):
"""Register `mod` as a plugin, find/create viewer, and run napari."""
from napari import Viewer, run
from napari.plugins import plugin_manager
plugin_manager.register(mod, name=plugin_name)
# now, check if a viewer was created, and if not, create one.
for obj in mod.values():
if isinstance(obj, Viewer):
_v = obj
break
else:
_v = Viewer()
try:
_v.window._qt_window.parent()
except RuntimeError:
# this script had a napari.run() in it, and the viewer has already been
# used and cleaned up... if we eventually have "reusable viewers", we
# can continue here
return
# finally, if the file declared a dock widget, add it to the viewer.
dws = plugin_manager.hooks.napari_experimental_provide_dock_widget
if any(i.plugin_name == plugin_name for i in dws.get_hookimpls()):
_v.window.add_plugin_dock_widget(plugin_name)
run()
def _run_pythonw(python_path):
"""Execute this script again through pythonw.
This can be used to ensure we're using a framework
build of Python on macOS, which fixes frozen menubar issues.
Parameters
----------
python_path : pathlib.Path
Path to python framework build.
"""
import subprocess
cwd = Path.cwd()
cmd = [python_path, '-m', 'napari']
env = os.environ.copy()
# Append command line arguments.
if len(sys.argv) > 1:
cmd.extend(sys.argv[1:])
result = subprocess.run(cmd, env=env, cwd=cwd)
sys.exit(result.returncode)
def main():
# Ensure we're always using a "framework build" on the latest
# macOS to ensure menubar works without needing to refocus napari.
# We try this for macOS later than the Catelina release
# See https://github.com/napari/napari/pull/1554 and
# https://github.com/napari/napari/issues/380#issuecomment-659656775
# and https://github.com/ContinuumIO/anaconda-issues/issues/199
import platform
from distutils.version import StrictVersion
_MACOS_AT_LEAST_CATALINA = sys.platform == "darwin" and StrictVersion(
platform.release()
) > StrictVersion('19.0.0')
_MACOS_AT_LEAST_BIG_SUR = sys.platform == "darwin" and StrictVersion(
platform.release()
) > StrictVersion('20.0.0')
_RUNNING_CONDA = "CONDA_PREFIX" in os.environ
_RUNNING_PYTHONW = "PYTHONEXECUTABLE" in os.environ
# quick fix for Big Sur py3.9
if _MACOS_AT_LEAST_BIG_SUR:
os.environ['QT_MAC_WANTS_LAYER'] = '1'
if _MACOS_AT_LEAST_CATALINA and _RUNNING_CONDA and not _RUNNING_PYTHONW:
python_path = Path(sys.exec_prefix) / 'bin' / 'pythonw'
if python_path.exists():
# Running again with pythonw will exit this script
# and use the framework build of python.
_run_pythonw(python_path)
else:
msg = (
'pythonw executable not found.\n'
'To unfreeze the menubar on macOS, '
'click away from napari to another app, '
'then reactivate napari. To avoid this problem, '
'please install python.app in conda using:\n'
'conda install -c conda-forge python.app'
)
warnings.warn(msg)
_run()
if __name__ == '__main__':
sys.exit(main())
|
[] |
[] |
[
"QT_MAC_WANTS_LAYER"
] |
[]
|
["QT_MAC_WANTS_LAYER"]
|
python
| 1 | 0 | |
cli/main.go
|
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"text/tabwriter"
"time"
"unicode"
"github.com/docker/go-units"
cfg "github.com/drycc/drycc/cli/config"
"github.com/drycc/drycc/controller/client"
"github.com/drycc/drycc/pkg/shutdown"
"github.com/drycc/drycc/pkg/version"
"github.com/drycc/go-docopt"
)
var (
flagCluster = os.Getenv("DRYCC_CLUSTER")
flagApp string
)
func main() {
defer shutdown.Exit()
log.SetFlags(0)
usage := `
usage: drycc [-a <app>] [-c <cluster>] <command> [<args>...]
Options:
-a <app>
-c <cluster>
-h, --help
Commands:
help show usage for a specific command
cluster manage clusters
create create an app
delete delete an app
apps list apps
info show app information
ps list jobs
kill kill jobs
log get app log
scale change formation
run run a job
env manage env variables
limit manage resource limits
meta manage app metadata
route manage routes
pg manage postgres database
mysql manage mysql database
mongodb manage mongodb database
redis manage redis database
provider manage resource providers
docker deploy Docker images to a Drycc cluster
remote manage git remotes
resource provision a new resource
release manage app releases
deployment list deployments
volume manage volumes
export export app data
import create app from exported data
version show drycc version
See 'drycc help <command>' for more information on a specific command.
`[1:]
args, _ := docopt.Parse(usage, nil, true, version.String(), true)
cmd := args.String["<command>"]
cmdArgs := args.All["<args>"].([]string)
if cmd == "help" {
if len(cmdArgs) == 0 { // `drycc help`
fmt.Println(usage)
return
} else if cmdArgs[0] == "--json" {
cmds := make(map[string]string)
for name, cmd := range commands {
cmds[name] = cmd.usage
}
out, err := json.MarshalIndent(cmds, "", "\t")
if err != nil {
shutdown.Fatal(err)
}
fmt.Println(string(out))
return
} else { // `drycc help <command>`
cmd = cmdArgs[0]
cmdArgs = make([]string, 1)
cmdArgs[0] = "--help"
}
}
// Run the update command as early as possible to avoid the possibility of
// installations being stranded without updates due to errors in other code
if cmd == "update" {
if err := runUpdate(); err != nil {
shutdown.Fatal(err)
}
return
} else {
defer updater.backgroundRun() // doesn't run if os.Exit is called
}
// Set the cluster config name
if args.String["-c"] != "" {
flagCluster = args.String["-c"]
}
flagApp = args.String["-a"]
if flagApp != "" {
if err := readConfig(); err != nil {
shutdown.Fatal(err)
}
if ra, err := appFromGitRemote(flagApp); err == nil {
clusterConf = ra.Cluster
flagApp = ra.Name
}
}
if err := runCommand(cmd, cmdArgs); err != nil {
log.Println(err)
shutdown.ExitWithCode(1)
return
}
}
type command struct {
usage string
f interface{}
optsFirst bool
}
var commands = make(map[string]*command)
func register(cmd string, f interface{}, usage string) *command {
switch f.(type) {
case func(*docopt.Args, controller.Client) error, func(*docopt.Args) error, func() error, func():
default:
panic(fmt.Sprintf("invalid command function %s '%T'", cmd, f))
}
c := &command{usage: strings.TrimLeftFunc(usage, unicode.IsSpace), f: f}
commands[cmd] = c
return c
}
func runCommand(name string, args []string) (err error) {
argv := make([]string, 1, 1+len(args))
argv[0] = name
argv = append(argv, args...)
cmd, ok := commands[name]
if !ok {
return fmt.Errorf("%s is not a drycc command. See 'drycc help'", name)
}
parsedArgs, err := docopt.Parse(cmd.usage, argv, true, "", cmd.optsFirst)
if err != nil {
return err
}
switch f := cmd.f.(type) {
case func(*docopt.Args, controller.Client) error:
// create client and run command
client, err := getClusterClient()
if err != nil {
shutdown.Fatal(err)
}
return f(parsedArgs, client)
case func(*docopt.Args) error:
return f(parsedArgs)
case func() error:
return f()
case func():
f()
return nil
}
return fmt.Errorf("unexpected command type %T", cmd.f)
}
var config *cfg.Config
var clusterConf *cfg.Cluster
func configPath() string {
return cfg.DefaultPath()
}
func readConfig() (err error) {
if config != nil {
return nil
}
config, err = cfg.ReadFile(configPath())
if os.IsNotExist(err) {
err = nil
}
if config.Upgrade() {
if err := config.SaveTo(configPath()); err != nil {
return fmt.Errorf("Error saving upgraded config: %s", err)
}
}
return
}
func getClusterClient() (controller.Client, error) {
cluster, err := getCluster()
if err != nil {
return nil, err
}
return cluster.Client()
}
var ErrNoClusters = errors.New("no clusters configured")
func getCluster() (*cfg.Cluster, error) {
app() // try to look up and cache app/cluster from git remotes
if clusterConf != nil {
return clusterConf, nil
}
if err := readConfig(); err != nil {
return nil, err
}
if len(config.Clusters) == 0 {
return nil, ErrNoClusters
}
name := flagCluster
// Get the default cluster
if name == "" {
name = config.Default
}
// Default cluster not set, pick the first one
if name == "" {
clusterConf = config.Clusters[0]
return clusterConf, nil
}
for _, s := range config.Clusters {
if s.Name == name {
clusterConf = s
return s, nil
}
}
return nil, fmt.Errorf("unknown cluster %q", name)
}
func app() (string, error) {
if flagApp != "" {
return flagApp, nil
}
if app := os.Getenv("DRYCC_APP"); app != "" {
flagApp = app
return app, nil
}
if err := readConfig(); err != nil {
return "", err
}
ra, err := appFromGitRemote(remoteFromGitConfig())
if err != nil {
return "", err
}
if ra == nil {
return "", errors.New("no app found, run from a repo with a drycc remote or specify one with -a")
}
clusterConf = ra.Cluster
flagApp = ra.Name
return ra.Name, nil
}
func mustApp() string {
name, err := app()
if err != nil {
log.Println(err)
shutdown.ExitWithCode(1)
}
return name
}
func tabWriter() *tabwriter.Writer {
return tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
}
func humanTime(ts *time.Time) string {
if ts == nil || ts.IsZero() {
return ""
}
return units.HumanDuration(time.Now().UTC().Sub(*ts)) + " ago"
}
func listRec(w io.Writer, a ...interface{}) {
for i, x := range a {
fmt.Fprint(w, x)
if i+1 < len(a) {
w.Write([]byte{'\t'})
} else {
w.Write([]byte{'\n'})
}
}
}
func compatCheck(client controller.Client, minVersion string) (bool, error) {
status, err := client.Status()
if err != nil {
return false, err
}
v := version.Parse(status.Version)
return v.Dev || !v.Before(version.Parse(minVersion)), nil
}
|
[
"\"DRYCC_CLUSTER\"",
"\"DRYCC_APP\""
] |
[] |
[
"DRYCC_APP",
"DRYCC_CLUSTER"
] |
[]
|
["DRYCC_APP", "DRYCC_CLUSTER"]
|
go
| 2 | 0 | |
references/bcb_chosen_clones/selected#487760#14#49.java
|
public static void browse(String url) throws IOException, SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(new java.net.URI(url));
return;
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (java.net.URISyntaxException e) {
e.printStackTrace();
}
}
}
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
java.lang.reflect.Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else {
java.util.Map<String, String> env = System.getenv();
if (env.get("BROWSER") != null) {
Runtime.getRuntime().exec(env.get("BROWSER") + " " + url);
return;
}
String[] browsers = { "firefox", "iceweasel", "chrome", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++) if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) {
browser = browsers[count];
break;
}
if (browser == null) throw new RuntimeException("couldn't find any browser..."); else Runtime.getRuntime().exec(new String[] { browser, url });
}
}
|
[] |
[] |
[] |
[]
|
[]
|
java
| 0 | 0 | |
models/books.go
|
package models
import (
"database/sql"
"os"
)
type Book struct {
ID int `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Year string `json:"year"`
}
type BookService interface {
BookDB
}
type BookDB interface {
GetBooks() ([]Book, error)
GetBook(id int) (*Book, error)
AddBook(book *Book) (int64, error)
UpdateBook(book *Book) (int64, error)
RemoveBook(id int) (int64, error)
}
func NewBookService(db *sql.DB) BookService {
return &bookService{
BookDB: &bookDB{db: db},
}
}
type bookService struct {
BookDB
}
var _ BookDB = &bookDB{}
type bookDB struct {
db *sql.DB
}
func (b bookDB) GetBooks() ([]Book, error) {
var books []Book
scheme := os.Getenv("DB_SCHEME")
rows, err := b.db.Query("SELECT * FROM $1", scheme)
if err != nil {
return []Book{}, err
}
for rows.Next() {
var book Book
err = rows.Scan(&book.ID, &book.Title, &book.Author, &book.Year)
if err != nil {
return []Book{}, err
}
books = append(books, book)
}
return books, nil
}
func (b bookDB) GetBook(id int) (*Book, error) {
var book *Book
scheme := os.Getenv("DB_SCHEME")
rows := b.db.QueryRow("SELECT * FROM $1 WHERE id=$2", scheme, id)
err := rows.Scan(&book.ID, &book.Title, &book.Author, &book.Year)
if err != nil {
return nil, err
}
return book, nil
}
func (b bookDB) AddBook(book *Book) (int64, error) {
scheme := os.Getenv("DB_SCHEME")
err := b.db.QueryRow("INSERT INTO $1 (title, author, year) VALUES($2, $3, $4) RETURNING id;", scheme, book.Title, book.Author, book.Year).Scan(&book.ID)
if err != nil {
return 0, err
}
return int64(book.ID), nil
}
func (b bookDB) UpdateBook(book *Book) (int64, error) {
scheme := os.Getenv("DB_SCHEME")
result, err := b.db.Exec("UPDATE $1 SET title=$2, author=$3, year=$4 WHERE id=$5 RETURNING id", scheme, &book.Title, &book.Author, &book.Year, &book.ID)
if err != nil {
return 0, err
}
rowsUpdated, err := result.RowsAffected()
if err != nil {
return 0, err
}
return rowsUpdated, nil
}
func (b bookDB) RemoveBook(id int) (int64, error) {
scheme := os.Getenv("DB_SCHEME")
result, err := b.db.Exec("DELETE FROM $1 WHERE id = $2", scheme, id)
if err != nil {
return 0, err
}
rowsDeleted, err := result.RowsAffected()
if err != nil {
return 0, err
}
return rowsDeleted, nil
}
|
[
"\"DB_SCHEME\"",
"\"DB_SCHEME\"",
"\"DB_SCHEME\"",
"\"DB_SCHEME\"",
"\"DB_SCHEME\""
] |
[] |
[
"DB_SCHEME"
] |
[]
|
["DB_SCHEME"]
|
go
| 1 | 0 | |
vendor/code.cloudfoundry.org/cli/command/v2/service_auth_tokens_command.go
|
package v2
import (
"os"
"code.cloudfoundry.org/cli/cf/cmd"
"code.cloudfoundry.org/cli/command"
)
type ServiceAuthTokensCommand struct {
usage interface{} `usage:"CF_NAME service-auth-tokens"`
}
func (_ ServiceAuthTokensCommand) Setup(config command.Config, ui command.UI) error {
return nil
}
func (_ ServiceAuthTokensCommand) Execute(args []string) error {
cmd.Main(os.Getenv("CF_TRACE"), os.Args)
return nil
}
|
[
"\"CF_TRACE\""
] |
[] |
[
"CF_TRACE"
] |
[]
|
["CF_TRACE"]
|
go
| 1 | 0 | |
python/graphscope/nx/tests/classes/test_reportviews.py
|
#
# This file is referred and derived from project NetworkX
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
# fmt: off
import os
import networkx
import pytest
from networkx.classes.reportviews import NodeDataView
from networkx.classes.tests.test_reportviews import TestDegreeView as _TestDegreeView
from networkx.classes.tests.test_reportviews import \
TestEdgeDataView as _TestEdgeDataView
from networkx.classes.tests.test_reportviews import TestEdgeView as _TestEdgeView
from networkx.classes.tests.test_reportviews import \
TestInDegreeView as _TestInDegreeView
from networkx.classes.tests.test_reportviews import \
TestInEdgeDataView as _TestInEdgeDataView
from networkx.classes.tests.test_reportviews import TestInEdgeView as _TestInEdgeView
from networkx.classes.tests.test_reportviews import \
TestNodeDataView as _TestNodeDataView
from networkx.classes.tests.test_reportviews import TestNodeView as _TestNodeView
from networkx.classes.tests.test_reportviews import \
TestNodeViewSetOps as _TestNodeViewSetOps
from networkx.classes.tests.test_reportviews import \
TestOutDegreeView as _TestOutDegreeView
from networkx.classes.tests.test_reportviews import \
TestOutEdgeDataView as _TestOutEdgeDataView
from networkx.classes.tests.test_reportviews import TestOutEdgeView as _TestOutEdgeView
from graphscope import nx
# fmt:on
# Nodes
@pytest.mark.usefixtures("graphscope_session")
class TestNodeView(_TestNodeView):
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.nv = cls.G.nodes # NodeView(G)
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]"
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
def test_iter(self):
nv = self.nv
nlist = list(self.G)
# the order of iteration is not the same every time
assert sorted(nlist) == sorted(nv)
# odd case where NodeView calls NodeDataView with data=False
nnv = nv(data=False)
assert sorted(nlist) == sorted(nnv)
def test_pickle(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestNodeDataView(_TestNodeDataView):
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.nv = NodeDataView(cls.G)
cls.ndv = cls.G.nodes.data(True)
cls.nwv = cls.G.nodes.data("foo")
def test_pickle(self):
pass
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
msg = str([(n, {}) for n in range(9)])
assert str(self.ndv) == msg
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
expected = "NodeDataView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
assert repr(self.nv) == expected
expected = (
"NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, "
+ "4: {}, 5: {}, 6: {}, 7: {}, 8: {}})"
)
assert repr(self.ndv) == expected
expected = (
"NodeDataView({0: None, 1: None, 2: None, 3: None, 4: None, "
+ "5: None, 6: None, 7: None, 8: None}, data='foo')"
)
assert repr(self.nwv) == expected
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
G = self.G.copy()
nlist = list(G)
nv = G.nodes.data()
ndv = G.nodes.data(True)
nwv = G.nodes.data("foo")
for i, (n, d) in enumerate(nv):
assert nlist[i] == n
assert d == {}
inv = iter(nv)
assert next(inv) == (0, {})
G.nodes[3]["foo"] = "bar"
# default
for n, d in nv:
if n == 3:
assert d == {"foo": "bar"}
else:
assert d == {}
# data=True
for n, d in ndv:
if n == 3:
assert d == {"foo": "bar"}
else:
assert d == {}
# data='foo'
for n, d in nwv:
if n == 3:
assert d == "bar"
else:
assert d is None
# data='foo', default=1
for n, d in G.nodes.data("foo", default=1):
if n == 3:
assert d == "bar"
else:
assert d == 1
@pytest.mark.usefixtures("graphscope_session")
class TestNodeViewSetOps(_TestNodeViewSetOps):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.G.nodes[3]["foo"] = "bar"
cls.nv = cls.G.nodes
@pytest.mark.usefixtures("graphscope_session")
class TestNodeDataViewSetOps(TestNodeViewSetOps):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.G.nodes[3]["foo"] = "bar"
cls.nv = cls.G.nodes.data("foo")
print("nv", cls.nv)
def n_its(self, nodes):
return {(node, "bar" if node == 3 else None) for node in nodes}
class TestNodeDataViewDefaultSetOps(TestNodeDataViewSetOps):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.G.nodes[3]["foo"] = "bar"
cls.nv = cls.G.nodes.data("foo", default=1)
def n_its(self, nodes):
return {(node, "bar" if node == 3 else 1) for node in nodes}
# Edges Data View
@pytest.mark.usefixtures("graphscope_session")
class TestEdgeDataView(_TestEdgeDataView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.eview = networkx.reportviews.EdgeView
def test_pickle(self):
pass
def test_str(self):
pass
def test_repr(self):
pass
def test_iter(self):
evr = self.eview(self.G)
ev = evr()
for u, v in ev:
pass
iev = iter(ev)
# The node order of iteration is not start from 0 every time.
# assert next(iev) == (0, 1)
assert iter(ev) != ev
assert iter(iev) == iev
@pytest.mark.usefixtures("graphscope_session")
class TestOutEdgeDataView(_TestOutEdgeDataView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, create_using=nx.DiGraph())
cls.eview = networkx.reportviews.OutEdgeView
def test_pickle(self):
pass
def test_str(self):
pass
def test_repr(self):
pass
def test_iter(self):
evr = self.eview(self.G)
ev = evr()
for u, v in ev:
pass
iev = iter(ev)
# The node order of iteration is not start from 0 every time.
# assert next(iev) == (0, 1)
assert iter(ev) != ev
assert iter(iev) == iev
@pytest.mark.usefixtures("graphscope_session")
class TestInEdgeDataView(_TestInEdgeDataView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, create_using=nx.DiGraph())
cls.eview = networkx.reportviews.InEdgeView
def test_iter(self):
evr = self.eview(self.G)
ev = evr()
for u, v in ev:
pass
iev = iter(ev)
assert next(iev) in ((0, 1), (1, 2))
assert iter(ev) != ev
assert iter(iev) == iev
def test_pickle(self):
pass
def test_str(self):
pass
def test_repr(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestEdgeView(_TestEdgeView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.eview = networkx.reportviews.EdgeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
ev = self.eview(self.G)
rep = str([(n, n + 1) for n in range(8)])
assert str(ev) in rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
ev = self.eview(self.G)
rep = (
"EdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
+ "(4, 5), (5, 6), (6, 7), (7, 8)])"
)
assert repr(ev) in rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_or(self):
# print("G | H edges:", gnv | hnv)
ev = self.eview(self.G)
some_edges = {(0, 1), (1, 0), (0, 2)}
result1 = {(n, n + 1) for n in range(8)}
result1.update(some_edges)
result2 = {(n + 1, n) for n in range(8)}
result2.update(some_edges)
assert (ev | some_edges) in (result1, result2)
assert (some_edges | ev) in (result1, result2)
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_xor(self):
# print("G ^ H edges:", gnv ^ hnv)
ev = self.eview(self.G)
some_edges = {(0, 1), (1, 0), (0, 2)}
if self.G.is_directed():
result = {(n, n + 1) for n in range(1, 8)}
result.update({(1, 0), (0, 2)})
assert ev ^ some_edges == result
else:
result = {(n, n + 1) for n in range(1, 8)}
result.update({(0, 2)})
assert ev ^ some_edges == result
return
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
ev = self.eview(self.G)
for u, v in ev:
pass
iev = iter(ev)
assert next(iev) == (0, 1)
assert iter(ev) != ev
assert iter(iev) == iev
def test_pickle(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestOutEdgeView(_TestOutEdgeView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, nx.DiGraph())
cls.eview = networkx.reportviews.OutEdgeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
ev = self.eview(self.G)
rep = str([(n, n + 1) for n in range(8)])
assert str(ev) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
ev = self.eview(self.G)
rep = (
"OutEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
+ "(4, 5), (5, 6), (6, 7), (7, 8)])"
)
assert repr(ev) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
ev = self.eview(self.G)
for u, v in ev:
pass
iev = iter(ev)
assert next(iev) == (0, 1)
assert iter(ev) != ev
assert iter(iev) == iev
def test_pickle(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestInEdgeView(_TestInEdgeView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, nx.DiGraph())
cls.eview = networkx.reportviews.InEdgeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
ev = self.eview(self.G)
rep = str([(n, n + 1) for n in range(8)])
assert str(ev) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
ev = self.eview(self.G)
rep = (
"InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
+ "(4, 5), (5, 6), (6, 7), (7, 8)])"
)
assert repr(ev) == rep
def test_iter(self):
ev = self.eview(self.G)
for u, v in ev:
pass
iev = iter(ev)
assert next(iev) in ((0, 1), (1, 2))
assert iter(ev) != ev
assert iter(iev) == iev
def test_pickle(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestDegreeView(_TestDegreeView):
GRAPH = nx.Graph
dview = networkx.reportviews.DegreeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
dv = self.dview(self.G)
rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
assert str(dv) == rep
dv = self.G.degree()
assert str(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
dv = self.dview(self.G)
rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
assert repr(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
dv = self.dview(self.G)
nlist = list(self.G)
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
# weighted
dv = self.dview(self.G, weight="foo")
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
def test_pickle(self):
print(type(self.G))
pass
class TestDiDegreeView(TestDegreeView):
GRAPH = nx.DiGraph
dview = networkx.reportviews.DiDegreeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
dv = self.G.degree()
rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
assert repr(dv) == rep
@pytest.mark.usefixtures("graphscope_session")
class TestOutDegreeView(_TestOutDegreeView):
GRAPH = nx.DiGraph
dview = networkx.reportviews.OutDegreeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
dv = self.dview(self.G)
rep = str([(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 0)])
assert str(dv) == rep
dv = self.G.out_degree()
assert str(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
dv = self.G.out_degree()
rep = "OutDegreeView({0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 0})"
assert repr(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
dv = self.dview(self.G)
nlist = list(self.G)
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
# weighted
dv = self.dview(self.G, weight="foo")
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
def test_pickle(self):
pass
@pytest.mark.usefixtures("graphscope_session")
class TestInDegreeView(_TestInDegreeView):
GRAPH = nx.DiGraph
dview = networkx.reportviews.InDegreeView
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_str(self):
dv = self.dview(self.G)
rep = str([(0, 0), (1, 1), (2, 1), (3, 2), (4, 1), (5, 1)])
assert str(dv) == rep
dv = self.G.in_degree()
assert str(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_repr(self):
dv = self.G.in_degree()
rep = "InDegreeView({0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 1})"
assert repr(dv) == rep
@pytest.mark.skipif(
os.environ.get("DEPLOYMENT", None) != "standalone",
reason="Only need to test on standalone",
)
def test_iter(self):
dv = self.dview(self.G)
nlist = list(self.G)
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
# weighted
dv = self.dview(self.G, weight="foo")
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (nlist[0], dv[nlist[0]])
assert next(idv) == (nlist[1], dv[nlist[1]])
def test_pickle(self):
pass
|
[] |
[] |
[
"DEPLOYMENT"
] |
[]
|
["DEPLOYMENT"]
|
python
| 1 | 0 | |
player.go
|
// Copyright 2014 José Carlos Nieto
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"errors"
"github.com/gorilla/websocket"
//"github.com/xiam/backstream"
"fmt"
"github.com/xiam/g"
"io"
"log"
"math"
"math/rand"
"net"
"os"
"github.com/xiam/shooter-server/ship"
"time"
)
const (
playerMaxSpeed = 5.0
playerTurnSpeed = math.Pi / 24
playerMaxLife = 32
playerNearValue = 500
)
var playerShowLog = false
var (
ErrNoWebsocket = errors.New(`Don't have any websocket connection.`)
)
func init() {
if os.Getenv("DEBUG") != "" {
playerShowLog = true
}
rand.Seed(time.Now().Unix())
}
type player struct {
ws *websocket.Conn
output chan []byte
addr net.Addr
points uint64
hitValue int
killValue int
bulletType int
sector *sector
compressor io.Writer
*ship.Ship
*control
shootTicks uint
speedFactor float64
destroying bool
}
func newPlayer(ws *websocket.Conn) *player {
self := &player{}
self.ws = ws
// Bot players do not use a websocket.
if self.ws != nil {
self.output = make(chan []byte, 256)
//self.compressor = backstream.NewWriter(self, 0)
self.addr = ws.RemoteAddr()
} else {
self.output = nil
}
// Creating controller.
self.control = NewControl()
self.speedFactor = 1.0
// Creating a ship.
self.Ship = ship.NewShip()
self.Ship.Entity.Kind = (1 + rand.Intn(8))
switch self.Ship.Entity.Kind {
case 1, 2, 3, 4:
self.Ship.Entity.Width = 80
self.Ship.Entity.Height = 120
case 5, 6, 7, 8:
self.Ship.Entity.Width = 80
self.Ship.Entity.Height = 110
}
self.Ship.Entity.Model = fmt.Sprintf("ship-%d", self.Ship.Entity.Kind)
self.hitValue = 2
self.Life = playerMaxLife
self.bulletType = BULLET_1X
self.shootTicks = 0
// Default values.
self.SetSpeed(0)
self.SetDirection(0, -1)
self.SetPosition(0, 0)
return self
}
func (self *player) log(s string) {
if self.addr != nil {
log.Printf("%s: %s\n", self.addr, s)
} else {
log.Printf("bot: %s\n", s)
}
}
// Determines is a player is near other player.
func (self *player) isNear(other *player) bool {
xdiff := math.Abs(self.Position[0] - other.Position[0])
ydiff := math.Abs(self.Position[1] - other.Position[1])
mdiff := math.Max(xdiff, ydiff)
if mdiff > playerNearValue {
return false
}
return true
}
func (self *player) Write(p []byte) (n int, err error) {
if self.ws == nil {
return 0, ErrNoWebsocket
}
err = self.ws.WriteMessage(websocket.TextMessage, p)
if playerShowLog == true {
log.Printf("%s <- %s: %v\n", self.ws.RemoteAddr(), p, err)
}
return len(p), err
}
// Serializes player.
func (self *player) Serialize() (buf []byte) {
data := self.Ship.DataMap()
(*data)["L"] = self.Life
(*data)["P"] = self.points
(*data)["N"] = self.control.Name
self.Ship.Diff.SetData(data)
return self.Ship.Diff.Serialize()
}
func (self *player) addLife(delta int) {
self.Life = int(math.Min(float64(self.Life+delta), float64(playerMaxLife)))
}
// Adds points to a player
func (self *player) addPoints(delta int) {
self.points = self.points + uint64(delta)
}
func (self *player) newBullet() *fire {
f := newFire(self.bulletType)
f.player = self
return f
}
func (self *player) shoot() {
if self.sector == nil {
return
}
self.shootTicks++
if self.shootTicks%3 != 1 {
return
}
b := self.newBullet()
b.SetPosition(
self.Position[0]+self.Direction[0]*(self.Width/2.0)*1.1,
self.Position[1]+self.Direction[1]*(self.Width/2.0)*1.1,
)
b.SetDirection(self.Direction[0], self.Direction[1])
b.SetSpeed(float64(playerMaxSpeed) * 3.0 * self.speedFactor)
self.sector.addFire(b)
}
func (self *player) hit(other *player, val int) {
if self.Life > 1 {
self.Life = self.Life - val
} else {
if other != nil {
other.addPoints(self.killValue)
}
self.destroy()
}
}
func (self *player) ident() {
if self.Id != "" {
self.write(identFn(self.Id))
}
}
func (self *player) sameAs(other *player) bool {
if self.Id != "" {
return self.Id == other.Id
}
return false
}
func (self *player) write(data []byte) {
if self.ws == nil {
return
}
if self.output == nil {
return
}
self.output <- data
}
func (self *player) notice(other *player) {
data := other.DataMap()
buf, err := json.Marshal(data)
if err == nil {
if other.ws == nil {
self.write(createFn("ship-ai", other.Id, buf))
} else {
self.write(createFn("ship", other.Id, buf))
}
}
}
func (self *player) collidesWithPlayer(other *player) ([]*g.Point, error) {
a := self.Poly()
b := other.Poly()
points, err := g.PolyIntersectsPoly(a, b)
if err == nil {
return points, nil
}
return points, err
}
func (self *player) update() {
b := self.Serialize()
if b != nil {
chunk := updateFn(self.Id, b)
if self.sector != nil {
for p, _ := range self.sector.players {
if p.ws != nil && p.output != nil {
if self.isNear(p) == true {
p.write(chunk)
}
}
}
}
}
}
func (self *player) destroy() {
if self.destroying == false {
self.destroying = true
//self.log("Attempt to destroy.")
// Announcing this ship is destroyed.
if self.sector != nil {
// Adding to top scores.
highScores.Add(self.control.Name, self.points)
// Last update
self.update()
//self.log("Updated")
//self.log("Removing from sector.")
self.sector.broadcast(destroyFn(self.Id))
self.sector.gbgPlayer <- self
self.Life = 0
//self.log("Removed")
}
if self.ws != nil {
topScores := highScores.GetTop()
jsonScores, _ := json.Marshal(topScores)
// Writing directly on the compressor
//self.log("Writing scores.")
self.write(scoresFn(jsonScores))
//self.log("Wrote.")
}
//self.log("Destroyed")
}
}
func (self *player) reader() {
for {
_, message, err := self.ws.ReadMessage()
if err != nil {
break
}
json.Unmarshal(message, self.control)
if playerShowLog == true {
log.Printf("%s -> %s\n", self.ws.RemoteAddr(), message)
}
}
//self.log("Exiting reader.")
//self.close()
self.destroy()
}
func (self *player) writer() {
var start, diff, sleep int64
var buf []byte
writing := true
for writing {
buf = make([]byte, 0, 1024*10)
start = time.Now().UnixNano()
loop := true
for loop {
select {
case message := <-self.output:
buf = append(buf, message...)
buf = append(buf, '\n')
default:
loop = false
}
}
if len(buf) > 0 {
_, err := self.Write(buf)
if err != nil {
writing = false
}
}
diff = time.Now().UnixNano() - start
sleep = fpsn - diff
//fmt.Printf("sleep: %d, diff: %d\n", sleep, diff)
if sleep < 0 {
continue
}
time.Sleep(time.Duration(sleep) * time.Nanosecond)
}
/*
for message := range self.output {
//_, err := self.compressor.Write(message)
_, err := self.Write(message)
if err != nil {
//self.log("Got write error.")
break
}
}
*/
//self.log("Exiting writer.")
self.close()
}
func (self *player) close() {
if self.ws != nil {
//self.log("Closing websocket.")
self.ws.Close()
self.ws = nil
//self.log("Websocket closed.")
}
if self.output != nil {
//self.log("Closing channel.")
close(self.output)
self.output = nil
//self.log("Channel closed.")
}
}
func (self *player) isFree() bool {
var poly *g.Poly
if self.sector != nil {
for other := range self.sector.players {
if self.sameAs(other) == false {
poly = self.Poly()
_, err := g.PolyIntersectsPoly(poly, other.Poly())
if err == nil {
return false
}
}
}
}
return true
}
func (self *player) correct() {
for self.isFree() == false {
area := int64(math.Max(float64(self.sector.bounds[0])/5, float64(self.sector.bounds[1]/5)))
self.Position[0], self.Position[1] = float64(rand.Int63n(area)-area/2), float64(rand.Int63n(area)-area/2)
}
}
func (self *player) Tick() {
var t float64
t = playerTurnSpeed
if self.control.Y > 0 {
self.Speed = -playerMaxSpeed
} else if self.control.Y < 0 {
self.Speed = playerMaxSpeed
} else {
self.Speed = 0.0
}
self.Speed = self.Speed * self.speedFactor
if self.control.X < 0 {
t = -t
} else if self.control.X == 0 {
t = 0.0
}
x := self.Direction[0]
y := self.Direction[1]
self.Direction[0] = x*math.Cos(t) - y*math.Sin(t)
self.Direction[1] = x*math.Sin(t) + y*math.Cos(t)
// Attempt to move.
self.Position[0] = self.Position[0] + self.Direction[0]*self.Speed
self.Position[1] = self.Position[1] + self.Direction[1]*self.Speed
// Boundary checking
if int64(self.Position[0]) > self.sector.bounds[0] {
self.Position[0] = float64(self.sector.bounds[0])
}
if int64(self.Position[0]) < -self.sector.bounds[0] {
self.Position[0] = float64(-self.sector.bounds[0])
}
if int64(self.Position[1]) > self.sector.bounds[1] {
self.Position[1] = float64(self.sector.bounds[1])
}
if int64(self.Position[1]) < -self.sector.bounds[1] {
self.Position[1] = float64(-self.sector.bounds[1])
}
// Collision check
poly := self.Poly()
for other, _ := range self.sector.players {
if self.sameAs(other) == false {
_, err := g.PolyIntersectsPoly(poly, other.Poly())
if err == nil {
self.hit(nil, 1)
}
}
}
if self.control.S > 0 {
self.shoot()
}
}
|
[
"\"DEBUG\""
] |
[] |
[
"DEBUG"
] |
[]
|
["DEBUG"]
|
go
| 1 | 0 | |
MicroServices/scenario/handlers/UpdateScenario.go
|
package handlers
import (
"io"
"log"
"net/http"
"os"
"strconv"
"github.com/matscus/Hamster/MicroServices/scenario/scn"
"github.com/matscus/Hamster/Package/Scenario/scenario"
"github.com/matscus/Hamster/Package/errorImpl"
)
//UpdateOrDeleteScenario - handle for update scenario values to table
func UpdateOrDeleteScenario(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
id, err := strconv.ParseInt(r.FormValue("scenarioID"), 10, 64)
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Parse form scenaroiID error", err))
return
}
s := scenario.Scenario{
ID: id,
Name: r.FormValue("scenarioName"),
Type: r.FormValue("scenarioType"),
Gun: r.FormValue("gun"),
Projects: r.FormValue("project"),
DBClient: PgClient,
}
oldname, err := s.GetNameForID()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Get name error", err))
return
}
err = os.Rename(os.Getenv("DIRPROJECTS")+"/"+s.Projects+"/"+s.Gun+"/"+oldname+".zip", os.Getenv("DIRPROJECTS")+"/"+s.Projects+"/"+s.Gun+"/"+s.Name+".zip")
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Rename error", err))
return
}
err = r.ParseMultipartForm(32 << 20)
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Parse multipartform error", err))
return
}
file, _, err := r.FormFile("uploadFile")
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Get form uploadFiles error", err))
return
}
if file == nil {
err = s.Update()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Update error", err))
return
}
err = scn.InitData()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Init data error", err))
return
}
w.WriteHeader(http.StatusOK)
_, errWrite := w.Write([]byte("{\"Message\":\"Update scenario complited\"}"))
if errWrite != nil {
log.Printf("[ERROR] Update scenario complited, but Not Writing to ResponseWriter due: %s", errWrite.Error())
}
return
}
defer file.Close()
f, err := os.OpenFile(os.Getenv("DIRPROJECTS")+"/"+s.Projects+"/"+s.Gun+"/"+s.Name+".zip", os.O_CREATE|os.O_RDWR, os.FileMode(0755))
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Open file error", err))
return
}
defer f.Close()
_, err = io.Copy(f, file)
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("IO copy file error", err))
return
}
err = s.Update()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Update error", err))
return
}
err = scn.InitData()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Init data error", err))
return
}
w.WriteHeader(http.StatusOK)
_, errWrite := w.Write([]byte("{\"Message\":\"Update scenario complited\"}"))
if errWrite != nil {
log.Printf("[ERROR] Update done, but Not Writing to ResponseWriter due: %s", errWrite.Error())
}
case "DELETE":
id, err := strconv.ParseInt(r.FormValue("scenarioID"), 10, 64)
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Parse form scenarioID error", err))
return
}
s := scenario.Scenario{
ID: id,
Name: r.FormValue("scenarioName"),
Type: r.FormValue("scenarioType"),
Gun: r.FormValue("gun"),
Projects: r.FormValue("project"),
DBClient: PgClient,
}
err = s.DeleteScenario()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Delete error", err))
return
}
err = os.Remove(os.Getenv("DIRPROJECTS") + "/" + s.Projects + "/" + s.Gun + "/" + s.Name + ".zip")
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Remove dir error", err))
return
}
err = scn.InitData()
if err != nil {
errorImpl.WriteHTTPError(w, http.StatusOK, errorImpl.ScenarioError("Init data error", err))
return
}
w.WriteHeader(http.StatusOK)
_, errWrite := w.Write([]byte("{\"Message\":\"Delete scenario complited\"}"))
if errWrite != nil {
log.Printf("[ERROR] Delete scenario complited, but Not Writing to ResponseWriter due: %s", errWrite.Error())
}
}
}
|
[
"\"DIRPROJECTS\"",
"\"DIRPROJECTS\"",
"\"DIRPROJECTS\"",
"\"DIRPROJECTS\""
] |
[] |
[
"DIRPROJECTS"
] |
[]
|
["DIRPROJECTS"]
|
go
| 1 | 0 | |
model/setup.go
|
package model
import (
"fmt"
"os"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func ConnectDatabase() {
dsn := os.Getenv("DB_CONNECTION_STRING")
if len(dsn) == 0 {
panic("Connection url not provided please provide it in the DB_CONNECTION_STRING env")
}
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("Failed to connect to database!")
}
var books []Book
var count int64
database.Find(&books).Count(&count)
if count == 0 {
err = seedData(err, database)
}
if err != nil {
fmt.Errorf("Failed to seed the data")
}
DB = database
}
func seedData(err error, database *gorm.DB) error {
err = database.AutoMigrate(&Book{})
book := &Book{1, "Beyond Good And Evil", "Friedrich Nietzsche", "Beyond Good And Evil asks, is truth absolute? Do humans invent ways to fortify already held views or truly seek the truth? Are the powerful more ‘right’ than the weak? Or is Nietzsche writing down page after page to hear himself talk?", 1}
database.Create(&book)
book = &Book{6, "Culture Map: Decoding How People Think, Lead, and Get Things Done Across Cultures", "Erin Meyer", "Whether you work in a home office or abroad, business success in our ever more globalized and virtual world requires the skills to navigate through cultural differences and decode cultures foreign to your own. Renowned expert Erin Meyer is your guide through this subtle, sometimes treacherous terrain where people from starkly different backgrounds are expected to work harmoniously together.", 6}
database.Create(&book)
book = &Book{2, "The Path\nA New Way to Think About Everything", " Professor Michael Puett, Christine Gross-Loh", "In the first book of its kind, The Path draws on the work of six of the great - but largely unknown - Chinese philosophers to offer a fresh and revolutionary guide to human flourishing.\n\nBy examining the teachings of Chinese thinkers and explaining what they reveal about our daily lives - from greeting others to raising children - The Path challenges some of our deepest held assumptions. It shows that the way to live well is not to slavishly follow a grand plan, as so much of Western thought would have us believe, but rather to follow a path - one of self-cultivation and self-discovery.", 2}
database.Create(&book)
book = &Book{3, "I Will Never See the World Again", "Ahmet Altan", "The destiny I put down in my novel has become mine. I am now under arrest like the hero I created years ago. I await the decision that will determine my future, just as he awaited his. I am unaware of my destiny, which has perhaps already been decided, just as he was unaware of his. I suffer the pathetic torment of profound helplessness, just as he did. Like a cursed oracle, I foresaw my future years ago not knowing that it was my own. Confined in a cell four metres long, imprisoned on absurd, Kafkaesque charges, novelist Ahmet Altan is one of many writers persecuted by Recep Tayyip Erdogan's oppressive regime. In this extraordinary memoir, written from his prison cell, Altan reflects upon his sentence, on a life whittled down to a courtyard covered by bars, and on the hope and solace a writer's mind can provide, even in the darkest places.", 3}
database.Create(&book)
book = &Book{4, "101 Essays That Will Change the Way You Think", "Brianna Wiest", "Over the past few years, Brianna Wiest has gained renown for her deeply moving, philosophical writing. This new compilation of her published work features pieces on why you should pursue purpose over passion, embrace negative thinking, see the wisdom in daily routine, and become aware of the cognitive biases that are creating the way you see your life.\n\nSome of these pieces have never been seen; others have been read by millions of people around the world. Regardless, each will leave you thinking: This idea changed my life.", 4}
database.Create(&book)
book = &Book{5, "The Nordic Theory of Everything: In Search of a Better Life", "Anu Partanen", "Partanen is a careful, judicious writer and she makes a careful, judicious case.. it s useful to know what the outsider knows: there are other ways of organizing humanity.", 5}
database.Create(&book)
return err
}
|
[
"\"DB_CONNECTION_STRING\""
] |
[] |
[
"DB_CONNECTION_STRING"
] |
[]
|
["DB_CONNECTION_STRING"]
|
go
| 1 | 0 | |
learn-python-programming-from-scratch/tutorials/django-framework/learnpython/learnpython/wsgi.py
|
"""
WSGI config for learnpython project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learnpython.settings')
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
cmd/transcriptionComplete/main_test.go
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/go-playground/validator"
"github.com/julienschmidt/httprouter"
"github.com/peterpla/lead-expert/pkg/config"
"github.com/peterpla/lead-expert/pkg/database"
"github.com/peterpla/lead-expert/pkg/queue"
)
func TestTranscriptionComplete(t *testing.T) {
cfg := config.GetConfigPointer()
servicePrefix := "transcription-complete-dot-" // <---- change to match service!!
port := cfg.TaskTranscriptionCompletePort // <---- change to match service!!
repo = database.NewFirestoreRequestRepository(cfg.ProjectID, cfg.DatabaseRequests)
validate = validator.New()
type test struct {
name string
method string
endpoint string
body string
respBody string
status int
}
jsonBody := fmt.Sprintf("{ \"customer_id\": %7d, \"media_uri\": %q, \"accepted_at\": %q }",
1234567, "gs://elated-practice-224603.appspot.com/audio_uploads/audio-01.mp3", time.Now().UTC().Format(time.RFC3339Nano))
tests := []test{
// valid
{name: "valid POST /task_handler",
method: "POST",
endpoint: "/task_handler",
body: jsonBody,
status: http.StatusOK},
{name: "valid GET /",
method: "GET",
endpoint: "/",
respBody: "service running",
status: http.StatusOK},
{name: "invalid GET /nope",
method: "GET",
endpoint: "/nope",
respBody: "not found",
status: http.StatusNotFound},
}
qi = queue.QueueInfo{}
q = queue.NewNullQueue(&qi) // use null queue, requests thrown away on exit
// q = queue.NewGCTQueue(&qi) // use Google Cloud Tasks
prefix := fmt.Sprintf("http://localhost:%s", port)
if cfg.IsGAE {
prefix = fmt.Sprintf("https://%s%s.appspot.com", servicePrefix, os.Getenv("PROJECT_ID"))
}
for _, tc := range tests {
url := prefix + tc.endpoint
// log.Printf("Test %s: %s", tc.name, url)
router := httprouter.New()
router.POST("/task_handler", taskHandler(q))
router.GET("/", indexHandler)
// build the POST request with custom header
theRequest, err := http.NewRequest(tc.method, url, strings.NewReader(tc.body))
if err != nil {
t.Fatal(err)
}
theRequest.Header.Set("X-Appengine-Taskname", "localTask")
theRequest.Header.Set("X-Appengine-Queuename", "localQueue")
// response recorder
rr := httptest.NewRecorder()
// send the request
router.ServeHTTP(rr, theRequest)
if tc.status != rr.Code {
t.Errorf("%s: %q expected status code %v, got %v", tc.name, tc.endpoint, tc.status, rr.Code)
}
if tc.respBody != "" {
var b []byte
if b, err = ioutil.ReadAll(rr.Body); err != nil {
t.Fatalf("%s: ReadAll error: %v", tc.name, err)
}
// log.Printf("%s: rr.Body: %q\n", tc.name, string(b))
if !strings.Contains(string(b), tc.respBody) {
t.Errorf("%s: expected %q, not found (in %q)", tc.name, tc.respBody, string(b))
}
}
}
}
|
[
"\"PROJECT_ID\""
] |
[] |
[
"PROJECT_ID"
] |
[]
|
["PROJECT_ID"]
|
go
| 1 | 0 | |
appengine/standard_python3/django/mysite/settings.py
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# Update the secret key to a value of your own before deploying the app.
SECRET_KEY = 'lldtg$9(wi49j_hpv8nnqlh!cj7kmbwq0$rj7vy(b(b30vlyzj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURITY WARNING: App Engine's security features ensure that it is safe to
# have ALLOWED_HOSTS = ['*'] when the app is deployed. If you deploy a Django
# app not on App Engine, make sure to set an appropriate host here.
# See https://docs.djangoproject.com/en/2.1/ref/settings/
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
# Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter
# See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers
# for more information
import pymysql # noqa: 402
pymysql.version_info = (1, 4, 6, 'final', 0) # change mysqlclient version
pymysql.install_as_MySQLdb()
# [START db_setup]
if os.getenv('GAE_APPLICATION', None):
# Running on production App Engine, so connect to Google Cloud SQL using
# the unix socket at /cloudsql/<your-cloudsql-connection string>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/[YOUR-CONNECTION-NAME]',
'USER': '[YOUR-USERNAME]',
'PASSWORD': '[YOUR-PASSWORD]',
'NAME': '[YOUR-DATABASE]',
}
}
else:
# Running locally so connect to either a local MySQL instance or connect to
# Cloud SQL via the proxy. To start the proxy via command line:
#
# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
#
# See https://cloud.google.com/sql/docs/mysql-connect-proxy
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': '3306',
'NAME': '[YOUR-DATABASE]',
'USER': '[YOUR-USERNAME]',
'PASSWORD': '[YOUR-PASSWORD]',
}
}
# [END db_setup]
# Use a in-memory sqlite3 database when testing in CI systems
if os.getenv('TRAMPOLINE_CI', None):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # noqa: 501
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_ROOT = 'static'
STATIC_URL = '/static/'
|
[] |
[] |
[
"GAE_APPLICATION",
"TRAMPOLINE_CI"
] |
[]
|
["GAE_APPLICATION", "TRAMPOLINE_CI"]
|
python
| 2 | 0 | |
Utilities/build_makelink.py
|
#!/usr/bin/env python
# encoding: utf-8
"""
build_makelink.py
Created by zonble on 2009-09-07.
"""
import sys
import os
def build_debug():
project_target_name = "OpenVanilla (Loader IMK)"
clean_command = "xcodebuild -project ../OpenVanilla.xcodeproj -configuration Debug clean"
build_command = "xcodebuild -project ../OpenVanilla.xcodeproj -configuration Debug -target \"" + project_target_name + "\" build"
os.system(clean_command)
os.system(build_command)
def logout():
command = "/usr/bin/osascript -e 'tell application \"System Events\" to log out'"
os.system(command)
def makelink():
current_folder = os.path.abspath(os.path.dirname(__file__))
debug_folder = os.path.join(current_folder, "../build/Debug/")
home = os.environ['HOME']
app = "OpenVanilla.app"
target_folder = os.path.join(home, "Library/Input Methods")
try:
os.mkdir(target_folder)
except Exception as e:
print e
pass
source = os.path.join(debug_folder, app)
target = os.path.join(target_folder, app)
try:
print "Creating symbolic link..."
os.symlink(source, target)
print "Done"
logout()
except Exception as e:
print e
pass
def main():
build_debug()
makelink()
pass
if __name__ == '__main__':
main()
|
[] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
python
| 1 | 0 | |
vendor/github.com/nats-io/nats.go/nats.go
|
// Copyright 2012-2019 The NATS 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.
// A Go client for the NATS messaging system (https://nats.io).
package nats
import (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/jwt"
"github.com/nats-io/nats.go/util"
"github.com/nats-io/nkeys"
"github.com/nats-io/nuid"
)
// Default Constants
const (
Version = "1.9.1"
DefaultURL = "nats://127.0.0.1:4222"
DefaultPort = 4222
DefaultMaxReconnect = 60
DefaultReconnectWait = 2 * time.Second
DefaultTimeout = 2 * time.Second
DefaultPingInterval = 2 * time.Minute
DefaultMaxPingOut = 2
DefaultMaxChanLen = 8192 // 8k
DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB
RequestChanLen = 8
DefaultDrainTimeout = 30 * time.Second
LangString = "go"
)
const (
// STALE_CONNECTION is for detection and proper handling of stale connections.
STALE_CONNECTION = "stale connection"
// PERMISSIONS_ERR is for when nats server subject authorization has failed.
PERMISSIONS_ERR = "permissions violation"
// AUTHORIZATION_ERR is for when nats server user authorization has failed.
AUTHORIZATION_ERR = "authorization violation"
// AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
AUTHENTICATION_EXPIRED_ERR = "user authentication expired"
)
// Errors
var (
ErrConnectionClosed = errors.New("nats: connection closed")
ErrConnectionDraining = errors.New("nats: connection draining")
ErrDrainTimeout = errors.New("nats: draining connection timed out")
ErrConnectionReconnecting = errors.New("nats: connection reconnecting")
ErrSecureConnRequired = errors.New("nats: secure connection required")
ErrSecureConnWanted = errors.New("nats: secure connection not available")
ErrBadSubscription = errors.New("nats: invalid subscription")
ErrTypeSubscription = errors.New("nats: invalid subscription type")
ErrBadSubject = errors.New("nats: invalid subject")
ErrBadQueueName = errors.New("nats: invalid queue name")
ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped")
ErrTimeout = errors.New("nats: timeout")
ErrBadTimeout = errors.New("nats: timeout invalid")
ErrAuthorization = errors.New("nats: authorization violation")
ErrAuthExpired = errors.New("nats: authentication expired")
ErrNoServers = errors.New("nats: no servers available for connection")
ErrJsonParse = errors.New("nats: connect message, json parse error")
ErrChanArg = errors.New("nats: argument needs to be a channel type")
ErrMaxPayload = errors.New("nats: maximum payload exceeded")
ErrMaxMessages = errors.New("nats: maximum messages delivered")
ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription")
ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed")
ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received")
ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded")
ErrInvalidConnection = errors.New("nats: invalid connection")
ErrInvalidMsg = errors.New("nats: invalid message or message nil")
ErrInvalidArg = errors.New("nats: invalid argument")
ErrInvalidContext = errors.New("nats: invalid context")
ErrNoDeadlineContext = errors.New("nats: context requires a deadline")
ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server")
ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server")
ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler")
ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler")
ErrNoUserCB = errors.New("nats: user callback not defined")
ErrNkeyAndUser = errors.New("nats: user callback and nkey defined")
ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server")
ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION)
ErrTokenAlreadySet = errors.New("nats: token and token handler both set")
ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection")
ErrMsgNoReply = errors.New("nats: message does not have a reply")
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// GetDefaultOptions returns default configuration options for the client.
func GetDefaultOptions() Options {
return Options{
AllowReconnect: true,
MaxReconnect: DefaultMaxReconnect,
ReconnectWait: DefaultReconnectWait,
Timeout: DefaultTimeout,
PingInterval: DefaultPingInterval,
MaxPingsOut: DefaultMaxPingOut,
SubChanLen: DefaultMaxChanLen,
ReconnectBufSize: DefaultReconnectBufSize,
DrainTimeout: DefaultDrainTimeout,
}
}
// DEPRECATED: Use GetDefaultOptions() instead.
// DefaultOptions is not safe for use by multiple clients.
// For details see #308.
var DefaultOptions = GetDefaultOptions()
// Status represents the state of the connection.
type Status int
const (
DISCONNECTED = Status(iota)
CONNECTED
CLOSED
RECONNECTING
CONNECTING
DRAINING_SUBS
DRAINING_PUBS
)
// ConnHandler is used for asynchronous events such as
// disconnected and closed connections.
type ConnHandler func(*Conn)
// ConnErrHandler is used to process asynchronous events like
// disconnected connection with the error (if any).
type ConnErrHandler func(*Conn, error)
// ErrHandler is used to process asynchronous errors encountered
// while processing inbound messages.
type ErrHandler func(*Conn, *Subscription, error)
// UserJWTHandler is used to fetch and return the account signed
// JWT for this user.
type UserJWTHandler func() (string, error)
// SignatureHandler is used to sign a nonce from the server while
// authenticating with nkeys. The user should sign the nonce and
// return the raw signature. The client will base64 encode this to
// send to the server.
type SignatureHandler func([]byte) ([]byte, error)
// AuthTokenHandler is used to generate a new token.
type AuthTokenHandler func() string
// asyncCB is used to preserve order for async callbacks.
type asyncCB struct {
f func()
next *asyncCB
}
type asyncCallbacksHandler struct {
mu sync.Mutex
cond *sync.Cond
head *asyncCB
tail *asyncCB
}
// Option is a function on the options for a connection.
type Option func(*Options) error
// CustomDialer can be used to specify any dialer, not necessarily
// a *net.Dialer.
type CustomDialer interface {
Dial(network, address string) (net.Conn, error)
}
// Options can be used to create a customized connection.
type Options struct {
// Url represents a single NATS server url to which the client
// will be connecting. If the Servers option is also set, it
// then becomes the first server in the Servers array.
Url string
// Servers is a configured set of servers which this client
// will use when attempting to connect.
Servers []string
// NoRandomize configures whether we will randomize the
// server pool.
NoRandomize bool
// NoEcho configures whether the server will echo back messages
// that are sent on this connection if we also have matching subscriptions.
// Note this is supported on servers >= version 1.2. Proto 1 or greater.
NoEcho bool
// Name is an optional name label which will be sent to the server
// on CONNECT to identify the client.
Name string
// Verbose signals the server to send an OK ack for commands
// successfully processed by the server.
Verbose bool
// Pedantic signals the server whether it should be doing further
// validation of subjects.
Pedantic bool
// Secure enables TLS secure connections that skip server
// verification by default. NOT RECOMMENDED.
Secure bool
// TLSConfig is a custom TLS configuration to use for secure
// transports.
TLSConfig *tls.Config
// AllowReconnect enables reconnection logic to be used when we
// encounter a disconnect from the current server.
AllowReconnect bool
// MaxReconnect sets the number of reconnect attempts that will be
// tried before giving up. If negative, then it will never give up
// trying to reconnect.
MaxReconnect int
// ReconnectWait sets the time to backoff after attempting a reconnect
// to a server that we were already connected to previously.
ReconnectWait time.Duration
// Timeout sets the timeout for a Dial operation on a connection.
Timeout time.Duration
// DrainTimeout sets the timeout for a Drain Operation to complete.
DrainTimeout time.Duration
// FlusherTimeout is the maximum time to wait for write operations
// to the underlying connection to complete (including the flusher loop).
FlusherTimeout time.Duration
// PingInterval is the period at which the client will be sending ping
// commands to the server, disabled if 0 or negative.
PingInterval time.Duration
// MaxPingsOut is the maximum number of pending ping commands that can
// be awaiting a response before raising an ErrStaleConnection error.
MaxPingsOut int
// ClosedCB sets the closed handler that is called when a client will
// no longer be connected.
ClosedCB ConnHandler
// DisconnectedCB sets the disconnected handler that is called
// whenever the connection is disconnected.
// Will not be called if DisconnectedErrCB is set
// DEPRECATED. Use DisconnectedErrCB which passes error that caused
// the disconnect event.
DisconnectedCB ConnHandler
// DisconnectedErrCB sets the disconnected error handler that is called
// whenever the connection is disconnected.
// Disconnected error could be nil, for instance when user explicitly closes the connection.
// DisconnectedCB will not be called if DisconnectedErrCB is set
DisconnectedErrCB ConnErrHandler
// ReconnectedCB sets the reconnected handler called whenever
// the connection is successfully reconnected.
ReconnectedCB ConnHandler
// DiscoveredServersCB sets the callback that is invoked whenever a new
// server has joined the cluster.
DiscoveredServersCB ConnHandler
// AsyncErrorCB sets the async error handler (e.g. slow consumer errors)
AsyncErrorCB ErrHandler
// ReconnectBufSize is the size of the backing bufio during reconnect.
// Once this has been exhausted publish operations will return an error.
ReconnectBufSize int
// SubChanLen is the size of the buffered channel used between the socket
// Go routine and the message delivery for SyncSubscriptions.
// NOTE: This does not affect AsyncSubscriptions which are
// dictated by PendingLimits()
SubChanLen int
// UserJWT sets the callback handler that will fetch a user's JWT.
UserJWT UserJWTHandler
// Nkey sets the public nkey that will be used to authenticate
// when connecting to the server. UserJWT and Nkey are mutually exclusive
// and if defined, UserJWT will take precedence.
Nkey string
// SignatureCB designates the function used to sign the nonce
// presented from the server.
SignatureCB SignatureHandler
// User sets the username to be used when connecting to the server.
User string
// Password sets the password to be used when connecting to a server.
Password string
// Token sets the token to be used when connecting to a server.
Token string
// TokenHandler designates the function used to generate the token to be used when connecting to a server.
TokenHandler AuthTokenHandler
// Dialer allows a custom net.Dialer when forming connections.
// DEPRECATED: should use CustomDialer instead.
Dialer *net.Dialer
// CustomDialer allows to specify a custom dialer (not necessarily
// a *net.Dialer).
CustomDialer CustomDialer
// UseOldRequestStyle forces the old method of Requests that utilize
// a new Inbox and a new Subscription for each request.
UseOldRequestStyle bool
// NoCallbacksAfterClientClose allows preventing the invocation of
// callbacks after Close() is called. Client won't receive notifications
// when Close is invoked by user code. Default is to invoke the callbacks.
NoCallbacksAfterClientClose bool
}
const (
// Scratch storage for assembling protocol headers
scratchSize = 512
// The size of the bufio reader/writer on top of the socket.
defaultBufSize = 32768
// The buffered size of the flush "kick" channel
flushChanSize = 1
// Default server pool size
srvPoolSize = 4
// NUID size
nuidSize = 22
// Default port used if none is specified in given URL(s)
defaultPortString = "4222"
)
// A Conn represents a bare connection to a nats-server.
// It can send and receive []byte payloads.
// The connection is safe to use in multiple Go routines concurrently.
type Conn struct {
// Keep all members for which we use atomic at the beginning of the
// struct and make sure they are all 64bits (or use padding if necessary).
// atomic.* functions crash on 32bit machines if operand is not aligned
// at 64bit. See https://github.com/golang/go/issues/599
Statistics
mu sync.RWMutex
// Opts holds the configuration of the Conn.
// Modifying the configuration of a running Conn is a race.
Opts Options
wg sync.WaitGroup
srvPool []*srv
current *srv
urls map[string]struct{} // Keep track of all known URLs (used by processInfo)
conn net.Conn
bw *bufio.Writer
pending *bytes.Buffer
fch chan struct{}
info serverInfo
ssid int64
subsMu sync.RWMutex
subs map[int64]*Subscription
ach *asyncCallbacksHandler
pongs []chan struct{}
scratch [scratchSize]byte
status Status
initc bool // true if the connection is performing the initial connect
err error
ps *parseState
ptmr *time.Timer
pout int
ar bool // abort reconnect
// New style response handler
respSub string // The wildcard subject
respScanf string // The scanf template to extract mux token
respMux *Subscription // A single response subscription
respMap map[string]chan *Msg // Request map for the response msg channels
respSetup sync.Once // Ensures response subscription occurs once
respRand *rand.Rand // Used for generating suffix
}
// A Subscription represents interest in a given subject.
type Subscription struct {
mu sync.Mutex
sid int64
// Subject that represents this subscription. This can be different
// than the received subject inside a Msg if this is a wildcard.
Subject string
// Optional queue group name. If present, all subscriptions with the
// same name will form a distributed queue, and each message will
// only be processed by one member of the group.
Queue string
delivered uint64
max uint64
conn *Conn
mcb MsgHandler
mch chan *Msg
closed bool
sc bool
connClosed bool
// Type of Subscription
typ SubscriptionType
// Async linked list
pHead *Msg
pTail *Msg
pCond *sync.Cond
// Pending stats, async subscriptions, high-speed etc.
pMsgs int
pBytes int
pMsgsMax int
pBytesMax int
pMsgsLimit int
pBytesLimit int
dropped int
}
// Msg is a structure used by Subscribers and PublishMsg().
type Msg struct {
Subject string
Reply string
Data []byte
Sub *Subscription
next *Msg
barrier *barrierInfo
}
type barrierInfo struct {
refs int64
f func()
}
// Tracks various stats received and sent on this connection,
// including counts for messages and bytes.
type Statistics struct {
InMsgs uint64
OutMsgs uint64
InBytes uint64
OutBytes uint64
Reconnects uint64
}
// Tracks individual backend servers.
type srv struct {
url *url.URL
didConnect bool
reconnects int
lastAttempt time.Time
lastErr error
isImplicit bool
tlsName string
}
type serverInfo struct {
Id string `json:"server_id"`
Host string `json:"host"`
Port uint `json:"port"`
Version string `json:"version"`
AuthRequired bool `json:"auth_required"`
TLSRequired bool `json:"tls_required"`
MaxPayload int64 `json:"max_payload"`
ConnectURLs []string `json:"connect_urls,omitempty"`
Proto int `json:"proto,omitempty"`
CID uint64 `json:"client_id,omitempty"`
Nonce string `json:"nonce,omitempty"`
}
const (
// clientProtoZero is the original client protocol from 2009.
// http://nats.io/documentation/internals/nats-protocol/
/* clientProtoZero */ _ = iota
// clientProtoInfo signals a client can receive more then the original INFO block.
// This can be used to update clients on other cluster members, etc.
clientProtoInfo
)
type connectInfo struct {
Verbose bool `json:"verbose"`
Pedantic bool `json:"pedantic"`
UserJWT string `json:"jwt,omitempty"`
Nkey string `json:"nkey,omitempty"`
Signature string `json:"sig,omitempty"`
User string `json:"user,omitempty"`
Pass string `json:"pass,omitempty"`
Token string `json:"auth_token,omitempty"`
TLS bool `json:"tls_required"`
Name string `json:"name"`
Lang string `json:"lang"`
Version string `json:"version"`
Protocol int `json:"protocol"`
Echo bool `json:"echo"`
}
// MsgHandler is a callback function that processes messages delivered to
// asynchronous subscribers.
type MsgHandler func(msg *Msg)
// Connect will attempt to connect to the NATS system.
// The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
// Comma separated arrays are also supported, e.g. urlA, urlB.
// Options start with the defaults but can be overridden.
func Connect(url string, options ...Option) (*Conn, error) {
opts := GetDefaultOptions()
opts.Servers = processUrlString(url)
for _, opt := range options {
if opt != nil {
if err := opt(&opts); err != nil {
return nil, err
}
}
}
return opts.Connect()
}
// Options that can be passed to Connect.
// Name is an Option to set the client name.
func Name(name string) Option {
return func(o *Options) error {
o.Name = name
return nil
}
}
// Secure is an Option to enable TLS secure connections that skip server verification by default.
// Pass a TLS Configuration for proper TLS.
// NOTE: This should NOT be used in a production setting.
func Secure(tls ...*tls.Config) Option {
return func(o *Options) error {
o.Secure = true
// Use of variadic just simplifies testing scenarios. We only take the first one.
if len(tls) > 1 {
return ErrMultipleTLSConfigs
}
if len(tls) == 1 {
o.TLSConfig = tls[0]
}
return nil
}
}
// RootCAs is a helper option to provide the RootCAs pool from a list of filenames.
// If Secure is not already set this will set it as well.
func RootCAs(file ...string) Option {
return func(o *Options) error {
pool := x509.NewCertPool()
for _, f := range file {
rootPEM, err := ioutil.ReadFile(f)
if err != nil || rootPEM == nil {
return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err)
}
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return fmt.Errorf("nats: failed to parse root certificate from %q", f)
}
}
if o.TLSConfig == nil {
o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
o.TLSConfig.RootCAs = pool
o.Secure = true
return nil
}
}
// ClientCert is a helper option to provide the client certificate from a file.
// If Secure is not already set this will set it as well.
func ClientCert(certFile, keyFile string) Option {
return func(o *Options) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return fmt.Errorf("nats: error loading client certificate: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return fmt.Errorf("nats: error parsing client certificate: %v", err)
}
if o.TLSConfig == nil {
o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
o.TLSConfig.Certificates = []tls.Certificate{cert}
o.Secure = true
return nil
}
}
// NoReconnect is an Option to turn off reconnect behavior.
func NoReconnect() Option {
return func(o *Options) error {
o.AllowReconnect = false
return nil
}
}
// DontRandomize is an Option to turn off randomizing the server pool.
func DontRandomize() Option {
return func(o *Options) error {
o.NoRandomize = true
return nil
}
}
// NoEcho is an Option to turn off messages echoing back from a server.
// Note this is supported on servers >= version 1.2. Proto 1 or greater.
func NoEcho() Option {
return func(o *Options) error {
o.NoEcho = true
return nil
}
}
// ReconnectWait is an Option to set the wait time between reconnect attempts.
func ReconnectWait(t time.Duration) Option {
return func(o *Options) error {
o.ReconnectWait = t
return nil
}
}
// MaxReconnects is an Option to set the maximum number of reconnect attempts.
func MaxReconnects(max int) Option {
return func(o *Options) error {
o.MaxReconnect = max
return nil
}
}
// PingInterval is an Option to set the period for client ping commands.
func PingInterval(t time.Duration) Option {
return func(o *Options) error {
o.PingInterval = t
return nil
}
}
// MaxPingsOutstanding is an Option to set the maximum number of ping requests
// that can go un-answered by the server before closing the connection.
func MaxPingsOutstanding(max int) Option {
return func(o *Options) error {
o.MaxPingsOut = max
return nil
}
}
// ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
func ReconnectBufSize(size int) Option {
return func(o *Options) error {
o.ReconnectBufSize = size
return nil
}
}
// Timeout is an Option to set the timeout for Dial on a connection.
func Timeout(t time.Duration) Option {
return func(o *Options) error {
o.Timeout = t
return nil
}
}
// FlusherTimeout is an Option to set the write (and flush) timeout on a connection.
func FlusherTimeout(t time.Duration) Option {
return func(o *Options) error {
o.FlusherTimeout = t
return nil
}
}
// DrainTimeout is an Option to set the timeout for draining a connection.
func DrainTimeout(t time.Duration) Option {
return func(o *Options) error {
o.DrainTimeout = t
return nil
}
}
// DisconnectErrHandler is an Option to set the disconnected error handler.
func DisconnectErrHandler(cb ConnErrHandler) Option {
return func(o *Options) error {
o.DisconnectedErrCB = cb
return nil
}
}
// DisconnectHandler is an Option to set the disconnected handler.
// DEPRECATED: Use DisconnectErrHandler.
func DisconnectHandler(cb ConnHandler) Option {
return func(o *Options) error {
o.DisconnectedCB = cb
return nil
}
}
// ReconnectHandler is an Option to set the reconnected handler.
func ReconnectHandler(cb ConnHandler) Option {
return func(o *Options) error {
o.ReconnectedCB = cb
return nil
}
}
// ClosedHandler is an Option to set the closed handler.
func ClosedHandler(cb ConnHandler) Option {
return func(o *Options) error {
o.ClosedCB = cb
return nil
}
}
// DiscoveredServersHandler is an Option to set the new servers handler.
func DiscoveredServersHandler(cb ConnHandler) Option {
return func(o *Options) error {
o.DiscoveredServersCB = cb
return nil
}
}
// ErrorHandler is an Option to set the async error handler.
func ErrorHandler(cb ErrHandler) Option {
return func(o *Options) error {
o.AsyncErrorCB = cb
return nil
}
}
// UserInfo is an Option to set the username and password to
// use when not included directly in the URLs.
func UserInfo(user, password string) Option {
return func(o *Options) error {
o.User = user
o.Password = password
return nil
}
}
// Token is an Option to set the token to use
// when a token is not included directly in the URLs
// and when a token handler is not provided.
func Token(token string) Option {
return func(o *Options) error {
if o.TokenHandler != nil {
return ErrTokenAlreadySet
}
o.Token = token
return nil
}
}
// TokenHandler is an Option to set the token handler to use
// when a token is not included directly in the URLs
// and when a token is not set.
func TokenHandler(cb AuthTokenHandler) Option {
return func(o *Options) error {
if o.Token != "" {
return ErrTokenAlreadySet
}
o.TokenHandler = cb
return nil
}
}
// UserCredentials is a convenience function that takes a filename
// for a user's JWT and a filename for the user's private Nkey seed.
func UserCredentials(userOrChainedFile string, seedFiles ...string) Option {
userCB := func() (string, error) {
return userFromFile(userOrChainedFile)
}
var keyFile string
if len(seedFiles) > 0 {
keyFile = seedFiles[0]
} else {
keyFile = userOrChainedFile
}
sigCB := func(nonce []byte) ([]byte, error) {
return sigHandler(nonce, keyFile)
}
return UserJWT(userCB, sigCB)
}
// UserJWT will set the callbacks to retrieve the user's JWT and
// the signature callback to sign the server nonce. This an the Nkey
// option are mutually exclusive.
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option {
return func(o *Options) error {
if userCB == nil {
return ErrNoUserCB
}
if sigCB == nil {
return ErrUserButNoSigCB
}
o.UserJWT = userCB
o.SignatureCB = sigCB
return nil
}
}
// Nkey will set the public Nkey and the signature callback to
// sign the server nonce.
func Nkey(pubKey string, sigCB SignatureHandler) Option {
return func(o *Options) error {
o.Nkey = pubKey
o.SignatureCB = sigCB
if pubKey != "" && sigCB == nil {
return ErrNkeyButNoSigCB
}
return nil
}
}
// SyncQueueLen will set the maximum queue len for the internal
// channel used for SubscribeSync().
func SyncQueueLen(max int) Option {
return func(o *Options) error {
o.SubChanLen = max
return nil
}
}
// Dialer is an Option to set the dialer which will be used when
// attempting to establish a connection.
// DEPRECATED: Should use CustomDialer instead.
func Dialer(dialer *net.Dialer) Option {
return func(o *Options) error {
o.Dialer = dialer
return nil
}
}
// SetCustomDialer is an Option to set a custom dialer which will be
// used when attempting to establish a connection. If both Dialer
// and CustomDialer are specified, CustomDialer takes precedence.
func SetCustomDialer(dialer CustomDialer) Option {
return func(o *Options) error {
o.CustomDialer = dialer
return nil
}
}
// UseOldRequestStyle is an Option to force usage of the old Request style.
func UseOldRequestStyle() Option {
return func(o *Options) error {
o.UseOldRequestStyle = true
return nil
}
}
// NoCallbacksAfterClientClose is an Option to disable callbacks when user code
// calls Close(). If close is initiated by any other condition, callbacks
// if any will be invoked.
func NoCallbacksAfterClientClose() Option {
return func(o *Options) error {
o.NoCallbacksAfterClientClose = true
return nil
}
}
// Handler processing
// SetDisconnectHandler will set the disconnect event handler.
// DEPRECATED: Use SetDisconnectErrHandler
func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DisconnectedCB = dcb
}
// SetDisconnectErrHandler will set the disconnect event handler.
func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DisconnectedErrCB = dcb
}
// SetReconnectHandler will set the reconnect event handler.
func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ReconnectedCB = rcb
}
// SetDiscoveredServersHandler will set the discovered servers handler.
func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DiscoveredServersCB = dscb
}
// SetClosedHandler will set the reconnect event handler.
func (nc *Conn) SetClosedHandler(cb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ClosedCB = cb
}
// SetErrorHandler will set the async error handler.
func (nc *Conn) SetErrorHandler(cb ErrHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.AsyncErrorCB = cb
}
// Process the url string argument to Connect.
// Return an array of urls, even if only one.
func processUrlString(url string) []string {
urls := strings.Split(url, ",")
for i, s := range urls {
urls[i] = strings.TrimSpace(s)
}
return urls
}
// Connect will attempt to connect to a NATS server with multiple options.
func (o Options) Connect() (*Conn, error) {
nc := &Conn{Opts: o}
// Some default options processing.
if nc.Opts.MaxPingsOut == 0 {
nc.Opts.MaxPingsOut = DefaultMaxPingOut
}
// Allow old default for channel length to work correctly.
if nc.Opts.SubChanLen == 0 {
nc.Opts.SubChanLen = DefaultMaxChanLen
}
// Default ReconnectBufSize
if nc.Opts.ReconnectBufSize == 0 {
nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
}
// Ensure that Timeout is not 0
if nc.Opts.Timeout == 0 {
nc.Opts.Timeout = DefaultTimeout
}
// Check first for user jwt callback being defined and nkey.
if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
return nil, ErrNkeyAndUser
}
// Check if we have an nkey but no signature callback defined.
if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
return nil, ErrNkeyButNoSigCB
}
// Allow custom Dialer for connecting using DialTimeout by default
if nc.Opts.Dialer == nil {
nc.Opts.Dialer = &net.Dialer{
Timeout: nc.Opts.Timeout,
}
}
if err := nc.setupServerPool(); err != nil {
return nil, err
}
// Create the async callback handler.
nc.ach = &asyncCallbacksHandler{}
nc.ach.cond = sync.NewCond(&nc.ach.mu)
if err := nc.connect(); err != nil {
return nil, err
}
// Spin up the async cb dispatcher on success
go nc.ach.asyncCBDispatcher()
return nc, nil
}
const (
_CRLF_ = "\r\n"
_EMPTY_ = ""
_SPC_ = " "
_PUB_P_ = "PUB "
)
const (
_OK_OP_ = "+OK"
_ERR_OP_ = "-ERR"
_PONG_OP_ = "PONG"
_INFO_OP_ = "INFO"
)
const (
conProto = "CONNECT %s" + _CRLF_
pingProto = "PING" + _CRLF_
pongProto = "PONG" + _CRLF_
subProto = "SUB %s %s %d" + _CRLF_
unsubProto = "UNSUB %d %s" + _CRLF_
okProto = _OK_OP_ + _CRLF_
)
// Return the currently selected server
func (nc *Conn) currentServer() (int, *srv) {
for i, s := range nc.srvPool {
if s == nil {
continue
}
if s == nc.current {
return i, s
}
}
return -1, nil
}
// Pop the current server and put onto the end of the list. Select head of list as long
// as number of reconnect attempts under MaxReconnect.
func (nc *Conn) selectNextServer() (*srv, error) {
i, s := nc.currentServer()
if i < 0 {
return nil, ErrNoServers
}
sp := nc.srvPool
num := len(sp)
copy(sp[i:num-1], sp[i+1:num])
maxReconnect := nc.Opts.MaxReconnect
if maxReconnect < 0 || s.reconnects < maxReconnect {
nc.srvPool[num-1] = s
} else {
nc.srvPool = sp[0 : num-1]
}
if len(nc.srvPool) <= 0 {
nc.current = nil
return nil, ErrNoServers
}
nc.current = nc.srvPool[0]
return nc.srvPool[0], nil
}
// Will assign the correct server to nc.current
func (nc *Conn) pickServer() error {
nc.current = nil
if len(nc.srvPool) <= 0 {
return ErrNoServers
}
for _, s := range nc.srvPool {
if s != nil {
nc.current = s
return nil
}
}
return ErrNoServers
}
const tlsScheme = "tls"
// Create the server pool using the options given.
// We will place a Url option first, followed by any
// Server Options. We will randomize the server pool unless
// the NoRandomize flag is set.
func (nc *Conn) setupServerPool() error {
nc.srvPool = make([]*srv, 0, srvPoolSize)
nc.urls = make(map[string]struct{}, srvPoolSize)
// Create srv objects from each url string in nc.Opts.Servers
// and add them to the pool.
for _, urlString := range nc.Opts.Servers {
if err := nc.addURLToPool(urlString, false, false); err != nil {
return err
}
}
// Randomize if allowed to
if !nc.Opts.NoRandomize {
nc.shufflePool()
}
// Normally, if this one is set, Options.Servers should not be,
// but we always allowed that, so continue to do so.
if nc.Opts.Url != _EMPTY_ {
// Add to the end of the array
if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
return err
}
// Then swap it with first to guarantee that Options.Url is tried first.
last := len(nc.srvPool) - 1
if last > 0 {
nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
}
} else if len(nc.srvPool) <= 0 {
// Place default URL if pool is empty.
if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
return err
}
}
// Check for Scheme hint to move to TLS mode.
for _, srv := range nc.srvPool {
if srv.url.Scheme == tlsScheme {
// FIXME(dlc), this is for all in the pool, should be case by case.
nc.Opts.Secure = true
if nc.Opts.TLSConfig == nil {
nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
}
}
return nc.pickServer()
}
// Helper function to return scheme
func (nc *Conn) connScheme() string {
if nc.Opts.Secure {
return tlsScheme
}
return "nats"
}
// Return true iff u.Hostname() is an IP address.
func hostIsIP(u *url.URL) bool {
return net.ParseIP(u.Hostname()) != nil
}
// addURLToPool adds an entry to the server pool
func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
if !strings.Contains(sURL, "://") {
sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
}
var (
u *url.URL
err error
)
for i := 0; i < 2; i++ {
u, err = url.Parse(sURL)
if err != nil {
return err
}
if u.Port() != "" {
break
}
// In case given URL is of the form "localhost:", just add
// the port number at the end, otherwise, add ":4222".
if sURL[len(sURL)-1] != ':' {
sURL += ":"
}
sURL += defaultPortString
}
var tlsName string
if implicit {
curl := nc.current.url
// Check to see if we do not have a url.User but current connected
// url does. If so copy over.
if u.User == nil && curl.User != nil {
u.User = curl.User
}
// We are checking to see if we have a secure connection and are
// adding an implicit server that just has an IP. If so we will remember
// the current hostname we are connected to.
if saveTLSName && hostIsIP(u) {
tlsName = curl.Hostname()
}
}
s := &srv{url: u, isImplicit: implicit, tlsName: tlsName}
nc.srvPool = append(nc.srvPool, s)
nc.urls[u.Host] = struct{}{}
return nil
}
// shufflePool swaps randomly elements in the server pool
func (nc *Conn) shufflePool() {
if len(nc.srvPool) <= 1 {
return
}
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range nc.srvPool {
j := r.Intn(i + 1)
nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
}
}
func (nc *Conn) newBuffer() *bufio.Writer {
var w io.Writer = nc.conn
if nc.Opts.FlusherTimeout > 0 {
w = &timeoutWriter{conn: nc.conn, timeout: nc.Opts.FlusherTimeout}
}
return bufio.NewWriterSize(w, defaultBufSize)
}
// createConn will connect to the server and wrap the appropriate
// bufio structures. It will do the right thing when an existing
// connection is in place.
func (nc *Conn) createConn() (err error) {
if nc.Opts.Timeout < 0 {
return ErrBadTimeout
}
if _, cur := nc.currentServer(); cur == nil {
return ErrNoServers
} else {
cur.lastAttempt = time.Now()
}
// We will auto-expand host names if they resolve to multiple IPs
hosts := []string{}
u := nc.current.url
if net.ParseIP(u.Hostname()) == nil {
addrs, _ := net.LookupHost(u.Hostname())
for _, addr := range addrs {
hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
}
}
// Fall back to what we were given.
if len(hosts) == 0 {
hosts = append(hosts, u.Host)
}
// CustomDialer takes precedence. If not set, use Opts.Dialer which
// is set to a default *net.Dialer (in Connect()) if not explicitly
// set by the user.
dialer := nc.Opts.CustomDialer
if dialer == nil {
// We will copy and shorten the timeout if we have multiple hosts to try.
copyDialer := *nc.Opts.Dialer
copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
dialer = ©Dialer
}
if len(hosts) > 1 && !nc.Opts.NoRandomize {
rand.Shuffle(len(hosts), func(i, j int) {
hosts[i], hosts[j] = hosts[j], hosts[i]
})
}
for _, host := range hosts {
nc.conn, err = dialer.Dial("tcp", host)
if err == nil {
break
}
}
if err != nil {
return err
}
// No clue why, but this stalls and kills performance on Mac (Mavericks).
// https://code.google.com/p/go/issues/detail?id=6930
//if ip, ok := nc.conn.(*net.TCPConn); ok {
// ip.SetReadBuffer(defaultBufSize)
//}
if nc.pending != nil && nc.bw != nil {
// Move to pending buffer.
nc.bw.Flush()
}
nc.bw = nc.newBuffer()
return nil
}
// makeTLSConn will wrap an existing Conn using TLS
func (nc *Conn) makeTLSConn() error {
// Allow the user to configure their own tls.Config structure.
var tlsCopy *tls.Config
if nc.Opts.TLSConfig != nil {
tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
} else {
tlsCopy = &tls.Config{}
}
// If its blank we will override it with the current host
if tlsCopy.ServerName == _EMPTY_ {
if nc.current.tlsName != _EMPTY_ {
tlsCopy.ServerName = nc.current.tlsName
} else {
h, _, _ := net.SplitHostPort(nc.current.url.Host)
tlsCopy.ServerName = h
}
}
nc.conn = tls.Client(nc.conn, tlsCopy)
conn := nc.conn.(*tls.Conn)
if err := conn.Handshake(); err != nil {
return err
}
nc.bw = nc.newBuffer()
return nil
}
// waitForExits will wait for all socket watcher Go routines to
// be shutdown before proceeding.
func (nc *Conn) waitForExits() {
// Kick old flusher forcefully.
select {
case nc.fch <- struct{}{}:
default:
}
// Wait for any previous go routines.
nc.wg.Wait()
}
// Report the connected server's Url
func (nc *Conn) ConnectedUrl() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.current.url.String()
}
// ConnectedAddr returns the connected server's IP
func (nc *Conn) ConnectedAddr() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.conn.RemoteAddr().String()
}
// Report the connected server's Id
func (nc *Conn) ConnectedServerId() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.info.Id
}
// Low level setup for structs, etc
func (nc *Conn) setup() {
nc.subs = make(map[int64]*Subscription)
nc.pongs = make([]chan struct{}, 0, 8)
nc.fch = make(chan struct{}, flushChanSize)
// Setup scratch outbound buffer for PUB
pub := nc.scratch[:len(_PUB_P_)]
copy(pub, _PUB_P_)
}
// Process a connected connection and initialize properly.
func (nc *Conn) processConnectInit() error {
// Set our deadline for the whole connect process
nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
defer nc.conn.SetDeadline(time.Time{})
// Set our status to connecting.
nc.status = CONNECTING
// Process the INFO protocol received from the server
err := nc.processExpectedInfo()
if err != nil {
return err
}
// Send the CONNECT protocol along with the initial PING protocol.
// Wait for the PONG response (or any error that we get from the server).
err = nc.sendConnect()
if err != nil {
return err
}
// Reset the number of PING sent out
nc.pout = 0
// Start or reset Timer
if nc.Opts.PingInterval > 0 {
if nc.ptmr == nil {
nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
} else {
nc.ptmr.Reset(nc.Opts.PingInterval)
}
}
// Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
nc.wg.Add(2)
go nc.readLoop()
go nc.flusher()
return nil
}
// Main connect function. Will connect to the nats-server
func (nc *Conn) connect() error {
var returnedErr error
// Create actual socket connection
// For first connect we walk all servers in the pool and try
// to connect immediately.
nc.mu.Lock()
nc.initc = true
// The pool may change inside the loop iteration due to INFO protocol.
for i := 0; i < len(nc.srvPool); i++ {
nc.current = nc.srvPool[i]
if err := nc.createConn(); err == nil {
// This was moved out of processConnectInit() because
// that function is now invoked from doReconnect() too.
nc.setup()
err = nc.processConnectInit()
if err == nil {
nc.srvPool[i].didConnect = true
nc.srvPool[i].reconnects = 0
nc.current.lastErr = nil
returnedErr = nil
break
} else {
returnedErr = err
nc.mu.Unlock()
nc.close(DISCONNECTED, false, err)
nc.mu.Lock()
nc.current = nil
}
} else {
// Cancel out default connection refused, will trigger the
// No servers error conditional
if strings.Contains(err.Error(), "connection refused") {
returnedErr = nil
}
}
}
nc.initc = false
if returnedErr == nil && nc.status != CONNECTED {
returnedErr = ErrNoServers
}
nc.mu.Unlock()
return returnedErr
}
// This will check to see if the connection should be
// secure. This can be dictated from either end and should
// only be called after the INIT protocol has been received.
func (nc *Conn) checkForSecure() error {
// Check to see if we need to engage TLS
o := nc.Opts
// Check for mismatch in setups
if o.Secure && !nc.info.TLSRequired {
return ErrSecureConnWanted
} else if nc.info.TLSRequired && !o.Secure {
// Switch to Secure since server needs TLS.
o.Secure = true
}
// Need to rewrap with bufio
if o.Secure {
if err := nc.makeTLSConn(); err != nil {
return err
}
}
return nil
}
// processExpectedInfo will look for the expected first INFO message
// sent when a connection is established. The lock should be held entering.
func (nc *Conn) processExpectedInfo() error {
c := &control{}
// Read the protocol
err := nc.readOp(c)
if err != nil {
return err
}
// The nats protocol should send INFO first always.
if c.op != _INFO_OP_ {
return ErrNoInfoReceived
}
// Parse the protocol
if err := nc.processInfo(c.args); err != nil {
return err
}
if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
return ErrNkeysNotSupported
}
return nc.checkForSecure()
}
// Sends a protocol control message by queuing into the bufio writer
// and kicking the flush Go routine. These writes are protected.
func (nc *Conn) sendProto(proto string) {
nc.mu.Lock()
nc.bw.WriteString(proto)
nc.kickFlusher()
nc.mu.Unlock()
}
// Generate a connect protocol message, issuing user/password if
// applicable. The lock is assumed to be held upon entering.
func (nc *Conn) connectProto() (string, error) {
o := nc.Opts
var nkey, sig, user, pass, token, ujwt string
u := nc.current.url.User
if u != nil {
// if no password, assume username is authToken
if _, ok := u.Password(); !ok {
token = u.Username()
} else {
user = u.Username()
pass, _ = u.Password()
}
} else {
// Take from options (possibly all empty strings)
user = o.User
pass = o.Password
token = o.Token
nkey = o.Nkey
}
// Look for user jwt.
if o.UserJWT != nil {
if jwt, err := o.UserJWT(); err != nil {
return _EMPTY_, err
} else {
ujwt = jwt
}
if nkey != _EMPTY_ {
return _EMPTY_, ErrNkeyAndUser
}
}
if ujwt != _EMPTY_ || nkey != _EMPTY_ {
if o.SignatureCB == nil {
if ujwt == _EMPTY_ {
return _EMPTY_, ErrNkeyButNoSigCB
}
return _EMPTY_, ErrUserButNoSigCB
}
sigraw, err := o.SignatureCB([]byte(nc.info.Nonce))
if err != nil {
return _EMPTY_, err
}
sig = base64.RawURLEncoding.EncodeToString(sigraw)
}
if nc.Opts.TokenHandler != nil {
if token != _EMPTY_ {
return _EMPTY_, ErrTokenAlreadySet
}
token = nc.Opts.TokenHandler()
}
cinfo := connectInfo{o.Verbose, o.Pedantic, ujwt, nkey, sig, user, pass, token,
o.Secure, o.Name, LangString, Version, clientProtoInfo, !o.NoEcho}
b, err := json.Marshal(cinfo)
if err != nil {
return _EMPTY_, ErrJsonParse
}
// Check if NoEcho is set and we have a server that supports it.
if o.NoEcho && nc.info.Proto < 1 {
return _EMPTY_, ErrNoEchoNotSupported
}
return fmt.Sprintf(conProto, b), nil
}
// normalizeErr removes the prefix -ERR, trim spaces and remove the quotes.
func normalizeErr(line string) string {
s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
return s
}
// Send a connect protocol message to the server, issue user/password if
// applicable. Will wait for a flush to return from the server for error
// processing.
func (nc *Conn) sendConnect() error {
// Construct the CONNECT protocol string
cProto, err := nc.connectProto()
if err != nil {
return err
}
// Write the protocol into the buffer
_, err = nc.bw.WriteString(cProto)
if err != nil {
return err
}
// Add to the buffer the PING protocol
_, err = nc.bw.WriteString(pingProto)
if err != nil {
return err
}
// Flush the buffer
err = nc.bw.Flush()
if err != nil {
return err
}
// We don't want to read more than we need here, otherwise
// we would need to transfer the excess read data to the readLoop.
// Since in normal situations we just are looking for a PONG\r\n,
// reading byte-by-byte here is ok.
proto, err := nc.readProto()
if err != nil {
return err
}
// If opts.Verbose is set, handle +OK
if nc.Opts.Verbose && proto == okProto {
// Read the rest now...
proto, err = nc.readProto()
if err != nil {
return err
}
}
// We expect a PONG
if proto != pongProto {
// But it could be something else, like -ERR
// Since we no longer use ReadLine(), trim the trailing "\r\n"
proto = strings.TrimRight(proto, "\r\n")
// If it's a server error...
if strings.HasPrefix(proto, _ERR_OP_) {
// Remove -ERR, trim spaces and quotes, and convert to lower case.
proto = normalizeErr(proto)
// Check if this is an auth error
if authErr := checkAuthError(strings.ToLower(proto)); authErr != nil {
// This will schedule an async error if we are in reconnect,
// and keep track of the auth error for the current server.
// If we have got the same error twice, this sets nc.ar to true to
// indicate that the reconnect should be aborted (will be checked
// in doReconnect()).
nc.processAuthError(authErr)
}
return errors.New("nats: " + proto)
}
// Notify that we got an unexpected protocol.
return fmt.Errorf("nats: expected '%s', got '%s'", _PONG_OP_, proto)
}
// This is where we are truly connected.
nc.status = CONNECTED
return nil
}
// reads a protocol one byte at a time.
func (nc *Conn) readProto() (string, error) {
var (
_buf = [10]byte{}
buf = _buf[:0]
b = [1]byte{}
protoEnd = byte('\n')
)
for {
if _, err := nc.conn.Read(b[:1]); err != nil {
// Do not report EOF error
if err == io.EOF {
return string(buf), nil
}
return "", err
}
buf = append(buf, b[0])
if b[0] == protoEnd {
return string(buf), nil
}
}
}
// A control protocol line.
type control struct {
op, args string
}
// Read a control line and process the intended op.
func (nc *Conn) readOp(c *control) error {
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
line, err := br.ReadString('\n')
if err != nil {
return err
}
parseControl(line, c)
return nil
}
// Parse a control line from the server.
func parseControl(line string, c *control) {
toks := strings.SplitN(line, _SPC_, 2)
if len(toks) == 1 {
c.op = strings.TrimSpace(toks[0])
c.args = _EMPTY_
} else if len(toks) == 2 {
c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
} else {
c.op = _EMPTY_
}
}
// flushReconnectPending will push the pending items that were
// gathered while we were in a RECONNECTING state to the socket.
func (nc *Conn) flushReconnectPendingItems() {
if nc.pending == nil {
return
}
if nc.pending.Len() > 0 {
nc.bw.Write(nc.pending.Bytes())
}
}
// Stops the ping timer if set.
// Connection lock is held on entry.
func (nc *Conn) stopPingTimer() {
if nc.ptmr != nil {
nc.ptmr.Stop()
}
}
// Try to reconnect using the option parameters.
// This function assumes we are allowed to reconnect.
func (nc *Conn) doReconnect(err error) {
// We want to make sure we have the other watchers shutdown properly
// here before we proceed past this point.
nc.waitForExits()
// FIXME(dlc) - We have an issue here if we have
// outstanding flush points (pongs) and they were not
// sent out, but are still in the pipe.
// Hold the lock manually and release where needed below,
// can't do defer here.
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any errors.
nc.err = nil
// Perform appropriate callback if needed for a disconnect.
// DisconnectedErrCB has priority over deprecated DisconnectedCB
if nc.Opts.DisconnectedErrCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) })
} else if nc.Opts.DisconnectedCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
// This is used to wait on go routines exit if we start them in the loop
// but an error occurs after that.
waitForGoRoutines := false
for len(nc.srvPool) > 0 {
cur, err := nc.selectNextServer()
if err != nil {
nc.err = err
break
}
sleepTime := int64(0)
// Sleep appropriate amount of time before the
// connection attempt if connecting to same server
// we just got disconnected from..
if time.Since(cur.lastAttempt) < nc.Opts.ReconnectWait {
sleepTime = int64(nc.Opts.ReconnectWait - time.Since(cur.lastAttempt))
}
// On Windows, createConn() will take more than a second when no
// server is running at that address. So it could be that the
// time elapsed between reconnect attempts is always > than
// the set option. Release the lock to give a chance to a parallel
// nc.Close() to break the loop.
nc.mu.Unlock()
if sleepTime <= 0 {
runtime.Gosched()
} else {
time.Sleep(time.Duration(sleepTime))
}
// If the readLoop, etc.. go routines were started, wait for them to complete.
if waitForGoRoutines {
nc.waitForExits()
waitForGoRoutines = false
}
nc.mu.Lock()
// Check if we have been closed first.
if nc.isClosed() {
break
}
// Mark that we tried a reconnect
cur.reconnects++
// Try to create a new connection
err = nc.createConn()
// Not yet connected, retry...
// Continue to hold the lock
if err != nil {
nc.err = nil
continue
}
// We are reconnected
nc.Reconnects++
// Process connect logic
if nc.err = nc.processConnectInit(); nc.err != nil {
// Check if we should abort reconnect. If so, break out
// of the loop and connection will be closed.
if nc.ar {
break
}
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer
// (was set to a buffered writer on nc.conn in createConn)
nc.bw.Reset(nc.pending)
continue
}
// Clear possible lastErr under the connection lock after
// a successful processConnectInit().
nc.current.lastErr = nil
// Clear out server stats for the server we connected to..
cur.didConnect = true
cur.reconnects = 0
// Send existing subscription state
nc.resendSubscriptions()
// Now send off and clear pending buffer
nc.flushReconnectPendingItems()
// Flush the buffer
nc.err = nc.bw.Flush()
if nc.err != nil {
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer (bytes.Buffer).
nc.bw.Reset(nc.pending)
// Stop the ping timer (if set)
nc.stopPingTimer()
// Since processConnectInit() returned without error, the
// go routines were started, so wait for them to return
// on the next iteration (after releasing the lock).
waitForGoRoutines = true
continue
}
// Done with the pending buffer
nc.pending = nil
// This is where we are truly connected.
nc.status = CONNECTED
// Queue up the reconnect callback.
if nc.Opts.ReconnectedCB != nil {
nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) })
}
// Release lock here, we will return below.
nc.mu.Unlock()
// Make sure to flush everything
nc.Flush()
return
}
// Call into close.. We have no servers left..
if nc.err == nil {
nc.err = ErrNoServers
}
nc.mu.Unlock()
nc.close(CLOSED, true, nil)
}
// processOpErr handles errors from reading or parsing the protocol.
// The lock should not be held entering this function.
func (nc *Conn) processOpErr(err error) {
nc.mu.Lock()
if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
nc.mu.Unlock()
return
}
if nc.Opts.AllowReconnect && nc.status == CONNECTED {
// Set our new status
nc.status = RECONNECTING
// Stop ping timer if set
nc.stopPingTimer()
if nc.conn != nil {
nc.bw.Flush()
nc.conn.Close()
nc.conn = nil
}
// Create pending buffer before reconnecting.
nc.pending = new(bytes.Buffer)
nc.bw.Reset(nc.pending)
go nc.doReconnect(err)
nc.mu.Unlock()
return
}
nc.status = DISCONNECTED
nc.err = err
nc.mu.Unlock()
nc.close(CLOSED, true, nil)
}
// dispatch is responsible for calling any async callbacks
func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
for {
ac.mu.Lock()
// Protect for spurious wakeups. We should get out of the
// wait only if there is an element to pop from the list.
for ac.head == nil {
ac.cond.Wait()
}
cur := ac.head
ac.head = cur.next
if cur == ac.tail {
ac.tail = nil
}
ac.mu.Unlock()
// This signals that the dispatcher has been closed and all
// previous callbacks have been dispatched.
if cur.f == nil {
return
}
// Invoke callback outside of handler's lock
cur.f()
}
}
// Add the given function to the tail of the list and
// signals the dispatcher.
func (ac *asyncCallbacksHandler) push(f func()) {
ac.pushOrClose(f, false)
}
// Signals that we are closing...
func (ac *asyncCallbacksHandler) close() {
ac.pushOrClose(nil, true)
}
// Add the given function to the tail of the list and
// signals the dispatcher.
func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
ac.mu.Lock()
defer ac.mu.Unlock()
// Make sure that library is not calling push with nil function,
// since this is used to notify the dispatcher that it should stop.
if !close && f == nil {
panic("pushing a nil callback")
}
cb := &asyncCB{f: f}
if ac.tail != nil {
ac.tail.next = cb
} else {
ac.head = cb
}
ac.tail = cb
if close {
ac.cond.Broadcast()
} else {
ac.cond.Signal()
}
}
// readLoop() will sit on the socket reading and processing the
// protocol from the server. It will dispatch appropriately based
// on the op type.
func (nc *Conn) readLoop() {
// Release the wait group on exit
defer nc.wg.Done()
// Create a parseState if needed.
nc.mu.Lock()
if nc.ps == nil {
nc.ps = &parseState{}
}
nc.mu.Unlock()
// Stack based buffer.
b := make([]byte, defaultBufSize)
for {
// ps is thread safe, so RLock is okay
nc.mu.RLock()
sb := nc.isClosed() || nc.isReconnecting()
if sb {
nc.ps = &parseState{}
}
conn := nc.conn
nc.mu.RUnlock()
if sb || conn == nil {
break
}
n, err := conn.Read(b)
if err != nil {
nc.processOpErr(err)
break
}
if err := nc.parse(b[:n]); err != nil {
nc.processOpErr(err)
break
}
}
// Clear the parseState here..
nc.mu.Lock()
nc.ps = nil
nc.mu.Unlock()
}
// waitForMsgs waits on the conditional shared with readLoop and processMsg.
// It is used to deliver messages to asynchronous subscribers.
func (nc *Conn) waitForMsgs(s *Subscription) {
var closed bool
var delivered, max uint64
// Used to account for adjustments to sub.pBytes when we wrap back around.
msgLen := -1
for {
s.mu.Lock()
// Do accounting for last msg delivered here so we only lock once
// and drain state trips after callback has returned.
if msgLen >= 0 {
s.pMsgs--
s.pBytes -= msgLen
msgLen = -1
}
if s.pHead == nil && !s.closed {
s.pCond.Wait()
}
// Pop the msg off the list
m := s.pHead
if m != nil {
s.pHead = m.next
if s.pHead == nil {
s.pTail = nil
}
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
continue
}
msgLen = len(m.Data)
}
mcb := s.mcb
max = s.max
closed = s.closed
if !s.closed {
s.delivered++
delivered = s.delivered
}
s.mu.Unlock()
if closed {
break
}
// Deliver the message.
if m != nil && (max == 0 || delivered <= max) {
mcb(m)
}
// If we have hit the max for delivered msgs, remove sub.
if max > 0 && delivered >= max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
break
}
}
// Check for barrier messages
s.mu.Lock()
for m := s.pHead; m != nil; m = s.pHead {
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
s.mu.Lock()
}
s.pHead = m.next
}
s.mu.Unlock()
}
// processMsg is called by parse and will place the msg on the
// appropriate channel/pending queue for processing. If the channel is full,
// or the pending queue is over the pending limits, the connection is
// considered a slow consumer.
func (nc *Conn) processMsg(data []byte) {
// Don't lock the connection to avoid server cutting us off if the
// flusher is holding the connection lock, trying to send to the server
// that is itself trying to send data to us.
nc.subsMu.RLock()
// Stats
atomic.AddUint64(&nc.InMsgs, 1)
atomic.AddUint64(&nc.InBytes, uint64(len(data)))
sub := nc.subs[nc.ps.ma.sid]
if sub == nil {
nc.subsMu.RUnlock()
return
}
// Copy them into string
subj := string(nc.ps.ma.subject)
reply := string(nc.ps.ma.reply)
// Doing message create outside of the sub's lock to reduce contention.
// It's possible that we end-up not using the message, but that's ok.
// FIXME(dlc): Need to copy, should/can do COW?
msgPayload := make([]byte, len(data))
copy(msgPayload, data)
// FIXME(dlc): Should we recycle these containers?
m := &Msg{Data: msgPayload, Subject: subj, Reply: reply, Sub: sub}
sub.mu.Lock()
// Subscription internal stats (applicable only for non ChanSubscription's)
if sub.typ != ChanSubscription {
sub.pMsgs++
if sub.pMsgs > sub.pMsgsMax {
sub.pMsgsMax = sub.pMsgs
}
sub.pBytes += len(m.Data)
if sub.pBytes > sub.pBytesMax {
sub.pBytesMax = sub.pBytes
}
// Check for a Slow Consumer
if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) ||
(sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) {
goto slowConsumer
}
}
// We have two modes of delivery. One is the channel, used by channel
// subscribers and syncSubscribers, the other is a linked list for async.
if sub.mch != nil {
select {
case sub.mch <- m:
default:
goto slowConsumer
}
} else {
// Push onto the async pList
if sub.pHead == nil {
sub.pHead = m
sub.pTail = m
sub.pCond.Signal()
} else {
sub.pTail.next = m
sub.pTail = m
}
}
// Clear SlowConsumer status.
sub.sc = false
sub.mu.Unlock()
nc.subsMu.RUnlock()
return
slowConsumer:
sub.dropped++
sc := !sub.sc
sub.sc = true
// Undo stats from above
if sub.typ != ChanSubscription {
sub.pMsgs--
sub.pBytes -= len(m.Data)
}
sub.mu.Unlock()
nc.subsMu.RUnlock()
if sc {
// Now we need connection's lock and we may end-up in the situation
// that we were trying to avoid, except that in this case, the client
// is already experiencing client-side slow consumer situation.
nc.mu.Lock()
nc.err = ErrSlowConsumer
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrSlowConsumer) })
}
nc.mu.Unlock()
}
}
// processPermissionsViolation is called when the server signals a subject
// permissions violation on either publish or subscribe.
func (nc *Conn) processPermissionsViolation(err string) {
nc.mu.Lock()
// create error here so we can pass it as a closure to the async cb dispatcher.
e := errors.New("nats: " + err)
nc.err = e
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) })
}
nc.mu.Unlock()
}
// processAuthError generally processing for auth errors. We want to do retries
// unless we get the same error again. This allows us for instance to swap credentials
// and have the app reconnect, but if nothing is changing we should bail.
// This function will return true if the connection should be closed, false otherwise.
// Connection lock is held on entry
func (nc *Conn) processAuthError(err error) bool {
nc.err = err
if !nc.initc && nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
}
// We should give up if we tried twice on this server and got the
// same error.
if nc.current.lastErr == err {
nc.ar = true
} else {
nc.current.lastErr = err
}
return nc.ar
}
// flusher is a separate Go routine that will process flush requests for the write
// bufio. This allows coalescing of writes to the underlying socket.
func (nc *Conn) flusher() {
// Release the wait group
defer nc.wg.Done()
// snapshot the bw and conn since they can change from underneath of us.
nc.mu.Lock()
bw := nc.bw
conn := nc.conn
fch := nc.fch
nc.mu.Unlock()
if conn == nil || bw == nil {
return
}
for {
if _, ok := <-fch; !ok {
return
}
nc.mu.Lock()
// Check to see if we should bail out.
if !nc.isConnected() || nc.isConnecting() || bw != nc.bw || conn != nc.conn {
nc.mu.Unlock()
return
}
if bw.Buffered() > 0 {
if err := bw.Flush(); err != nil {
if nc.err == nil {
nc.err = err
}
}
}
nc.mu.Unlock()
}
}
// processPing will send an immediate pong protocol response to the
// server. The server uses this mechanism to detect dead clients.
func (nc *Conn) processPing() {
nc.sendProto(pongProto)
}
// processPong is used to process responses to the client's ping
// messages. We use pings for the flush mechanism as well.
func (nc *Conn) processPong() {
var ch chan struct{}
nc.mu.Lock()
if len(nc.pongs) > 0 {
ch = nc.pongs[0]
nc.pongs = nc.pongs[1:]
}
nc.pout = 0
nc.mu.Unlock()
if ch != nil {
ch <- struct{}{}
}
}
// processOK is a placeholder for processing OK messages.
func (nc *Conn) processOK() {
// do nothing
}
// processInfo is used to parse the info messages sent
// from the server.
// This function may update the server pool.
func (nc *Conn) processInfo(info string) error {
if info == _EMPTY_ {
return nil
}
ncInfo := serverInfo{}
if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
return err
}
// Copy content into connection's info structure.
nc.info = ncInfo
// The array could be empty/not present on initial connect,
// if advertise is disabled on that server, or servers that
// did not include themselves in the async INFO protocol.
// If empty, do not remove the implicit servers from the pool.
if len(ncInfo.ConnectURLs) == 0 {
return nil
}
// Note about pool randomization: when the pool was first created,
// it was randomized (if allowed). We keep the order the same (removing
// implicit servers that are no longer sent to us). New URLs are sent
// to us in no specific order so don't need extra randomization.
hasNew := false
// This is what we got from the server we are connected to.
urls := nc.info.ConnectURLs
// Transform that to a map for easy lookups
tmp := make(map[string]struct{}, len(urls))
for _, curl := range urls {
tmp[curl] = struct{}{}
}
// Walk the pool and removed the implicit servers that are no longer in the
// given array/map
sp := nc.srvPool
for i := 0; i < len(sp); i++ {
srv := sp[i]
curl := srv.url.Host
// Check if this URL is in the INFO protocol
_, inInfo := tmp[curl]
// Remove from the temp map so that at the end we are left with only
// new (or restarted) servers that need to be added to the pool.
delete(tmp, curl)
// Keep servers that were set through Options, but also the one that
// we are currently connected to (even if it is a discovered server).
if !srv.isImplicit || srv.url == nc.current.url {
continue
}
if !inInfo {
// Remove from server pool. Keep current order.
copy(sp[i:], sp[i+1:])
nc.srvPool = sp[:len(sp)-1]
sp = nc.srvPool
i--
}
}
// Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
saveTLS := nc.current != nil && !hostIsIP(nc.current.url)
// If there are any left in the tmp map, these are new (or restarted) servers
// and need to be added to the pool.
for curl := range tmp {
// Before adding, check if this is a new (as in never seen) URL.
// This is used to figure out if we invoke the DiscoveredServersCB
if _, present := nc.urls[curl]; !present {
hasNew = true
}
nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
}
if hasNew && !nc.initc && nc.Opts.DiscoveredServersCB != nil {
nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
}
return nil
}
// processAsyncInfo does the same than processInfo, but is called
// from the parser. Calls processInfo under connection's lock
// protection.
func (nc *Conn) processAsyncInfo(info []byte) {
nc.mu.Lock()
// Ignore errors, we will simply not update the server pool...
nc.processInfo(string(info))
nc.mu.Unlock()
}
// LastError reports the last error encountered via the connection.
// It can be used reliably within ClosedCB in order to find out reason
// why connection was closed for example.
func (nc *Conn) LastError() error {
if nc == nil {
return ErrInvalidConnection
}
nc.mu.RLock()
err := nc.err
nc.mu.RUnlock()
return err
}
// Check if the given error string is an auth error, and if so returns
// the corresponding ErrXXX error, nil otherwise
func checkAuthError(e string) error {
if strings.HasPrefix(e, AUTHORIZATION_ERR) {
return ErrAuthorization
}
if strings.HasPrefix(e, AUTHENTICATION_EXPIRED_ERR) {
return ErrAuthExpired
}
return nil
}
// processErr processes any error messages from the server and
// sets the connection's lastError.
func (nc *Conn) processErr(ie string) {
// Trim, remove quotes
ne := normalizeErr(ie)
// convert to lower case.
e := strings.ToLower(ne)
close := false
// FIXME(dlc) - process Slow Consumer signals special.
if e == STALE_CONNECTION {
nc.processOpErr(ErrStaleConnection)
} else if strings.HasPrefix(e, PERMISSIONS_ERR) {
nc.processPermissionsViolation(ne)
} else if authErr := checkAuthError(e); authErr != nil {
nc.mu.Lock()
close = nc.processAuthError(authErr)
nc.mu.Unlock()
} else {
close = true
nc.mu.Lock()
nc.err = errors.New("nats: " + ne)
nc.mu.Unlock()
}
if close {
nc.close(CLOSED, true, nil)
}
}
// kickFlusher will send a bool on a channel to kick the
// flush Go routine to flush data to the server.
func (nc *Conn) kickFlusher() {
if nc.bw != nil {
select {
case nc.fch <- struct{}{}:
default:
}
}
}
// Publish publishes the data argument to the given subject. The data
// argument is left untouched and needs to be correctly interpreted on
// the receiver.
func (nc *Conn) Publish(subj string, data []byte) error {
return nc.publish(subj, _EMPTY_, data)
}
// PublishMsg publishes the Msg structure, which includes the
// Subject, an optional Reply and an optional Data field.
func (nc *Conn) PublishMsg(m *Msg) error {
if m == nil {
return ErrInvalidMsg
}
return nc.publish(m.Subject, m.Reply, m.Data)
}
// PublishRequest will perform a Publish() excpecting a response on the
// reply subject. Use Request() for automatically waiting for a response
// inline.
func (nc *Conn) PublishRequest(subj, reply string, data []byte) error {
return nc.publish(subj, reply, data)
}
// Used for handrolled itoa
const digits = "0123456789"
// publish is the internal function to publish messages to a nats-server.
// Sends a protocol data message by queuing into the bufio writer
// and kicking the flush go routine. These writes should be protected.
func (nc *Conn) publish(subj, reply string, data []byte) error {
if nc == nil {
return ErrInvalidConnection
}
if subj == "" {
return ErrBadSubject
}
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
if nc.isDrainingPubs() {
nc.mu.Unlock()
return ErrConnectionDraining
}
// Proactively reject payloads over the threshold set by server.
msgSize := int64(len(data))
if msgSize > nc.info.MaxPayload {
nc.mu.Unlock()
return ErrMaxPayload
}
// Check if we are reconnecting, and if so check if
// we have exceeded our reconnect outbound buffer limits.
if nc.isReconnecting() {
// Flush to underlying buffer.
nc.bw.Flush()
// Check if we are over
if nc.pending.Len() >= nc.Opts.ReconnectBufSize {
nc.mu.Unlock()
return ErrReconnectBufExceeded
}
}
msgh := nc.scratch[:len(_PUB_P_)]
msgh = append(msgh, subj...)
msgh = append(msgh, ' ')
if reply != "" {
msgh = append(msgh, reply...)
msgh = append(msgh, ' ')
}
// We could be smarter here, but simple loop is ok,
// just avoid strconv in fast path
// FIXME(dlc) - Find a better way here.
// msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
var b [12]byte
var i = len(b)
if len(data) > 0 {
for l := len(data); l > 0; l /= 10 {
i -= 1
b[i] = digits[l%10]
}
} else {
i -= 1
b[i] = digits[0]
}
msgh = append(msgh, b[i:]...)
msgh = append(msgh, _CRLF_...)
_, err := nc.bw.Write(msgh)
if err == nil {
_, err = nc.bw.Write(data)
}
if err == nil {
_, err = nc.bw.WriteString(_CRLF_)
}
if err != nil {
nc.mu.Unlock()
return err
}
nc.OutMsgs++
nc.OutBytes += uint64(len(data))
if len(nc.fch) == 0 {
nc.kickFlusher()
}
nc.mu.Unlock()
return nil
}
// respHandler is the global response handler. It will look up
// the appropriate channel based on the last token and place
// the message on the channel if possible.
func (nc *Conn) respHandler(m *Msg) {
nc.mu.Lock()
// Just return if closed.
if nc.isClosed() {
nc.mu.Unlock()
return
}
var mch chan *Msg
// Grab mch
rt := nc.respToken(m.Subject)
if rt != _EMPTY_ {
mch = nc.respMap[rt]
// Delete the key regardless, one response only.
delete(nc.respMap, rt)
} else if len(nc.respMap) == 1 {
// If the server has rewritten the subject, the response token (rt)
// will not match (could be the case with JetStream). If that is the
// case and there is a single entry, use that.
for k, v := range nc.respMap {
mch = v
delete(nc.respMap, k)
break
}
}
nc.mu.Unlock()
// Don't block, let Request timeout instead, mch is
// buffered and we should delete the key before a
// second response is processed.
select {
case mch <- m:
default:
return
}
}
// Create the response subscription we will use for all
// new style responses. This will be on an _INBOX with an
// additional terminal token. The subscription will be on
// a wildcard. Caller is responsible for ensuring this is
// only called once.
func (nc *Conn) createRespMux(respSub string) error {
s, err := nc.Subscribe(respSub, nc.respHandler)
if err != nil {
return err
}
nc.mu.Lock()
nc.respScanf = strings.Replace(respSub, "*", "%s", -1)
nc.respMux = s
nc.mu.Unlock()
return nil
}
// Helper to setup and send new request style requests. Return the chan to receive the response.
func (nc *Conn) createNewRequestAndSend(subj string, data []byte) (chan *Msg, string, error) {
// Do setup for the new style if needed.
if nc.respMap == nil {
nc.initNewResp()
}
// Create new literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
respInbox := nc.newRespInbox()
token := respInbox[respInboxPrefixLen:]
nc.respMap[token] = mch
createSub := nc.respMux == nil
ginbox := nc.respSub
nc.mu.Unlock()
if createSub {
// Make sure scoped subscription is setup only once.
var err error
nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
if err != nil {
return nil, token, err
}
}
if err := nc.PublishRequest(subj, respInbox, data); err != nil {
return nil, token, err
}
return mch, token, nil
}
// Request will send a request payload and deliver the response message,
// or an error, including a timeout if no message was received properly.
func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequest(subj, data, timeout)
}
mch, token, err := nc.createNewRequestAndSend(subj, data)
if err != nil {
return nil, err
}
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
var ok bool
var msg *Msg
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
case <-t.C:
nc.mu.Lock()
delete(nc.respMap, token)
nc.mu.Unlock()
return nil, ErrTimeout
}
return msg, nil
}
// oldRequest will create an Inbox and perform a Request() call
// with the Inbox reply and return the first reply received.
// This is optimized for the case of multiple responses.
func (nc *Conn) oldRequest(subj string, data []byte, timeout time.Duration) (*Msg, error) {
inbox := NewInbox()
ch := make(chan *Msg, RequestChanLen)
s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, false)
if err != nil {
return nil, err
}
s.AutoUnsubscribe(1)
defer s.Unsubscribe()
err = nc.PublishRequest(subj, inbox, data)
if err != nil {
return nil, err
}
return s.NextMsg(timeout)
}
// InboxPrefix is the prefix for all inbox subjects.
const (
InboxPrefix = "_INBOX."
inboxPrefixLen = len(InboxPrefix)
respInboxPrefixLen = inboxPrefixLen + nuidSize + 1
replySuffixLen = 8 // Gives us 62^8
rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
base = 62
)
// NewInbox will return an inbox string which can be used for directed replies from
// subscribers. These are guaranteed to be unique, but can be shared and subscribed
// to by others.
func NewInbox() string {
var b [inboxPrefixLen + nuidSize]byte
pres := b[:inboxPrefixLen]
copy(pres, InboxPrefix)
ns := b[inboxPrefixLen:]
copy(ns, nuid.Next())
return string(b[:])
}
// Function to init new response structures.
func (nc *Conn) initNewResp() {
// _INBOX wildcard
nc.respSub = fmt.Sprintf("%s.*", NewInbox())
nc.respMap = make(map[string]chan *Msg)
nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
}
// newRespInbox creates a new literal response subject
// that will trigger the mux subscription handler.
// Lock should be held.
func (nc *Conn) newRespInbox() string {
if nc.respMap == nil {
nc.initNewResp()
}
var b [respInboxPrefixLen + replySuffixLen]byte
pres := b[:respInboxPrefixLen]
copy(pres, nc.respSub)
rn := nc.respRand.Int63()
for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
b[i] = rdigits[l%base]
l /= base
}
return string(b[:])
}
// NewRespInbox is the new format used for _INBOX.
func (nc *Conn) NewRespInbox() string {
nc.mu.Lock()
s := nc.newRespInbox()
nc.mu.Unlock()
return s
}
// respToken will return the last token of a literal response inbox
// which we use for the message channel lookup. This needs to do a
// scan to protect itself against the server changing the subject.
// Lock should be held.
func (nc *Conn) respToken(respInbox string) string {
var token string
n, err := fmt.Sscanf(respInbox, nc.respScanf, &token)
if err != nil || n != 1 {
return ""
}
return token
}
// Subscribe will express interest in the given subject. The subject
// can have wildcards (partial:*, full:>). Messages will be delivered
// to the associated MsgHandler.
func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, _EMPTY_, cb, nil, false)
}
// ChanSubscribe will express interest in the given subject and place
// all messages received on the channel.
// You should not close the channel until sub.Unsubscribe() has been called.
func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) {
return nc.subscribe(subj, _EMPTY_, nil, ch, false)
}
// ChanQueueSubscribe will express interest in the given subject.
// All subscribers with the same queue name will form the queue group
// and only one member of the group will be selected to receive any given message,
// which will be placed on the channel.
// You should not close the channel until sub.Unsubscribe() has been called.
// Note: This is the same than QueueSubscribeSyncWithChan.
func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) {
return nc.subscribe(subj, group, nil, ch, false)
}
// SubscribeSync will express interest on the given subject. Messages will
// be received synchronously using Subscription.NextMsg().
func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
mch := make(chan *Msg, nc.Opts.SubChanLen)
s, e := nc.subscribe(subj, _EMPTY_, nil, mch, true)
return s, e
}
// QueueSubscribe creates an asynchronous queue subscriber on the given subject.
// All subscribers with the same queue name will form the queue group and
// only one member of the group will be selected to receive any given
// message asynchronously.
func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, queue, cb, nil, false)
}
// QueueSubscribeSync creates a synchronous queue subscriber on the given
// subject. All subscribers with the same queue name will form the queue
// group and only one member of the group will be selected to receive any
// given message synchronously using Subscription.NextMsg().
func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) {
mch := make(chan *Msg, nc.Opts.SubChanLen)
s, e := nc.subscribe(subj, queue, nil, mch, true)
return s, e
}
// QueueSubscribeSyncWithChan will express interest in the given subject.
// All subscribers with the same queue name will form the queue group
// and only one member of the group will be selected to receive any given message,
// which will be placed on the channel.
// You should not close the channel until sub.Unsubscribe() has been called.
// Note: This is the same than ChanQueueSubscribe.
func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) {
return nc.subscribe(subj, queue, nil, ch, false)
}
// badSubject will do quick test on whether a subject is acceptable.
// Spaces are not allowed and all tokens should be > 0 in len.
func badSubject(subj string) bool {
if strings.ContainsAny(subj, " \t\r\n") {
return true
}
tokens := strings.Split(subj, ".")
for _, t := range tokens {
if len(t) == 0 {
return true
}
}
return false
}
// badQueue will check a queue name for whitespace.
func badQueue(qname string) bool {
return strings.ContainsAny(qname, " \t\r\n")
}
// subscribe is the internal subscribe function that indicates interest in a subject.
func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool) (*Subscription, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
if badSubject(subj) {
return nil, ErrBadSubject
}
if queue != "" && badQueue(queue) {
return nil, ErrBadQueueName
}
nc.mu.Lock()
// ok here, but defer is generally expensive
defer nc.mu.Unlock()
// Check for some error conditions.
if nc.isClosed() {
return nil, ErrConnectionClosed
}
if nc.isDraining() {
return nil, ErrConnectionDraining
}
if cb == nil && ch == nil {
return nil, ErrBadSubscription
}
sub := &Subscription{Subject: subj, Queue: queue, mcb: cb, conn: nc}
// Set pending limits.
sub.pMsgsLimit = DefaultSubPendingMsgsLimit
sub.pBytesLimit = DefaultSubPendingBytesLimit
// If we have an async callback, start up a sub specific
// Go routine to deliver the messages.
if cb != nil {
sub.typ = AsyncSubscription
sub.pCond = sync.NewCond(&sub.mu)
go nc.waitForMsgs(sub)
} else if !isSync {
sub.typ = ChanSubscription
sub.mch = ch
} else { // Sync Subscription
sub.typ = SyncSubscription
sub.mch = ch
}
nc.subsMu.Lock()
nc.ssid++
sub.sid = nc.ssid
nc.subs[sub.sid] = sub
nc.subsMu.Unlock()
// We will send these for all subs when we reconnect
// so that we can suppress here if reconnecting.
if !nc.isReconnecting() {
fmt.Fprintf(nc.bw, subProto, subj, queue, sub.sid)
// Kick flusher if needed.
if len(nc.fch) == 0 {
nc.kickFlusher()
}
}
return sub, nil
}
// NumSubscriptions returns active number of subscriptions.
func (nc *Conn) NumSubscriptions() int {
nc.mu.RLock()
defer nc.mu.RUnlock()
return len(nc.subs)
}
// Lock for nc should be held here upon entry
func (nc *Conn) removeSub(s *Subscription) {
nc.subsMu.Lock()
delete(nc.subs, s.sid)
nc.subsMu.Unlock()
s.mu.Lock()
defer s.mu.Unlock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid
s.closed = true
if s.pCond != nil {
s.pCond.Broadcast()
}
}
// SubscriptionType is the type of the Subscription.
type SubscriptionType int
// The different types of subscription types.
const (
AsyncSubscription = SubscriptionType(iota)
SyncSubscription
ChanSubscription
NilSubscription
)
// Type returns the type of Subscription.
func (s *Subscription) Type() SubscriptionType {
if s == nil {
return NilSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
return s.typ
}
// IsValid returns a boolean indicating whether the subscription
// is still active. This will return false if the subscription has
// already been closed.
func (s *Subscription) IsValid() bool {
if s == nil {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
return s.conn != nil && !s.closed
}
// Drain will remove interest but continue callbacks until all messages
// have been processed.
func (s *Subscription) Drain() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, 0, true)
}
// Unsubscribe will remove interest in the given subject.
func (s *Subscription) Unsubscribe() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
closed := s.closed
s.mu.Unlock()
if conn == nil || conn.IsClosed() {
return ErrConnectionClosed
}
if closed {
return ErrBadSubscription
}
if conn.IsDraining() {
return ErrConnectionDraining
}
return conn.unsubscribe(s, 0, false)
}
// checkDrained will watch for a subscription to be fully drained
// and then remove it.
func (nc *Conn) checkDrained(sub *Subscription) {
if nc == nil || sub == nil {
return
}
// This allows us to know that whatever we have in the client pending
// is correct and the server will not send additional information.
nc.Flush()
// Once we are here we just wait for Pending to reach 0 or
// any other state to exit this go routine.
for {
// check connection is still valid.
if nc.IsClosed() {
return
}
// Check subscription state
sub.mu.Lock()
conn := sub.conn
closed := sub.closed
pMsgs := sub.pMsgs
sub.mu.Unlock()
if conn == nil || closed || pMsgs == 0 {
nc.mu.Lock()
nc.removeSub(sub)
nc.mu.Unlock()
return
}
time.Sleep(100 * time.Millisecond)
}
}
// AutoUnsubscribe will issue an automatic Unsubscribe that is
// processed by the server when max messages have been received.
// This can be useful when sending a request to an unknown number
// of subscribers.
func (s *Subscription) AutoUnsubscribe(max int) error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
closed := s.closed
s.mu.Unlock()
if conn == nil || closed {
return ErrBadSubscription
}
return conn.unsubscribe(s, max, false)
}
// unsubscribe performs the low level unsubscribe to the server.
// Use Subscription.Unsubscribe()
func (nc *Conn) unsubscribe(sub *Subscription, max int, drainMode bool) error {
nc.mu.Lock()
// ok here, but defer is expensive
defer nc.mu.Unlock()
defer nc.kickFlusher()
if nc.isClosed() {
return ErrConnectionClosed
}
nc.subsMu.RLock()
s := nc.subs[sub.sid]
nc.subsMu.RUnlock()
// Already unsubscribed
if s == nil {
return nil
}
maxStr := _EMPTY_
if max > 0 {
s.max = uint64(max)
maxStr = strconv.Itoa(max)
} else if !drainMode {
nc.removeSub(s)
}
if drainMode {
go nc.checkDrained(sub)
}
// We will send these for all subs when we reconnect
// so that we can suppress here.
if !nc.isReconnecting() {
fmt.Fprintf(nc.bw, unsubProto, s.sid, maxStr)
}
return nil
}
// NextMsg will return the next message available to a synchronous subscriber
// or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription),
// the connection is closed (ErrConnectionClosed), or the timeout is reached (ErrTimeout).
func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
if s == nil {
return nil, ErrBadSubscription
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, s.getNextMsgErr()
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
// If we are here a message was not immediately available, so lets loop
// with a timeout.
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
select {
case msg, ok = <-mch:
if !ok {
return nil, s.getNextMsgErr()
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-t.C:
return nil, ErrTimeout
}
return msg, nil
}
// validateNextMsgState checks whether the subscription is in a valid
// state to call NextMsg and be delivered another message synchronously.
// This should be called while holding the lock.
func (s *Subscription) validateNextMsgState() error {
if s.connClosed {
return ErrConnectionClosed
}
if s.mch == nil {
if s.max > 0 && s.delivered >= s.max {
return ErrMaxMessages
} else if s.closed {
return ErrBadSubscription
}
}
if s.mcb != nil {
return ErrSyncSubRequired
}
if s.sc {
s.sc = false
return ErrSlowConsumer
}
return nil
}
// This is called when the sync channel has been closed.
// The error returned will be either connection or subscription
// closed depending on what caused NextMsg() to fail.
func (s *Subscription) getNextMsgErr() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.connClosed {
return ErrConnectionClosed
}
return ErrBadSubscription
}
// processNextMsgDelivered takes a message and applies the needed
// accounting to the stats from the subscription, returning an
// error in case we have the maximum number of messages have been
// delivered already. It should not be called while holding the lock.
func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
s.mu.Lock()
nc := s.conn
max := s.max
// Update some stats.
s.delivered++
delivered := s.delivered
if s.typ == SyncSubscription {
s.pMsgs--
s.pBytes -= len(msg.Data)
}
s.mu.Unlock()
if max > 0 {
if delivered > max {
return ErrMaxMessages
}
// Remove subscription if we have reached max.
if delivered == max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
}
}
return nil
}
// Queued returns the number of queued messages in the client for this subscription.
// DEPRECATED: Use Pending()
func (s *Subscription) QueuedMsgs() (int, error) {
m, _, err := s.Pending()
return int(m), err
}
// Pending returns the number of queued messages and queued bytes in the client for this subscription.
func (s *Subscription) Pending() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgs, s.pBytes, nil
}
// MaxPending returns the maximum number of queued messages and queued bytes seen so far.
func (s *Subscription) MaxPending() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgsMax, s.pBytesMax, nil
}
// ClearMaxPending resets the maximums seen so far.
func (s *Subscription) ClearMaxPending() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return ErrBadSubscription
}
if s.typ == ChanSubscription {
return ErrTypeSubscription
}
s.pMsgsMax, s.pBytesMax = 0, 0
return nil
}
// Pending Limits
const (
DefaultSubPendingMsgsLimit = 65536
DefaultSubPendingBytesLimit = 65536 * 1024
)
// PendingLimits returns the current limits for this subscription.
// If no error is returned, a negative value indicates that the
// given metric is not limited.
func (s *Subscription) PendingLimits() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgsLimit, s.pBytesLimit, nil
}
// SetPendingLimits sets the limits for pending msgs and bytes for this subscription.
// Zero is not allowed. Any negative value means that the given metric is not limited.
func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return ErrBadSubscription
}
if s.typ == ChanSubscription {
return ErrTypeSubscription
}
if msgLimit == 0 || bytesLimit == 0 {
return ErrInvalidArg
}
s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit
return nil
}
// Delivered returns the number of delivered messages for this subscription.
func (s *Subscription) Delivered() (int64, error) {
if s == nil {
return -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return -1, ErrBadSubscription
}
return int64(s.delivered), nil
}
// Dropped returns the number of known dropped messages for this subscription.
// This will correspond to messages dropped by violations of PendingLimits. If
// the server declares the connection a SlowConsumer, this number may not be
// valid.
func (s *Subscription) Dropped() (int, error) {
if s == nil {
return -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil || s.closed {
return -1, ErrBadSubscription
}
return s.dropped, nil
}
// Respond allows a convenient way to respond to requests in service based subscriptions.
func (m *Msg) Respond(data []byte) error {
if m == nil || m.Sub == nil {
return ErrMsgNotBound
}
if m.Reply == "" {
return ErrMsgNoReply
}
m.Sub.mu.Lock()
nc := m.Sub.conn
m.Sub.mu.Unlock()
// No need to check the connection here since the call to publish will do all the checking.
return nc.Publish(m.Reply, data)
}
// FIXME: This is a hack
// removeFlushEntry is needed when we need to discard queued up responses
// for our pings as part of a flush call. This happens when we have a flush
// call outstanding and we call close.
func (nc *Conn) removeFlushEntry(ch chan struct{}) bool {
nc.mu.Lock()
defer nc.mu.Unlock()
if nc.pongs == nil {
return false
}
for i, c := range nc.pongs {
if c == ch {
nc.pongs[i] = nil
return true
}
}
return false
}
// The lock must be held entering this function.
func (nc *Conn) sendPing(ch chan struct{}) {
nc.pongs = append(nc.pongs, ch)
nc.bw.WriteString(pingProto)
// Flush in place.
nc.bw.Flush()
}
// This will fire periodically and send a client origin
// ping to the server. Will also check that we have received
// responses from the server.
func (nc *Conn) processPingTimer() {
nc.mu.Lock()
if nc.status != CONNECTED {
nc.mu.Unlock()
return
}
// Check for violation
nc.pout++
if nc.pout > nc.Opts.MaxPingsOut {
nc.mu.Unlock()
nc.processOpErr(ErrStaleConnection)
return
}
nc.sendPing(nil)
nc.ptmr.Reset(nc.Opts.PingInterval)
nc.mu.Unlock()
}
// FlushTimeout allows a Flush operation to have an associated timeout.
func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) {
if nc == nil {
return ErrInvalidConnection
}
if timeout <= 0 {
return ErrBadTimeout
}
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
// Create a buffered channel to prevent chan send to block
// in processPong() if this code here times out just when
// PONG was received.
ch := make(chan struct{}, 1)
nc.sendPing(ch)
nc.mu.Unlock()
select {
case _, ok := <-ch:
if !ok {
err = ErrConnectionClosed
} else {
close(ch)
}
case <-t.C:
err = ErrTimeout
}
if err != nil {
nc.removeFlushEntry(ch)
}
return
}
// Flush will perform a round trip to the server and return when it
// receives the internal reply.
func (nc *Conn) Flush() error {
return nc.FlushTimeout(60 * time.Second)
}
// Buffered will return the number of bytes buffered to be sent to the server.
// FIXME(dlc) take into account disconnected state.
func (nc *Conn) Buffered() (int, error) {
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.isClosed() || nc.bw == nil {
return -1, ErrConnectionClosed
}
return nc.bw.Buffered(), nil
}
// resendSubscriptions will send our subscription state back to the
// server. Used in reconnects
func (nc *Conn) resendSubscriptions() {
// Since we are going to send protocols to the server, we don't want to
// be holding the subsMu lock (which is used in processMsg). So copy
// the subscriptions in a temporary array.
nc.subsMu.RLock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
nc.subsMu.RUnlock()
for _, s := range subs {
adjustedMax := uint64(0)
s.mu.Lock()
if s.max > 0 {
if s.delivered < s.max {
adjustedMax = s.max - s.delivered
}
// adjustedMax could be 0 here if the number of delivered msgs
// reached the max, if so unsubscribe.
if adjustedMax == 0 {
s.mu.Unlock()
fmt.Fprintf(nc.bw, unsubProto, s.sid, _EMPTY_)
continue
}
}
s.mu.Unlock()
fmt.Fprintf(nc.bw, subProto, s.Subject, s.Queue, s.sid)
if adjustedMax > 0 {
maxStr := strconv.Itoa(int(adjustedMax))
fmt.Fprintf(nc.bw, unsubProto, s.sid, maxStr)
}
}
}
// This will clear any pending flush calls and release pending calls.
// Lock is assumed to be held by the caller.
func (nc *Conn) clearPendingFlushCalls() {
// Clear any queued pongs, e.g. pending flush calls.
for _, ch := range nc.pongs {
if ch != nil {
close(ch)
}
}
nc.pongs = nil
}
// This will clear any pending Request calls.
// Lock is assumed to be held by the caller.
func (nc *Conn) clearPendingRequestCalls() {
if nc.respMap == nil {
return
}
for key, ch := range nc.respMap {
if ch != nil {
close(ch)
delete(nc.respMap, key)
}
}
}
// Low level close call that will do correct cleanup and set
// desired status. Also controls whether user defined callbacks
// will be triggered. The lock should not be held entering this
// function. This function will handle the locking manually.
func (nc *Conn) close(status Status, doCBs bool, err error) {
nc.mu.Lock()
if nc.isClosed() {
nc.status = status
nc.mu.Unlock()
return
}
nc.status = CLOSED
// Kick the Go routines so they fall out.
nc.kickFlusher()
nc.mu.Unlock()
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any queued and blocking Requests.
nc.clearPendingRequestCalls()
// Stop ping timer if set.
nc.stopPingTimer()
nc.ptmr = nil
// Need to close and set tcp conn to nil if reconnect loop has stopped,
// otherwise we would incorrectly invoke Disconnect handler (if set)
// down below.
if nc.ar && nc.conn != nil {
nc.conn.Close()
nc.conn = nil
} else if nc.conn != nil {
// Go ahead and make sure we have flushed the outbound
nc.bw.Flush()
defer nc.conn.Close()
}
// Close sync subscriber channels and release any
// pending NextMsg() calls.
nc.subsMu.Lock()
for _, s := range nc.subs {
s.mu.Lock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid, for signaling to deliverMsgs
s.closed = true
// Mark connection closed in subscription
s.connClosed = true
// If we have an async subscription, signals it to exit
if s.typ == AsyncSubscription && s.pCond != nil {
s.pCond.Signal()
}
s.mu.Unlock()
}
nc.subs = nil
nc.subsMu.Unlock()
nc.status = status
// Perform appropriate callback if needed for a disconnect.
if doCBs {
if nc.conn != nil {
if nc.Opts.DisconnectedErrCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) })
} else if nc.Opts.DisconnectedCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
}
if nc.Opts.ClosedCB != nil {
nc.ach.push(func() { nc.Opts.ClosedCB(nc) })
}
nc.ach.close()
}
nc.mu.Unlock()
}
// Close will close the connection to the server. This call will release
// all blocking calls, such as Flush() and NextMsg()
func (nc *Conn) Close() {
if nc != nil {
nc.close(CLOSED, !nc.Opts.NoCallbacksAfterClientClose, nil)
}
}
// IsClosed tests if a Conn has been closed.
func (nc *Conn) IsClosed() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isClosed()
}
// IsReconnecting tests if a Conn is reconnecting.
func (nc *Conn) IsReconnecting() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isReconnecting()
}
// IsConnected tests if a Conn is connected.
func (nc *Conn) IsConnected() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isConnected()
}
// drainConnection will run in a separate Go routine and will
// flush all publishes and drain all active subscriptions.
func (nc *Conn) drainConnection() {
// Snapshot subs list.
nc.mu.Lock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
errCB := nc.Opts.AsyncErrorCB
drainWait := nc.Opts.DrainTimeout
nc.mu.Unlock()
// for pushing errors with context.
pushErr := func(err error) {
nc.mu.Lock()
nc.err = err
if errCB != nil {
nc.ach.push(func() { errCB(nc, nil, err) })
}
nc.mu.Unlock()
}
// Do subs first
for _, s := range subs {
if err := s.Drain(); err != nil {
// We will notify about these but continue.
pushErr(err)
}
}
// Wait for the subscriptions to drop to zero.
timeout := time.Now().Add(drainWait)
for time.Now().Before(timeout) {
if nc.NumSubscriptions() == 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
// Check if we timed out.
if nc.NumSubscriptions() != 0 {
pushErr(ErrDrainTimeout)
}
// Flip State
nc.mu.Lock()
nc.status = DRAINING_PUBS
nc.mu.Unlock()
// Do publish drain via Flush() call.
err := nc.Flush()
if err != nil {
pushErr(err)
nc.close(CLOSED, true, nil)
return
}
// Move to closed state.
nc.close(CLOSED, true, nil)
}
// Drain will put a connection into a drain state. All subscriptions will
// immediately be put into a drain state. Upon completion, the publishers
// will be drained and can not publish any additional messages. Upon draining
// of the publishers, the connection will be closed. Use the ClosedCB()
// option to know when the connection has moved from draining to closed.
func (nc *Conn) Drain() error {
nc.mu.Lock()
defer nc.mu.Unlock()
if nc.isClosed() {
return ErrConnectionClosed
}
if nc.isConnecting() || nc.isReconnecting() {
return ErrConnectionReconnecting
}
if nc.isDraining() {
return nil
}
nc.status = DRAINING_SUBS
go nc.drainConnection()
return nil
}
// IsDraining tests if a Conn is in the draining state.
func (nc *Conn) IsDraining() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isDraining()
}
// caller must lock
func (nc *Conn) getServers(implicitOnly bool) []string {
poolSize := len(nc.srvPool)
var servers = make([]string, 0)
for i := 0; i < poolSize; i++ {
if implicitOnly && !nc.srvPool[i].isImplicit {
continue
}
url := nc.srvPool[i].url
servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
}
return servers
}
// Servers returns the list of known server urls, including additional
// servers discovered after a connection has been established. If
// authentication is enabled, use UserInfo or Token when connecting with
// these urls.
func (nc *Conn) Servers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(false)
}
// DiscoveredServers returns only the server urls that have been discovered
// after a connection has been established. If authentication is enabled,
// use UserInfo or Token when connecting with these urls.
func (nc *Conn) DiscoveredServers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(true)
}
// Status returns the current state of the connection.
func (nc *Conn) Status() Status {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.status
}
// Test if Conn has been closed Lock is assumed held.
func (nc *Conn) isClosed() bool {
return nc.status == CLOSED
}
// Test if Conn is in the process of connecting
func (nc *Conn) isConnecting() bool {
return nc.status == CONNECTING
}
// Test if Conn is being reconnected.
func (nc *Conn) isReconnecting() bool {
return nc.status == RECONNECTING
}
// Test if Conn is connected or connecting.
func (nc *Conn) isConnected() bool {
return nc.status == CONNECTED || nc.isDraining()
}
// Test if Conn is in the draining state.
func (nc *Conn) isDraining() bool {
return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
}
// Test if Conn is in the draining state for pubs.
func (nc *Conn) isDrainingPubs() bool {
return nc.status == DRAINING_PUBS
}
// Stats will return a race safe copy of the Statistics section for the connection.
func (nc *Conn) Stats() Statistics {
// Stats are updated either under connection's mu or with atomic operations
// for inbound stats in processMsg().
nc.mu.Lock()
stats := Statistics{
InMsgs: atomic.LoadUint64(&nc.InMsgs),
InBytes: atomic.LoadUint64(&nc.InBytes),
OutMsgs: nc.OutMsgs,
OutBytes: nc.OutBytes,
Reconnects: nc.Reconnects,
}
nc.mu.Unlock()
return stats
}
// MaxPayload returns the size limit that a message payload can have.
// This is set by the server configuration and delivered to the client
// upon connect.
func (nc *Conn) MaxPayload() int64 {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.MaxPayload
}
// AuthRequired will return if the connected server requires authorization.
func (nc *Conn) AuthRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.AuthRequired
}
// TLSRequired will return if the connected server requires TLS connections.
func (nc *Conn) TLSRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.TLSRequired
}
// Barrier schedules the given function `f` to all registered asynchronous
// subscriptions.
// Only the last subscription to see this barrier will invoke the function.
// If no subscription is registered at the time of this call, `f()` is invoked
// right away.
// ErrConnectionClosed is returned if the connection is closed prior to
// the call.
func (nc *Conn) Barrier(f func()) error {
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
nc.subsMu.Lock()
// Need to figure out how many non chan subscriptions there are
numSubs := 0
for _, sub := range nc.subs {
if sub.typ == AsyncSubscription {
numSubs++
}
}
if numSubs == 0 {
nc.subsMu.Unlock()
nc.mu.Unlock()
f()
return nil
}
barrier := &barrierInfo{refs: int64(numSubs), f: f}
for _, sub := range nc.subs {
sub.mu.Lock()
if sub.mch == nil {
msg := &Msg{barrier: barrier}
// Push onto the async pList
if sub.pTail != nil {
sub.pTail.next = msg
} else {
sub.pHead = msg
sub.pCond.Signal()
}
sub.pTail = msg
}
sub.mu.Unlock()
}
nc.subsMu.Unlock()
nc.mu.Unlock()
return nil
}
// GetClientID returns the client ID assigned by the server to which
// the client is currently connected to. Note that the value may change if
// the client reconnects.
// This function returns ErrNoClientIDReturned if the server is of a
// version prior to 1.2.0.
func (nc *Conn) GetClientID() (uint64, error) {
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.isClosed() {
return 0, ErrConnectionClosed
}
if nc.info.CID == 0 {
return 0, ErrClientIDNotSupported
}
return nc.info.CID, nil
}
// NkeyOptionFromSeed will load an nkey pair from a seed file.
// It will return the NKey Option and will handle
// signing of nonce challenges from the server. It will take
// care to not hold keys in memory and to wipe memory.
func NkeyOptionFromSeed(seedFile string) (Option, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
pub, err := kp.PublicKey()
if err != nil {
return nil, err
}
if !nkeys.IsValidPublicUserKey(pub) {
return nil, fmt.Errorf("nats: Not a valid nkey user seed")
}
sigCB := func(nonce []byte) ([]byte, error) {
return sigHandler(nonce, seedFile)
}
return Nkey(string(pub), sigCB), nil
}
// Just wipe slice with 'x', for clearing contents of creds or nkey seed file.
func wipeSlice(buf []byte) {
for i := range buf {
buf[i] = 'x'
}
}
func userFromFile(userFile string) (string, error) {
path, err := expandPath(userFile)
if err != nil {
return _EMPTY_, fmt.Errorf("nats: %v", err)
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return _EMPTY_, fmt.Errorf("nats: %v", err)
}
defer wipeSlice(contents)
return jwt.ParseDecoratedJWT(contents)
}
func homeDir() (string, error) {
if runtime.GOOS == "windows" {
homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
userProfile := os.Getenv("USERPROFILE")
var home string
if homeDrive == "" || homePath == "" {
if userProfile == "" {
return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
}
home = userProfile
} else {
home = filepath.Join(homeDrive, homePath)
}
return home, nil
}
home := os.Getenv("HOME")
if home == "" {
return _EMPTY_, errors.New("nats: failed to get home dir, require $HOME")
}
return home, nil
}
func expandPath(p string) (string, error) {
p = os.ExpandEnv(p)
if !strings.HasPrefix(p, "~") {
return p, nil
}
home, err := homeDir()
if err != nil {
return _EMPTY_, err
}
return filepath.Join(home, p[1:]), nil
}
func nkeyPairFromSeedFile(seedFile string) (nkeys.KeyPair, error) {
contents, err := ioutil.ReadFile(seedFile)
if err != nil {
return nil, fmt.Errorf("nats: %v", err)
}
defer wipeSlice(contents)
return jwt.ParseDecoratedNKey(contents)
}
// Sign authentication challenges from the server.
// Do not keep private seed in memory.
func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
sig, _ := kp.Sign(nonce)
return sig, nil
}
type timeoutWriter struct {
timeout time.Duration
conn net.Conn
err error
}
// Write implements the io.Writer interface.
func (tw *timeoutWriter) Write(p []byte) (int, error) {
if tw.err != nil {
return 0, tw.err
}
var n int
tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout))
n, tw.err = tw.conn.Write(p)
tw.conn.SetWriteDeadline(time.Time{})
return n, tw.err
}
|
[
"\"HOMEDRIVE\"",
"\"HOMEPATH\"",
"\"USERPROFILE\"",
"\"HOME\""
] |
[] |
[
"USERPROFILE",
"HOME",
"HOMEPATH",
"HOMEDRIVE"
] |
[]
|
["USERPROFILE", "HOME", "HOMEPATH", "HOMEDRIVE"]
|
go
| 4 | 0 | |
cmd/fluxctl/args_test.go
|
package main
import (
"fmt"
"testing"
"os"
"os/exec"
)
func helperCommand(command string, s ...string) (cmd *exec.Cmd) {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, s...)
cmd = exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
defer os.Exit(0)
args := os.Args
for len(args) > 0 {
if args[0] == "--" {
args = args[1:]
break
}
args = args[1:]
}
if len(args) == 0 {
t.Fatalf("No command\n")
}
_, args = args[0], args[1:]
for _, a := range args {
if a == "user.name" {
fmt.Fprintf(os.Stdout, "Jane Doe")
} else if a == "user.email" {
fmt.Fprintf(os.Stdout, "[email protected]")
}
}
}
func checkAuthor(t *testing.T, input string, expected string) {
execCommand = helperCommand
defer func(){ execCommand = exec.Command }()
author := getUserGitConfigValue(input)
if author != expected {
t.Fatalf("author %q does not match expected value %q", author, expected)
}
}
func TestGetCommitAuthor_OnlyName(t *testing.T) {
checkAuthor(t, "user.name", "Jane Doe")
}
func TestGetCommitAuthor_OnlyEmail(t *testing.T) {
checkAuthor(t, "user.email", "[email protected]")
}
|
[
"\"GO_WANT_HELPER_PROCESS\""
] |
[] |
[
"GO_WANT_HELPER_PROCESS"
] |
[]
|
["GO_WANT_HELPER_PROCESS"]
|
go
| 1 | 0 | |
pkg/sorted/leveldb/leveldb.go
|
/*
Copyright 2014 The Camlistore 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 leveldb provides an implementation of sorted.KeyValue
// on top of a single mutable database file on disk using
// github.com/syndtr/goleveldb.
package leveldb
import (
"errors"
"fmt"
"os"
"sync"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/pkg/sorted"
"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb"
"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb/filter"
"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb/iterator"
"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb/opt"
"camlistore.org/third_party/github.com/syndtr/goleveldb/leveldb/util"
)
var _ sorted.Wiper = (*kvis)(nil)
func init() {
sorted.RegisterKeyValue("leveldb", newKeyValueFromJSONConfig)
}
// NewStorage is a convenience that calls newKeyValueFromJSONConfig
// with file as the leveldb storage file.
func NewStorage(file string) (sorted.KeyValue, error) {
return newKeyValueFromJSONConfig(jsonconfig.Obj{"file": file})
}
// newKeyValueFromJSONConfig returns a KeyValue implementation on top of a
// github.com/syndtr/goleveldb/leveldb file.
func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
file := cfg.RequiredString("file")
if err := cfg.Validate(); err != nil {
return nil, err
}
strictness := opt.DefaultStrict
if os.Getenv("CAMLI_DEV_CAMLI_ROOT") != "" {
// Be more strict in dev mode.
strictness = opt.StrictAll
}
opts := &opt.Options{
// TODO(tgulacsi): decide whether this default 500 is too much or not. Till that go with the default.
CachedOpenFiles: 500,
// The default is 10,
// 8 means 2.126% or 1/47th disk check rate,
// 10 means 0.812% error rate (1/2^(bits/1.44)) or 1/123th disk check rate,
// 12 means 0.31% or 1/322th disk check rate.
// TODO(tgulacsi): decide which number is the best here. Till that go with the default.
Filter: filter.NewBloomFilter(10),
Strict: strictness,
}
db, err := leveldb.OpenFile(file, opts)
if err != nil {
return nil, err
}
is := &kvis{
db: db,
path: file,
opts: opts,
readOpts: &opt.ReadOptions{Strict: strictness},
// On machine crash we want to reindex anyway, and
// fsyncs may impose great performance penalty.
writeOpts: &opt.WriteOptions{Sync: false},
}
return is, nil
}
type kvis struct {
path string
db *leveldb.DB
opts *opt.Options
readOpts *opt.ReadOptions
writeOpts *opt.WriteOptions
txmu sync.Mutex
}
func (is *kvis) Get(key string) (string, error) {
val, err := is.db.Get([]byte(key), is.readOpts)
if err != nil {
if err == leveldb.ErrNotFound {
return "", sorted.ErrNotFound
}
return "", err
}
if val == nil {
return "", sorted.ErrNotFound
}
return string(val), nil
}
func (is *kvis) Set(key, value string) error {
if err := sorted.CheckSizes(key, value); err != nil {
return err
}
return is.db.Put([]byte(key), []byte(value), is.writeOpts)
}
func (is *kvis) Delete(key string) error {
return is.db.Delete([]byte(key), is.writeOpts)
}
func (is *kvis) Find(start, end string) sorted.Iterator {
var startB, endB []byte
// A nil Range.Start is treated as a key before all keys in the DB.
if start != "" {
startB = []byte(start)
}
// A nil Range.Limit is treated as a key after all keys in the DB.
if end != "" {
endB = []byte(end)
}
it := &iter{
it: is.db.NewIterator(
&util.Range{Start: startB, Limit: endB},
is.readOpts,
),
}
return it
}
func (is *kvis) Wipe() error {
// Close the already open DB.
if err := is.db.Close(); err != nil {
return err
}
if err := os.RemoveAll(is.path); err != nil {
return err
}
db, err := leveldb.OpenFile(is.path, is.opts)
if err != nil {
return fmt.Errorf("error creating %s: %v", is.path, err)
}
is.db = db
return nil
}
func (is *kvis) BeginBatch() sorted.BatchMutation {
return &lvbatch{batch: new(leveldb.Batch)}
}
type lvbatch struct {
errMu sync.Mutex
err error // Set if one of the mutations had too large a key or value. Sticky.
batch *leveldb.Batch
}
func (lvb *lvbatch) Set(key, value string) {
lvb.errMu.Lock()
defer lvb.errMu.Unlock()
if lvb.err != nil {
return
}
if err := sorted.CheckSizes(key, value); err != nil {
if err == sorted.ErrKeyTooLarge {
lvb.err = fmt.Errorf("%v: %v", err, key)
} else {
lvb.err = fmt.Errorf("%v: %v", err, value)
}
return
}
lvb.batch.Put([]byte(key), []byte(value))
}
func (lvb *lvbatch) Delete(key string) {
lvb.batch.Delete([]byte(key))
}
func (is *kvis) CommitBatch(bm sorted.BatchMutation) error {
b, ok := bm.(*lvbatch)
if !ok {
return errors.New("invalid batch type")
}
b.errMu.Lock()
defer b.errMu.Unlock()
if b.err != nil {
return b.err
}
return is.db.Write(b.batch, is.writeOpts)
}
func (is *kvis) Close() error {
return is.db.Close()
}
type iter struct {
it iterator.Iterator
key, val []byte
skey, sval *string // for caching string values
err error
closed bool
}
func (it *iter) Close() error {
it.closed = true
it.it.Release()
return nil
}
func (it *iter) KeyBytes() []byte {
return it.it.Key()
}
func (it *iter) Key() string {
if it.skey != nil {
return *it.skey
}
str := string(it.it.Key())
it.skey = &str
return str
}
func (it *iter) ValueBytes() []byte {
return it.it.Value()
}
func (it *iter) Value() string {
if it.sval != nil {
return *it.sval
}
str := string(it.it.Value())
it.sval = &str
return str
}
func (it *iter) Next() bool {
if err := it.it.Error(); err != nil {
return false
}
if it.closed {
panic("Next called after Next returned value")
}
it.skey, it.sval = nil, nil
return it.it.Next()
}
|
[
"\"CAMLI_DEV_CAMLI_ROOT\""
] |
[] |
[
"CAMLI_DEV_CAMLI_ROOT"
] |
[]
|
["CAMLI_DEV_CAMLI_ROOT"]
|
go
| 1 | 0 | |
memory/memory_test.go
|
package memory
import (
"fmt"
"os"
"testing"
"time"
"github.com/zzsds/registry"
)
var (
testData = map[string][]*registry.Service{
"foo": {
{
Name: "foo",
Version: "1.0.0",
Nodes: []*registry.Node{
{
Id: "foo-1.0.0-123",
Address: "localhost:9999",
},
{
Id: "foo-1.0.0-321",
Address: "localhost:9999",
},
},
},
{
Name: "foo",
Version: "1.0.1",
Nodes: []*registry.Node{
{
Id: "foo-1.0.1-321",
Address: "localhost:6666",
},
},
},
{
Name: "foo",
Version: "1.0.3",
Nodes: []*registry.Node{
{
Id: "foo-1.0.3-345",
Address: "localhost:8888",
},
},
},
},
"bar": {
{
Name: "bar",
Version: "default",
Nodes: []*registry.Node{
{
Id: "bar-1.0.0-123",
Address: "localhost:9999",
},
{
Id: "bar-1.0.0-321",
Address: "localhost:9999",
},
},
},
{
Name: "bar",
Version: "latest",
Nodes: []*registry.Node{
{
Id: "bar-1.0.1-321",
Address: "localhost:6666",
},
},
},
},
}
)
func TestMemoryRegistry(t *testing.T) {
m := NewRegistry()
fn := func(k string, v []*registry.Service) {
services, err := m.GetService(k)
if err != nil {
t.Errorf("Unexpected error getting service %s: %v", k, err)
}
if len(services) != len(v) {
t.Errorf("Expected %d services for %s, got %d", len(v), k, len(services))
}
for _, service := range v {
var seen bool
for _, s := range services {
if s.Version == service.Version {
seen = true
break
}
}
if !seen {
t.Errorf("expected to find version %s", service.Version)
}
}
}
// register data
for _, v := range testData {
serviceCount := 0
for _, service := range v {
if err := m.Register(service); err != nil {
t.Errorf("Unexpected register error: %v", err)
}
serviceCount++
// after the service has been registered we should be able to query it
services, err := m.GetService(service.Name)
if err != nil {
t.Errorf("Unexpected error getting service %s: %v", service.Name, err)
}
if len(services) != serviceCount {
t.Errorf("Expected %d services for %s, got %d", serviceCount, service.Name, len(services))
}
}
}
// using test data
for k, v := range testData {
fn(k, v)
}
services, err := m.ListServices()
if err != nil {
t.Errorf("Unexpected error when listing services: %v", err)
}
totalServiceCount := 0
for _, testSvc := range testData {
for range testSvc {
totalServiceCount++
}
}
if len(services) != totalServiceCount {
t.Errorf("Expected total service count: %d, got: %d", totalServiceCount, len(services))
}
// deregister
for _, v := range testData {
for _, service := range v {
if err := m.Deregister(service); err != nil {
t.Errorf("Unexpected deregister error: %v", err)
}
}
}
// after all the service nodes have been deregistered we should not get any results
for _, v := range testData {
for _, service := range v {
services, err := m.GetService(service.Name)
if err != registry.ErrNotFound {
t.Errorf("Expected error: %v, got: %v", registry.ErrNotFound, err)
}
if len(services) != 0 {
t.Errorf("Expected %d services for %s, got %d", 0, service.Name, len(services))
}
}
}
}
func TestMemoryRegistryTTL(t *testing.T) {
m := NewRegistry()
for _, v := range testData {
for _, service := range v {
if err := m.Register(service, registry.RegisterTTL(time.Millisecond)); err != nil {
t.Fatal(err)
}
}
}
time.Sleep(ttlPruneTime * 2)
for name := range testData {
svcs, err := m.GetService(name)
if err != nil {
t.Fatal(err)
}
for _, svc := range svcs {
if len(svc.Nodes) > 0 {
t.Fatalf("Service %q still has nodes registered", name)
}
}
}
}
func TestMemoryRegistryTTLConcurrent(t *testing.T) {
concurrency := 1000
waitTime := ttlPruneTime * 2
m := NewRegistry()
for _, v := range testData {
for _, service := range v {
if err := m.Register(service, registry.RegisterTTL(waitTime/2)); err != nil {
t.Fatal(err)
}
}
}
if len(os.Getenv("IN_TRAVIS_CI")) == 0 {
t.Logf("test will wait %v, then check TTL timeouts", waitTime)
}
errChan := make(chan error, concurrency)
syncChan := make(chan struct{})
for i := 0; i < concurrency; i++ {
go func() {
<-syncChan
for name := range testData {
svcs, err := m.GetService(name)
if err != nil {
errChan <- err
return
}
for _, svc := range svcs {
if len(svc.Nodes) > 0 {
errChan <- fmt.Errorf("Service %q still has nodes registered", name)
return
}
}
}
errChan <- nil
}()
}
time.Sleep(waitTime)
close(syncChan)
for i := 0; i < concurrency; i++ {
if err := <-errChan; err != nil {
t.Fatal(err)
}
}
}
|
[
"\"IN_TRAVIS_CI\""
] |
[] |
[
"IN_TRAVIS_CI"
] |
[]
|
["IN_TRAVIS_CI"]
|
go
| 1 | 0 | |
vendor/github.com/elastic/beats/vendor/k8s.io/apimachinery/pkg/runtime/converter.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 runtime
import (
"bytes"
encodingjson "encoding/json"
"fmt"
"math"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/klog"
)
// UnstructuredConverter is an interface for converting between interface{}
// and map[string]interface representation.
type UnstructuredConverter interface {
ToUnstructured(obj interface{}) (map[string]interface{}, error)
FromUnstructured(u map[string]interface{}, obj interface{}) error
}
type structField struct {
structType reflect.Type
field int
}
type fieldInfo struct {
name string
nameValue reflect.Value
omitempty bool
}
type fieldsCacheMap map[structField]*fieldInfo
type fieldsCache struct {
sync.Mutex
value atomic.Value
}
func newFieldsCache() *fieldsCache {
cache := &fieldsCache{}
cache.value.Store(make(fieldsCacheMap))
return cache
}
var (
marshalerType = reflect.TypeOf(new(encodingjson.Marshaler)).Elem()
unmarshalerType = reflect.TypeOf(new(encodingjson.Unmarshaler)).Elem()
mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{})
stringType = reflect.TypeOf(string(""))
int64Type = reflect.TypeOf(int64(0))
float64Type = reflect.TypeOf(float64(0))
boolType = reflect.TypeOf(bool(false))
fieldCache = newFieldsCache()
// DefaultUnstructuredConverter performs unstructured to Go typed object conversions.
DefaultUnstructuredConverter = &unstructuredConverter{
mismatchDetection: parseBool(os.Getenv("KUBE_PATCH_CONVERSION_DETECTOR")),
comparison: conversion.EqualitiesOrDie(
func(a, b time.Time) bool {
return a.UTC() == b.UTC()
},
),
}
)
func parseBool(key string) bool {
if len(key) == 0 {
return false
}
value, err := strconv.ParseBool(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't parse '%s' as bool for unstructured mismatch detection", key))
}
return value
}
// unstructuredConverter knows how to convert between interface{} and
// Unstructured in both ways.
type unstructuredConverter struct {
// If true, we will be additionally running conversion via json
// to ensure that the result is true.
// This is supposed to be set only in tests.
mismatchDetection bool
// comparison is the default test logic used to compare
comparison conversion.Equalities
}
// NewTestUnstructuredConverter creates an UnstructuredConverter that accepts JSON typed maps and translates them
// to Go types via reflection. It performs mismatch detection automatically and is intended for use by external
// test tools. Use DefaultUnstructuredConverter if you do not explicitly need mismatch detection.
func NewTestUnstructuredConverter(comparison conversion.Equalities) UnstructuredConverter {
return &unstructuredConverter{
mismatchDetection: true,
comparison: comparison,
}
}
// FromUnstructured converts an object from map[string]interface{} representation into a concrete type.
// It uses encoding/json/Unmarshaler if object implements it or reflection if not.
func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj interface{}) error {
t := reflect.TypeOf(obj)
value := reflect.ValueOf(obj)
if t.Kind() != reflect.Ptr || value.IsNil() {
return fmt.Errorf("FromUnstructured requires a non-nil pointer to an object, got %v", t)
}
err := fromUnstructured(reflect.ValueOf(u), value.Elem())
if c.mismatchDetection {
newObj := reflect.New(t.Elem()).Interface()
newErr := fromUnstructuredViaJSON(u, newObj)
if (err != nil) != (newErr != nil) {
klog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err)
}
if err == nil && !c.comparison.DeepEqual(obj, newObj) {
klog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj)
}
}
return err
}
func fromUnstructuredViaJSON(u map[string]interface{}, obj interface{}) error {
data, err := json.Marshal(u)
if err != nil {
return err
}
return json.Unmarshal(data, obj)
}
func fromUnstructured(sv, dv reflect.Value) error {
sv = unwrapInterface(sv)
if !sv.IsValid() {
dv.Set(reflect.Zero(dv.Type()))
return nil
}
st, dt := sv.Type(), dv.Type()
switch dt.Kind() {
case reflect.Map, reflect.Slice, reflect.Ptr, reflect.Struct, reflect.Interface:
// Those require non-trivial conversion.
default:
// This should handle all simple types.
if st.AssignableTo(dt) {
dv.Set(sv)
return nil
}
// We cannot simply use "ConvertibleTo", as JSON doesn't support conversions
// between those four groups: bools, integers, floats and string. We need to
// do the same.
if st.ConvertibleTo(dt) {
switch st.Kind() {
case reflect.String:
switch dt.Kind() {
case reflect.String:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Bool:
switch dt.Kind() {
case reflect.Bool:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
switch dt.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Float32, reflect.Float64:
switch dt.Kind() {
case reflect.Float32, reflect.Float64:
dv.Set(sv.Convert(dt))
return nil
}
if sv.Float() == math.Trunc(sv.Float()) {
dv.Set(sv.Convert(dt))
return nil
}
}
return fmt.Errorf("cannot convert %s to %s", st.String(), dt.String())
}
}
// Check if the object has a custom JSON marshaller/unmarshaller.
if reflect.PtrTo(dt).Implements(unmarshalerType) {
data, err := json.Marshal(sv.Interface())
if err != nil {
return fmt.Errorf("error encoding %s to json: %v", st.String(), err)
}
unmarshaler := dv.Addr().Interface().(encodingjson.Unmarshaler)
return unmarshaler.UnmarshalJSON(data)
}
switch dt.Kind() {
case reflect.Map:
return mapFromUnstructured(sv, dv)
case reflect.Slice:
return sliceFromUnstructured(sv, dv)
case reflect.Ptr:
return pointerFromUnstructured(sv, dv)
case reflect.Struct:
return structFromUnstructured(sv, dv)
case reflect.Interface:
return interfaceFromUnstructured(sv, dv)
default:
return fmt.Errorf("unrecognized type: %v", dt.Kind())
}
}
func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo {
fieldCacheMap := fieldCache.value.Load().(fieldsCacheMap)
if info, ok := fieldCacheMap[structField{structType, field}]; ok {
return info
}
// Cache miss - we need to compute the field name.
info := &fieldInfo{}
typeField := structType.Field(field)
jsonTag := typeField.Tag.Get("json")
if len(jsonTag) == 0 {
// Make the first character lowercase.
if typeField.Name == "" {
info.name = typeField.Name
} else {
info.name = strings.ToLower(typeField.Name[:1]) + typeField.Name[1:]
}
} else {
items := strings.Split(jsonTag, ",")
info.name = items[0]
for i := range items {
if items[i] == "omitempty" {
info.omitempty = true
}
}
}
info.nameValue = reflect.ValueOf(info.name)
fieldCache.Lock()
defer fieldCache.Unlock()
fieldCacheMap = fieldCache.value.Load().(fieldsCacheMap)
newFieldCacheMap := make(fieldsCacheMap)
for k, v := range fieldCacheMap {
newFieldCacheMap[k] = v
}
newFieldCacheMap[structField{structType, field}] = info
fieldCache.value.Store(newFieldCacheMap)
return info
}
func unwrapInterface(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
return v
}
func mapFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() != reflect.Map {
return fmt.Errorf("cannot restore map from %v", st.Kind())
}
if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
}
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.MakeMap(dt))
for _, key := range sv.MapKeys() {
value := reflect.New(dt.Elem()).Elem()
if val := unwrapInterface(sv.MapIndex(key)); val.IsValid() {
if err := fromUnstructured(val, value); err != nil {
return err
}
} else {
value.Set(reflect.Zero(dt.Elem()))
}
if st.Key().AssignableTo(dt.Key()) {
dv.SetMapIndex(key, value)
} else {
dv.SetMapIndex(key.Convert(dt.Key()), value)
}
}
return nil
}
func sliceFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() == reflect.String && dt.Elem().Kind() == reflect.Uint8 {
// We store original []byte representation as string.
// This conversion is allowed, but we need to be careful about
// marshaling data appropriately.
if len(sv.Interface().(string)) > 0 {
marshalled, err := json.Marshal(sv.Interface())
if err != nil {
return fmt.Errorf("error encoding %s to json: %v", st, err)
}
// TODO: Is this Unmarshal needed?
var data []byte
err = json.Unmarshal(marshalled, &data)
if err != nil {
return fmt.Errorf("error decoding from json: %v", err)
}
dv.SetBytes(data)
} else {
dv.Set(reflect.Zero(dt))
}
return nil
}
if st.Kind() != reflect.Slice {
return fmt.Errorf("cannot restore slice from %v", st.Kind())
}
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.MakeSlice(dt, sv.Len(), sv.Cap()))
for i := 0; i < sv.Len(); i++ {
if err := fromUnstructured(sv.Index(i), dv.Index(i)); err != nil {
return err
}
}
return nil
}
func pointerFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() == reflect.Ptr && sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.New(dt.Elem()))
switch st.Kind() {
case reflect.Ptr, reflect.Interface:
return fromUnstructured(sv.Elem(), dv.Elem())
default:
return fromUnstructured(sv, dv.Elem())
}
}
func structFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() != reflect.Map {
return fmt.Errorf("cannot restore struct from: %v", st.Kind())
}
for i := 0; i < dt.NumField(); i++ {
fieldInfo := fieldInfoFromField(dt, i)
fv := dv.Field(i)
if len(fieldInfo.name) == 0 {
// This field is inlined.
if err := fromUnstructured(sv, fv); err != nil {
return err
}
} else {
value := unwrapInterface(sv.MapIndex(fieldInfo.nameValue))
if value.IsValid() {
if err := fromUnstructured(value, fv); err != nil {
return err
}
} else {
fv.Set(reflect.Zero(fv.Type()))
}
}
}
return nil
}
func interfaceFromUnstructured(sv, dv reflect.Value) error {
// TODO: Is this conversion safe?
dv.Set(sv)
return nil
}
// ToUnstructured converts an object into map[string]interface{} representation.
// It uses encoding/json/Marshaler if object implements it or reflection if not.
func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {
var u map[string]interface{}
var err error
if unstr, ok := obj.(Unstructured); ok {
u = unstr.UnstructuredContent()
} else {
t := reflect.TypeOf(obj)
value := reflect.ValueOf(obj)
if t.Kind() != reflect.Ptr || value.IsNil() {
return nil, fmt.Errorf("ToUnstructured requires a non-nil pointer to an object, got %v", t)
}
u = map[string]interface{}{}
err = toUnstructured(value.Elem(), reflect.ValueOf(&u).Elem())
}
if c.mismatchDetection {
newUnstr := map[string]interface{}{}
newErr := toUnstructuredViaJSON(obj, &newUnstr)
if (err != nil) != (newErr != nil) {
klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
}
if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
}
}
if err != nil {
return nil, err
}
return u, nil
}
// DeepCopyJSON deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal() and also int64.
// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil
func DeepCopyJSON(x map[string]interface{}) map[string]interface{} {
return DeepCopyJSONValue(x).(map[string]interface{})
}
// DeepCopyJSONValue deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal() and also int64.
// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil
func DeepCopyJSONValue(x interface{}) interface{} {
switch x := x.(type) {
case map[string]interface{}:
if x == nil {
// Typed nil - an interface{} that contains a type map[string]interface{} with a value of nil
return x
}
clone := make(map[string]interface{}, len(x))
for k, v := range x {
clone[k] = DeepCopyJSONValue(v)
}
return clone
case []interface{}:
if x == nil {
// Typed nil - an interface{} that contains a type []interface{} with a value of nil
return x
}
clone := make([]interface{}, len(x))
for i, v := range x {
clone[i] = DeepCopyJSONValue(v)
}
return clone
case string, int64, bool, float64, nil, encodingjson.Number:
return x
default:
panic(fmt.Errorf("cannot deep copy %T", x))
}
}
func toUnstructuredViaJSON(obj interface{}, u *map[string]interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
return json.Unmarshal(data, u)
}
var (
nullBytes = []byte("null")
trueBytes = []byte("true")
falseBytes = []byte("false")
)
func getMarshaler(v reflect.Value) (encodingjson.Marshaler, bool) {
// Check value receivers if v is not a pointer and pointer receivers if v is a pointer
if v.Type().Implements(marshalerType) {
return v.Interface().(encodingjson.Marshaler), true
}
// Check pointer receivers if v is not a pointer
if v.Kind() != reflect.Ptr && v.CanAddr() {
v = v.Addr()
if v.Type().Implements(marshalerType) {
return v.Interface().(encodingjson.Marshaler), true
}
}
return nil, false
}
func toUnstructured(sv, dv reflect.Value) error {
// Check if the object has a custom JSON marshaller/unmarshaller.
if marshaler, ok := getMarshaler(sv); ok {
if sv.Kind() == reflect.Ptr && sv.IsNil() {
// We're done - we don't need to store anything.
return nil
}
data, err := marshaler.MarshalJSON()
if err != nil {
return err
}
switch {
case len(data) == 0:
return fmt.Errorf("error decoding from json: empty value")
case bytes.Equal(data, nullBytes):
// We're done - we don't need to store anything.
case bytes.Equal(data, trueBytes):
dv.Set(reflect.ValueOf(true))
case bytes.Equal(data, falseBytes):
dv.Set(reflect.ValueOf(false))
case data[0] == '"':
var result string
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding string from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
case data[0] == '{':
result := make(map[string]interface{})
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding object from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
case data[0] == '[':
result := make([]interface{}, 0)
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding array from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
default:
var (
resultInt int64
resultFloat float64
err error
)
if err = json.Unmarshal(data, &resultInt); err == nil {
dv.Set(reflect.ValueOf(resultInt))
} else if err = json.Unmarshal(data, &resultFloat); err == nil {
dv.Set(reflect.ValueOf(resultFloat))
} else {
return fmt.Errorf("error decoding number from json: %v", err)
}
}
return nil
}
st, dt := sv.Type(), dv.Type()
switch st.Kind() {
case reflect.String:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(stringType))
}
dv.Set(reflect.ValueOf(sv.String()))
return nil
case reflect.Bool:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(boolType))
}
dv.Set(reflect.ValueOf(sv.Bool()))
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(int64Type))
}
dv.Set(reflect.ValueOf(sv.Int()))
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uVal := sv.Uint()
if uVal > math.MaxInt64 {
return fmt.Errorf("unsigned value %d does not fit into int64 (overflow)", uVal)
}
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(int64Type))
}
dv.Set(reflect.ValueOf(int64(uVal)))
return nil
case reflect.Float32, reflect.Float64:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(float64Type))
}
dv.Set(reflect.ValueOf(sv.Float()))
return nil
case reflect.Map:
return mapToUnstructured(sv, dv)
case reflect.Slice:
return sliceToUnstructured(sv, dv)
case reflect.Ptr:
return pointerToUnstructured(sv, dv)
case reflect.Struct:
return structToUnstructured(sv, dv)
case reflect.Interface:
return interfaceToUnstructured(sv, dv)
default:
return fmt.Errorf("unrecognized type: %v", st.Kind())
}
}
func mapToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
if st.Key().Kind() == reflect.String {
switch st.Elem().Kind() {
// TODO It should be possible to reuse the slice for primitive types.
// However, it is panicing in the following form.
// case reflect.String, reflect.Bool,
// reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
// reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
// sv.Set(sv)
// return nil
default:
// We need to do a proper conversion.
}
}
dv.Set(reflect.MakeMap(mapStringInterfaceType))
dv = dv.Elem()
dt = dv.Type()
}
if dt.Kind() != reflect.Map {
return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
}
if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
}
for _, key := range sv.MapKeys() {
value := reflect.New(dt.Elem()).Elem()
if err := toUnstructured(sv.MapIndex(key), value); err != nil {
return err
}
if st.Key().AssignableTo(dt.Key()) {
dv.SetMapIndex(key, value)
} else {
dv.SetMapIndex(key.Convert(dt.Key()), value)
}
}
return nil
}
func sliceToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
if st.Elem().Kind() == reflect.Uint8 {
dv.Set(reflect.New(stringType))
data, err := json.Marshal(sv.Bytes())
if err != nil {
return err
}
var result string
if err = json.Unmarshal(data, &result); err != nil {
return err
}
dv.Set(reflect.ValueOf(result))
return nil
}
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
switch st.Elem().Kind() {
// TODO It should be possible to reuse the slice for primitive types.
// However, it is panicing in the following form.
// case reflect.String, reflect.Bool,
// reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
// reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
// sv.Set(sv)
// return nil
default:
// We need to do a proper conversion.
dv.Set(reflect.MakeSlice(reflect.SliceOf(dt), sv.Len(), sv.Cap()))
dv = dv.Elem()
dt = dv.Type()
}
}
if dt.Kind() != reflect.Slice {
return fmt.Errorf("cannot convert slice to: %v", dt.Kind())
}
for i := 0; i < sv.Len(); i++ {
if err := toUnstructured(sv.Index(i), dv.Index(i)); err != nil {
return err
}
}
return nil
}
func pointerToUnstructured(sv, dv reflect.Value) error {
if sv.IsNil() {
// We're done - we don't need to store anything.
return nil
}
return toUnstructured(sv.Elem(), dv)
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Map, reflect.Slice:
// TODO: It seems that 0-len maps are ignored in it.
return v.IsNil() || v.Len() == 0
case reflect.Ptr, reflect.Interface:
return v.IsNil()
}
return false
}
func structToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.MakeMapWithSize(mapStringInterfaceType, st.NumField()))
dv = dv.Elem()
dt = dv.Type()
}
if dt.Kind() != reflect.Map {
return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
}
realMap := dv.Interface().(map[string]interface{})
for i := 0; i < st.NumField(); i++ {
fieldInfo := fieldInfoFromField(st, i)
fv := sv.Field(i)
if fieldInfo.name == "-" {
// This field should be skipped.
continue
}
if fieldInfo.omitempty && isZero(fv) {
// omitempty fields should be ignored.
continue
}
if len(fieldInfo.name) == 0 {
// This field is inlined.
if err := toUnstructured(fv, dv); err != nil {
return err
}
continue
}
switch fv.Type().Kind() {
case reflect.String:
realMap[fieldInfo.name] = fv.String()
case reflect.Bool:
realMap[fieldInfo.name] = fv.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
realMap[fieldInfo.name] = fv.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
realMap[fieldInfo.name] = fv.Uint()
case reflect.Float32, reflect.Float64:
realMap[fieldInfo.name] = fv.Float()
default:
subv := reflect.New(dt.Elem()).Elem()
if err := toUnstructured(fv, subv); err != nil {
return err
}
dv.SetMapIndex(fieldInfo.nameValue, subv)
}
}
return nil
}
func interfaceToUnstructured(sv, dv reflect.Value) error {
if !sv.IsValid() || sv.IsNil() {
dv.Set(reflect.Zero(dv.Type()))
return nil
}
return toUnstructured(sv.Elem(), dv)
}
|
[
"\"KUBE_PATCH_CONVERSION_DETECTOR\""
] |
[] |
[
"KUBE_PATCH_CONVERSION_DETECTOR"
] |
[]
|
["KUBE_PATCH_CONVERSION_DETECTOR"]
|
go
| 1 | 0 | |
cache/init.go
|
package cache
import (
"conduit/util"
"os"
"strconv"
"github.com/go-redis/redis"
)
// RedisClient Redis缓存客户端单例
var RedisClient *redis.Client
// Redis 在中间件中初始化redis链接
func Redis() {
db, _ := strconv.ParseUint(os.Getenv("REDIS_DB"), 10, 64)
client := redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_ADDR"),
Password: os.Getenv("REDIS_PW"),
DB: int(db),
})
_, err := client.Ping().Result()
if err != nil {
util.Log().Panic("连接Redis不成功", err)
}
RedisClient = client
}
|
[
"\"REDIS_DB\"",
"\"REDIS_ADDR\"",
"\"REDIS_PW\""
] |
[] |
[
"REDIS_DB",
"REDIS_ADDR",
"REDIS_PW"
] |
[]
|
["REDIS_DB", "REDIS_ADDR", "REDIS_PW"]
|
go
| 3 | 0 | |
tests/opentelemetry-docker-tests/tests/postgres/test_aiopg_functional.py
|
# Copyright 2020, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import aiopg
import psycopg2
import pytest
from opentelemetry import trace as trace_api
from opentelemetry.instrumentation.aiopg import AiopgInstrumentor
from opentelemetry.test.test_base import TestBase
POSTGRES_HOST = os.getenv("POSTGRESQL_HOST", "localhost")
POSTGRES_PORT = int(os.getenv("POSTGRESQL_PORT", "5432"))
POSTGRES_DB_NAME = os.getenv("POSTGRESQL_DB_NAME", "opentelemetry-tests")
POSTGRES_PASSWORD = os.getenv("POSTGRESQL_PASSWORD", "testpassword")
POSTGRES_USER = os.getenv("POSTGRESQL_USER", "testuser")
def async_call(coro):
loop = asyncio.get_event_loop()
return loop.run_until_complete(coro)
class TestFunctionalAiopgConnect(TestBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._connection = None
cls._cursor = None
cls._tracer = cls.tracer_provider.get_tracer(__name__)
AiopgInstrumentor().instrument(tracer_provider=cls.tracer_provider)
cls._connection = async_call(
aiopg.connect(
dbname=POSTGRES_DB_NAME,
user=POSTGRES_USER,
password=POSTGRES_PASSWORD,
host=POSTGRES_HOST,
port=POSTGRES_PORT,
)
)
cls._cursor = async_call(cls._connection.cursor())
@classmethod
def tearDownClass(cls):
if cls._cursor:
cls._cursor.close()
if cls._connection:
cls._connection.close()
AiopgInstrumentor().uninstrument()
def validate_spans(self, span_name):
spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans), 2)
for span in spans:
if span.name == "rootSpan":
root_span = span
else:
child_span = span
self.assertIsInstance(span.start_time, int)
self.assertIsInstance(span.end_time, int)
self.assertIsNotNone(root_span)
self.assertIsNotNone(child_span)
self.assertEqual(root_span.name, "rootSpan")
self.assertEqual(child_span.name, span_name)
self.assertIsNotNone(child_span.parent)
self.assertIs(child_span.parent, root_span.get_span_context())
self.assertIs(child_span.kind, trace_api.SpanKind.CLIENT)
self.assertEqual(child_span.attributes["db.system"], "postgresql")
self.assertEqual(child_span.attributes["db.name"], POSTGRES_DB_NAME)
self.assertEqual(child_span.attributes["db.user"], POSTGRES_USER)
self.assertEqual(child_span.attributes["net.peer.name"], POSTGRES_HOST)
self.assertEqual(child_span.attributes["net.peer.port"], POSTGRES_PORT)
def test_execute(self):
"""Should create a child span for execute method"""
stmt = "CREATE TABLE IF NOT EXISTS test (id integer)"
with self._tracer.start_as_current_span("rootSpan"):
async_call(self._cursor.execute(stmt))
self.validate_spans(stmt)
def test_executemany(self):
"""Should create a child span for executemany"""
stmt = "INSERT INTO test (id) VALUES (%s)"
with pytest.raises(psycopg2.ProgrammingError):
with self._tracer.start_as_current_span("rootSpan"):
data = (("1",), ("2",), ("3",))
async_call(self._cursor.executemany(stmt, data))
self.validate_spans(stmt)
def test_callproc(self):
"""Should create a child span for callproc"""
with self._tracer.start_as_current_span("rootSpan"), self.assertRaises(
Exception
):
async_call(self._cursor.callproc("test", ()))
self.validate_spans("test")
class TestFunctionalAiopgCreatePool(TestBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._connection = None
cls._cursor = None
cls._tracer = cls.tracer_provider.get_tracer(__name__)
AiopgInstrumentor().instrument(tracer_provider=cls.tracer_provider)
cls._pool = async_call(
aiopg.create_pool(
dbname=POSTGRES_DB_NAME,
user=POSTGRES_USER,
password=POSTGRES_PASSWORD,
host=POSTGRES_HOST,
port=POSTGRES_PORT,
)
)
cls._connection = async_call(cls._pool.acquire())
cls._cursor = async_call(cls._connection.cursor())
@classmethod
def tearDownClass(cls):
if cls._cursor:
cls._cursor.close()
if cls._connection:
cls._connection.close()
if cls._pool:
cls._pool.close()
AiopgInstrumentor().uninstrument()
def validate_spans(self, span_name):
spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans), 2)
for span in spans:
if span.name == "rootSpan":
root_span = span
else:
child_span = span
self.assertIsInstance(span.start_time, int)
self.assertIsInstance(span.end_time, int)
self.assertIsNotNone(root_span)
self.assertIsNotNone(child_span)
self.assertEqual(root_span.name, "rootSpan")
self.assertEqual(child_span.name, span_name)
self.assertIsNotNone(child_span.parent)
self.assertIs(child_span.parent, root_span.get_span_context())
self.assertIs(child_span.kind, trace_api.SpanKind.CLIENT)
self.assertEqual(child_span.attributes["db.system"], "postgresql")
self.assertEqual(child_span.attributes["db.name"], POSTGRES_DB_NAME)
self.assertEqual(child_span.attributes["db.user"], POSTGRES_USER)
self.assertEqual(child_span.attributes["net.peer.name"], POSTGRES_HOST)
self.assertEqual(child_span.attributes["net.peer.port"], POSTGRES_PORT)
def test_execute(self):
"""Should create a child span for execute method"""
stmt = "CREATE TABLE IF NOT EXISTS test (id integer)"
with self._tracer.start_as_current_span("rootSpan"):
async_call(self._cursor.execute(stmt))
self.validate_spans(stmt)
def test_executemany(self):
"""Should create a child span for executemany"""
stmt = "INSERT INTO test (id) VALUES (%s)"
with pytest.raises(psycopg2.ProgrammingError):
with self._tracer.start_as_current_span("rootSpan"):
data = (("1",), ("2",), ("3",))
async_call(self._cursor.executemany(stmt, data))
self.validate_spans(stmt)
def test_callproc(self):
"""Should create a child span for callproc"""
with self._tracer.start_as_current_span("rootSpan"), self.assertRaises(
Exception
):
async_call(self._cursor.callproc("test", ()))
self.validate_spans("test")
|
[] |
[] |
[
"POSTGRESQL_HOST",
"POSTGRESQL_PORT",
"POSTGRESQL_DB_NAME",
"POSTGRESQL_PASSWORD",
"POSTGRESQL_USER"
] |
[]
|
["POSTGRESQL_HOST", "POSTGRESQL_PORT", "POSTGRESQL_DB_NAME", "POSTGRESQL_PASSWORD", "POSTGRESQL_USER"]
|
python
| 5 | 0 | |
Problem Solving/Algorithms/Find the Median.py
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'findMedian' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def findMedian(arr):
# Write your code here
return sorted(arr)[len(arr)//2]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = findMedian(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
[] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
python
| 1 | 0 | |
util/pkg/vfs/s3context.go
|
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vfs
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/golang/glog"
"os"
"sync"
)
type S3Context struct {
mutex sync.Mutex
clients map[string]*s3.S3
bucketLocations map[string]string
}
func NewS3Context() *S3Context {
return &S3Context{
clients: make(map[string]*s3.S3),
bucketLocations: make(map[string]string),
}
}
func (s *S3Context) getClient(region string) (*s3.S3, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
s3Client := s.clients[region]
if s3Client == nil {
config := aws.NewConfig().WithRegion(region)
config = config.WithCredentialsChainVerboseErrors(true)
session := session.New()
s3Client = s3.New(session, config)
}
s.clients[region] = s3Client
return s3Client, nil
}
func (s *S3Context) getRegionForBucket(bucket string) (string, error) {
region := func() string {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.bucketLocations[bucket]
}()
if region != "" {
return region, nil
}
// Probe to find correct region for bucket
awsRegion := os.Getenv("AWS_REGION")
if awsRegion == "" {
awsRegion = "us-east-1"
}
s3Client, err := s.getClient(awsRegion)
if err != nil {
return "", fmt.Errorf("unable to get client for querying s3 bucket location: %v", err)
}
request := &s3.GetBucketLocationInput{}
request.Bucket = aws.String(bucket)
glog.V(2).Infof("Querying S3 for bucket location for %q", bucket)
response, err := s3Client.GetBucketLocation(request)
if err != nil {
// TODO: Auto-create bucket?
return "", fmt.Errorf("error getting location for S3 bucket %q: %v", bucket, err)
}
if response.LocationConstraint == nil {
// US Classic does not return a region
region = "us-east-1"
} else {
region = *response.LocationConstraint
// Another special case: "EU" can mean eu-west-1
if region == "EU" {
region = "eu-west-1"
}
}
glog.V(2).Infof("Found bucket %q in region %q", bucket, region)
s.mutex.Lock()
defer s.mutex.Unlock()
s.bucketLocations[bucket] = region
return region, nil
}
|
[
"\"AWS_REGION\""
] |
[] |
[
"AWS_REGION"
] |
[]
|
["AWS_REGION"]
|
go
| 1 | 0 | |
learnElhoseinyRegressionModel.py
|
# -*- coding: utf-8 -*-
"""
Elhoseiny model based on Geodesic Regression model R_G
"""
import torch
from torch import nn, optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torch.nn.functional as F
from dataGenerators import ImagesAll, TestImages, my_collate
from axisAngle import get_error2, geodesic_loss
from poseModels import model_3layer
from helperFunctions import classes, get_accuracy
from featureModels import resnet_model, vgg_model
import numpy as np
import scipy.io as spio
import gc
import os
import time
import progressbar
import argparse
from tensorboardX import SummaryWriter
parser = argparse.ArgumentParser(description='Pure Regression Models')
parser.add_argument('--gpu_id', type=str, default='0')
parser.add_argument('--render_path', type=str, default='data/renderforcnn/')
parser.add_argument('--augmented_path', type=str, default='data/augmented2/')
parser.add_argument('--pascal3d_path', type=str, default='data/flipped_new/test/')
parser.add_argument('--save_str', type=str)
parser.add_argument('--num_workers', type=int, default=4)
parser.add_argument('--feature_network', type=str, default='resnet')
parser.add_argument('--N0', type=int, default=2048)
parser.add_argument('--N1', type=int, default=1000)
parser.add_argument('--N2', type=int, default=500)
parser.add_argument('--init_lr', type=float, default=1e-4)
parser.add_argument('--num_epochs', type=int, default=3)
args = parser.parse_args()
print(args)
# assign GPU
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
# save stuff here
results_file = os.path.join('results', args.save_str)
model_file = os.path.join('models', args.save_str + '.tar')
plots_file = os.path.join('plots', args.save_str)
log_dir = os.path.join('logs', args.save_str)
# relevant variables
ydata_type = 'axis_angle'
ndim = 3
num_classes = len(classes)
mse_loss = nn.MSELoss().cuda()
gve_loss = geodesic_loss().cuda()
ce_loss = nn.CrossEntropyLoss().cuda()
# DATA
# datasets
real_data = ImagesAll(args.augmented_path, 'real', ydata_type)
render_data = ImagesAll(args.render_path, 'render', ydata_type)
test_data = TestImages(args.pascal3d_path, ydata_type)
# setup data loaders
real_loader = DataLoader(real_data, batch_size=args.num_workers, shuffle=True, num_workers=args.num_workers, pin_memory=True, collate_fn=my_collate)
render_loader = DataLoader(render_data, batch_size=args.num_workers, shuffle=True, num_workers=args.num_workers, pin_memory=True, collate_fn=my_collate)
test_loader = DataLoader(test_data, batch_size=32)
print('Real: {0} \t Render: {1} \t Test: {2}'.format(len(real_loader), len(render_loader), len(test_loader)))
max_iterations = min(len(real_loader), len(render_loader))
# my_model
class ElhoseinyModel(nn.Module):
def __init__(self):
super().__init__()
self.num_classes = num_classes
if args.feature_network == 'resnet':
self.feature_model = resnet_model('resnet50', 'layer4').cuda()
elif args.feature_network == 'vgg':
self.feature_model = vgg_model('vgg13', 'fc6').cuda()
self.pose_model = model_3layer(args.N0, args.N1, args.N2, ndim).cuda()
self.category_model = nn.Linear(args.N0, num_classes).cuda()
def forward(self, x):
x = self.feature_model(x)
y0 = self.category_model(x)
y1 = self.pose_model(x)
y1 = np.pi*F.tanh(y1)
del x
return [y0, y1] # cat, pose
model = ElhoseinyModel()
# print(model)
# loss and optimizer
optimizer = optim.Adam(model.parameters(), lr=args.init_lr)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
# store stuff
writer = SummaryWriter(log_dir)
count = 0
val_err, val_acc = [], []
# OPTIMIZATION functions
def training_init():
global count, val_err, val_acc
model.train()
bar = progressbar.ProgressBar(max_value=max_iterations)
for i, (sample_real, sample_render) in enumerate(zip(real_loader, render_loader)):
# forward steps
xdata_real = Variable(sample_real['xdata'].cuda())
label_real = Variable(sample_real['label'].cuda())
ydata_real = Variable(sample_real['ydata'].cuda())
output_real = model(xdata_real)
xdata_render = Variable(sample_render['xdata'].cuda())
label_render = Variable(sample_render['label'].cuda())
ydata_render = Variable(sample_render['ydata'].cuda())
output_render = model(xdata_render)
output_pose = torch.cat((output_real[1], output_render[1]))
gt_pose = torch.cat((ydata_real, ydata_render))
Lr = mse_loss(output_pose, gt_pose)
Lc = ce_loss(output_real[0], label_real.squeeze())
loss = Lc + Lr
optimizer.zero_grad()
loss.backward()
optimizer.step()
# store
count += 1
writer.add_scalar('train_loss', loss.item(), count)
if i % 1000 == 0:
ytrue_cat, ytrue_pose, ypred_cat, ypred_pose = testing()
spio.savemat(results_file, {'ytrue_cat': ytrue_cat, 'ytrue_pose': ytrue_pose, 'ypred_cat': ypred_cat, 'ypred_pose': ypred_pose})
tmp_acc = get_accuracy(ytrue_cat, ypred_cat, num_classes)
tmp_err = get_error2(ytrue_pose, ypred_pose, ytrue_cat, num_classes)
writer.add_scalar('val_acc', tmp_acc, count)
writer.add_scalar('val_err', tmp_err, count)
val_acc.append(tmp_acc)
val_err.append(tmp_err)
# cleanup
del xdata_real, xdata_render, label_real, label_render, ydata_real, ydata_render, Lr, Lc
del output_real, output_render, sample_real, sample_render, loss, output_pose, gt_pose
bar.update(i)
# stop
if i == max_iterations:
break
render_loader.dataset.shuffle_images()
real_loader.dataset.shuffle_images()
def training():
global count, val_err, val_acc
model.train()
bar = progressbar.ProgressBar(max_value=max_iterations)
for i, (sample_real, sample_render) in enumerate(zip(real_loader, render_loader)):
# forward steps
xdata_real = Variable(sample_real['xdata'].cuda())
label_real = Variable(sample_real['label'].cuda())
ydata_real = Variable(sample_real['ydata'].cuda())
output_real = model(xdata_real)
xdata_render = Variable(sample_render['xdata'].cuda())
label_render = Variable(sample_render['label'].cuda())
ydata_render = Variable(sample_render['ydata'].cuda())
output_render = model(xdata_render)
output_pose = torch.cat((output_real[1], output_render[1]))
gt_pose = torch.cat((ydata_real, ydata_render))
Lr = gve_loss(output_pose, gt_pose)
Lc = ce_loss(output_real[0], label_real.squeeze())
loss = 0.1*Lc + Lr
optimizer.zero_grad()
loss.backward()
optimizer.step()
# store
count += 1
writer.add_scalar('train_loss', loss.item(), count)
if i % 1000 == 0:
ytrue_cat, ytrue_pose, ypred_cat, ypred_pose = testing()
spio.savemat(results_file, {'ytrue_cat': ytrue_cat, 'ytrue_pose': ytrue_pose, 'ypred_cat': ypred_cat, 'ypred_pose': ypred_pose})
tmp_acc = get_accuracy(ytrue_cat, ypred_cat, num_classes)
tmp_err = get_error2(ytrue_pose, ypred_pose, ytrue_cat, num_classes)
writer.add_scalar('val_acc', tmp_acc, count)
writer.add_scalar('val_err', tmp_err, count)
val_acc.append(tmp_acc)
val_err.append(tmp_err)
# cleanup
del xdata_real, xdata_render, label_real, label_render, ydata_real, ydata_render, Lr, Lc
del output_real, output_render, sample_real, sample_render, loss, output_pose, gt_pose
bar.update(i)
# stop
if i == max_iterations:
break
render_loader.dataset.shuffle_images()
real_loader.dataset.shuffle_images()
def testing():
model.eval()
ytrue_cat, ytrue_pose = [], []
ypred_cat, ypred_pose = [], []
for i, sample in enumerate(test_loader):
xdata = Variable(sample['xdata'].cuda())
output = model(xdata)
output_cat = output[0]
output_pose = output[1]
tmp_labels = np.argmax(output_cat.data.cpu().numpy(), axis=1)
ypred_cat.append(tmp_labels)
label = Variable(sample['label'])
ytrue_cat.append(sample['label'].squeeze().numpy())
ypred_pose.append(output_pose.data.cpu().numpy())
ytrue_pose.append(sample['ydata'].numpy())
del xdata, label, output, sample, output_cat, output_pose
gc.collect()
ytrue_cat = np.concatenate(ytrue_cat)
ypred_cat = np.concatenate(ypred_cat)
ytrue_pose = np.concatenate(ytrue_pose)
ypred_pose = np.concatenate(ypred_pose)
model.train()
return ytrue_cat, ytrue_pose, ypred_cat, ypred_pose
def save_checkpoint(filename):
torch.save(model.state_dict(), filename)
# initialization
training_init()
ytrue_cat, ytrue_pose, ypred_cat, ypred_pose = testing()
spio.savemat(results_file, {'ytrue_cat': ytrue_cat, 'ytrue_pose': ytrue_pose, 'ypred_cat': ypred_cat, 'ypred_pose': ypred_pose})
tmp_acc = get_accuracy(ytrue_cat, ypred_cat, num_classes)
tmp_err = get_error2(ytrue_pose, ypred_pose, ytrue_cat, num_classes)
print('Acc: {0} \t Err: {1}'.format(tmp_acc, tmp_err))
for epoch in range(args.num_epochs):
tic = time.time()
scheduler.step()
# training step
training()
# save model at end of epoch
save_checkpoint(model_file)
# validation
ytrue_cat, ytrue_pose, ypred_cat, ypred_pose = testing()
spio.savemat(results_file, {'ytrue_cat': ytrue_cat, 'ytrue_pose': ytrue_pose, 'ypred_cat': ypred_cat, 'ypred_pose': ypred_pose})
tmp_acc = get_accuracy(ytrue_cat, ypred_cat, num_classes)
tmp_err = get_error2(ytrue_pose, ypred_pose, ytrue_cat, num_classes)
print('Acc: {0} \t Err: {1}'.format(tmp_acc, tmp_err))
# time and output
toc = time.time() - tic
print('Epoch: {0} done in time {1}s'.format(epoch, toc))
# cleanup
gc.collect()
writer.close()
val_acc = np.stack(val_acc)
val_err = np.stack(val_err)
spio.savemat(plots_file, {'val_acc': val_acc, 'val_err': val_err})
# evaluate the model
ytrue_cat, ytrue_pose, ypred_cat, ypred_pose = testing()
spio.savemat(results_file, {'ytrue_cat': ytrue_cat, 'ytrue_pose': ytrue_pose, 'ypred_cat': ypred_cat, 'ypred_pose': ypred_pose})
tmp_acc = get_accuracy(ytrue_cat, ypred_cat, num_classes)
tmp_err = get_error2(ytrue_pose, ypred_pose, ytrue_cat, num_classes)
print('Acc: {0} \t Err: {1}'.format(tmp_acc, tmp_err))
|
[] |
[] |
[
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_VISIBLE_DEVICES"]
|
python
| 1 | 0 | |
services/ui_backend_service/api/ws.py
|
import os
import json
import time
import asyncio
import collections
from aiohttp import web, WSMsgType
from typing import List, Dict, Any, Callable
from .utils import resource_conditions, TTLQueue
from services.utils import logging
from pyee import AsyncIOEventEmitter
from ..data.refiner import TaskRefiner, ArtifactRefiner
from throttler import throttle_simultaneous
WS_QUEUE_TTL_SECONDS = os.environ.get("WS_QUEUE_TTL_SECONDS", 60 * 5) # 5 minute TTL by default
WS_POSTPROCESS_CONCURRENCY_LIMIT = int(os.environ.get("WS_POSTPROCESS_CONCURRENCY_LIMIT", 8))
SUBSCRIBE = 'SUBSCRIBE'
UNSUBSCRIBE = 'UNSUBSCRIBE'
WSSubscription = collections.namedtuple(
"WSSubscription", "ws disconnected_ts fullpath resource query uuid filter")
class Websocket(object):
'''
Adds a '/ws' endpoint and support for broadcasting realtime resource events to subscribed frontend clients.
Subscribe to runs created by user dipper:
/runs?_tags=user:dipper
'uuid' can be used to identify specific subscription.
Subscribe to future events:
{"type": "SUBSCRIBE", "uuid": "myst3rySh4ck", "resource": "/runs"}
Subscribing to future events and return past data since unix time (seconds):
{"type": "SUBSCRIBE", "uuid": "myst3rySh4ck", "resource": "/runs", "since": 1602752197}
Unsubscribe:
{"type": "UNSUBSCRIBE", "uuid": "myst3rySh4ck"}
Example event:
{"type": "UPDATE", "uuid": "myst3rySh4ck", "resource": "/runs", "data": {"foo": "bar"}}
'''
subscriptions: List[WSSubscription] = []
def __init__(self, app, db, event_emitter=None, queue_ttl: int = WS_QUEUE_TTL_SECONDS, cache=None):
self.event_emitter = event_emitter or AsyncIOEventEmitter()
self.db = db
self.queue = TTLQueue(queue_ttl)
self.task_refiner = TaskRefiner(cache=cache.artifact_cache) if cache else None
self.artifact_refiner = ArtifactRefiner(cache=cache.artifact_cache) if cache else None
self.logger = logging.getLogger("Websocket")
event_emitter.on('notify', self.event_handler)
app.router.add_route('GET', '/ws', self.websocket_handler)
self.loop = asyncio.get_event_loop()
async def event_handler(self, operation: str, resources: List[str], data: Dict, table_name: str = None, filter_dict: Dict = {}):
"""
Event handler for websocket events on 'notify'.
Either receives raw data from table triggers listener and either performs a database load
before broadcasting from the provided table, or receives predefined data and broadcasts it as-is.
Parameters
----------
operation : str
name of the operation related to the DB event, either 'INSERT' or 'UPDATE'
resources : List[str]
List of resource paths that this event is related to. Used strictly for broadcasting to
websocket subscriptions
data : Dict
The data of the record to be broadcast. Can either be complete, or partial.
In case of partial data (and a provided table name) this is only used for the DB query.
table_name : str (optional)
name of the table that the complete data should be queried from.
filter_dict : Dict (optional)
a dictionary of filters used in the query when fetching complete data.
"""
# Check if event needs to be broadcast (if anyone is subscribed to the resource)
if any(subscription.resource in resources for subscription in self.subscriptions):
# load the data and postprocessor for broadcasting if table
# is provided (otherwise data has already been loaded in advance)
if table_name:
table = self.db.get_table_by_name(table_name)
_postprocess = await self.get_table_postprocessor(table_name)
_data = await load_data_from_db(table, data, filter_dict, postprocess=_postprocess)
else:
_data = data
if not _data:
# Skip sending this event to subscriptions in case data is None or empty.
# This could be caused by insufficient/broken data and can break the UI.
return
# Append event to the queue so that we can later dispatch them in case of disconnections
#
# NOTE: server instance specific ws queue will not work when scaling across multiple instances.
# but on the other hand loading data and pushing everything into the queue for every server instance is also
# a suboptimal solution.
await self.queue.append({
'operation': operation,
'resources': resources,
'data': _data
})
for subscription in self.subscriptions:
try:
if subscription.disconnected_ts and time.time() - subscription.disconnected_ts > WS_QUEUE_TTL_SECONDS:
await self.unsubscribe_from(subscription.ws, subscription.uuid)
else:
await self._event_subscription(subscription, operation, resources, _data)
except ConnectionResetError:
self.logger.debug("Trying to broadcast to a stale subscription. Unsubscribing")
await self.unsubscribe_from(subscription.ws, subscription.uuid)
except Exception:
self.logger.exception("Broadcasting to subscription failed")
async def _event_subscription(self, subscription: WSSubscription, operation: str, resources: List[str], data: Dict):
for resource in resources:
if subscription.resource == resource:
# Check if possible filters match this event
# only if the subscription actually provided conditions.
if subscription.filter:
filters_match_request = subscription.filter(data)
else:
filters_match_request = True
if filters_match_request:
payload = {'type': operation, 'uuid': subscription.uuid,
'resource': resource, 'data': data}
await subscription.ws.send_str(json.dumps(payload))
async def subscribe_to(self, ws, uuid: str, resource: str, since: int):
# Always unsubscribe existing duplicate identifiers
await self.unsubscribe_from(ws, uuid)
# Create new subscription
_resource, query, filter_fn = resource_conditions(resource)
subscription = WSSubscription(
ws=ws, fullpath=resource, resource=_resource, query=query, uuid=uuid,
filter=filter_fn, disconnected_ts=None)
self.subscriptions.append(subscription)
# Send previous events that client might have missed due to disconnection
if since:
# Subtract 1 second to make sure all events are included
event_queue = await self.queue.values_since(since)
for _, event in event_queue:
self.loop.create_task(
self._event_subscription(subscription, event['operation'], event['resources'], event['data'])
)
async def unsubscribe_from(self, ws, uuid: str = None):
if uuid:
self.subscriptions = list(
filter(lambda s: uuid != s.uuid or ws != s.ws, self.subscriptions))
else:
self.subscriptions = list(
filter(lambda s: ws != s.ws, self.subscriptions))
async def handle_disconnect(self, ws):
"""
Sets disconnected timestamp on websocket subscription without removing it from the list.
Removing is handled by event_handler that checks for expired subscriptions before emitting
"""
self.subscriptions = list(
map(
lambda sub: sub._replace(disconnected_ts=time.time()) if sub.ws == ws else sub,
self.subscriptions)
)
async def websocket_handler(self, request):
"Handler for received messages from the open Web Socket connection."
# TODO: Consider using options autoping=True and heartbeat=20 if supported by clients.
ws = web.WebSocketResponse()
await ws.prepare(request)
while not ws.closed:
async for msg in ws:
if msg.type == WSMsgType.TEXT:
try:
# Custom ping message handling.
# If someone is pinging, lets answer with pong rightaway.
if msg.data == "__ping__":
await ws.send_str("__pong__")
else:
payload = json.loads(msg.data)
op_type = payload.get("type")
resource = payload.get("resource")
uuid = payload.get("uuid")
since = payload.get("since")
if since is not None and str(since).isnumeric():
since = int(since)
else:
since = None
if op_type == SUBSCRIBE and uuid and resource:
await self.subscribe_to(ws, uuid, resource, since)
elif op_type == UNSUBSCRIBE and uuid:
await self.unsubscribe_from(ws, uuid)
except Exception:
self.logger.exception("Exception occurred.")
# Always remove clients from listeners
await self.handle_disconnect(ws)
return ws
@throttle_simultaneous(count=8)
async def get_table_postprocessor(self, table_name):
if table_name == self.db.task_table_postgres.table_name:
return self.task_refiner.postprocess
elif table_name == self.db.artifact_table_postgres.table_name:
return self.artifact_refiner.postprocess
else:
return None
async def load_data_from_db(table, data: Dict[str, Any],
filter_dict: Dict = {},
postprocess: Callable = None):
# filter the data for loading based on available primary keys
conditions_dict = {
key: data[key] for key in table.primary_keys
if key in data
}
filter_dict = {**conditions_dict, **filter_dict}
conditions, values = [], []
for k, v in filter_dict.items():
conditions.append("{} = %s".format(k))
values.append(v)
results, *_ = await table.find_records(
conditions=conditions, values=values, fetch_single=True,
enable_joins=True,
expanded=True,
postprocess=postprocess
)
return results.body
|
[] |
[] |
[
"WS_QUEUE_TTL_SECONDS",
"WS_POSTPROCESS_CONCURRENCY_LIMIT"
] |
[]
|
["WS_QUEUE_TTL_SECONDS", "WS_POSTPROCESS_CONCURRENCY_LIMIT"]
|
python
| 2 | 0 | |
manage.py
|
#!/usr/bin/env python
import os
import sys
import pymysql
pymysql.install_as_MySQLdb()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
# """Django's command-line utility for administrative tasks."""
# import os
# import sys
# def main():
# """Run administrative tasks."""
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.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 | |
main.go
|
package main
import (
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/allinbits/cosmos-cash-resolver/resolver"
"github.com/allinbits/cosmos-cash-resolver/x/did/types"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/time/rate"
"google.golang.org/grpc"
)
const (
MaxReqPerSecond = 5
DidPrefix = "did:cosmos:"
)
var (
serverAddr = flag.String("grpc-server-address", "localhost:9090", "The target grpc server address in the format of host:port")
listenAddr = flag.String("listen-address", "0.0.0.0:2109", "The REST server listen address in the format of host:port")
rpsLimit = flag.Int("mrps", 10, "Max-Requests-Per-Seconds: define the throttle limit in requests per seconds")
)
// loadSettings load the settings from flags and env vars. Env vars have priority over flags
func loadSettings() {
flag.Parse()
if val := os.Getenv("GRPC_SERVER_ADDRESS"); val != "" {
serverAddr = &val
}
if val := os.Getenv("LISTEN_ADDRESS"); val != "" {
listenAddr = &val
}
if val := os.Getenv("MRPS"); val != "" {
l, err := strconv.Atoi(val)
if err != nil {
log.Fatalln("invalid int value for MRPS")
}
rpsLimit = &l
}
}
// openGRPCConnection
func openGRPCConnection(addr string) (conn *grpc.ClientConn, err error) {
opts := []grpc.DialOption{
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithTimeout(time.Duration(3) * time.Second),
}
conn, err = grpc.Dial(addr, opts...)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
return
}
type Runtime struct {
resolves uint64
startTime time.Time
}
const (
didLDJson = "application/did+ld+json"
)
func main() {
loadSettings()
// setup server
e := echo.New()
e.Use(middleware.Logger())
e.HideBanner = true
e.StdLogger.Println("starting cosmos-cash-resolver rest server")
e.StdLogger.Println("target node is ", *serverAddr)
// track the curent runtime session
rt := Runtime{
resolves: 0,
startTime: time.Now(),
}
// open grpc connection
conn, err := openGRPCConnection(*serverAddr)
if err != nil {
e.StdLogger.Fatal(err)
}
defer conn.Close()
// start the rest server
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{http.MethodGet},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
}))
e.Use(middleware.RateLimiter(
middleware.NewRateLimiterMemoryStore(rate.Limit(*rpsLimit)),
))
e.GET("/identifier/:did", func(c echo.Context) error {
did := c.Param("did")
// decode the paramater
did, err = url.QueryUnescape(did)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{})
}
accept := strings.Split(c.Request().Header.Get("accept"), ";")[0]
opt := resolver.ResolutionOption{Accept: accept}
rr := resolver.ResolveRepresentation(conn, did, opt)
// add universal resolver specific data:
rr.ResolutionMetadata.DidProperties = map[string]string{
"method": "cosmos",
"methodSpecificId": strings.TrimPrefix(rr.Document.Id, DidPrefix),
}
// track the resolution
atomic.AddUint64(&rt.resolves, 1)
c.Response().Header().Set(echo.HeaderContentType, didLDJson)
return c.JSON(http.StatusOK, rr)
})
e.GET("/identifier/aries/:did", func(c echo.Context) error {
did := c.Param("did")
// decode the paramater
did, err = url.QueryUnescape(did)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{})
}
accept := strings.Split(c.Request().Header.Get("accept"), ";")[0]
opt := resolver.ResolutionOption{Accept: accept}
rr := resolver.ResolveRepresentation(conn, did, opt)
// add universal resolver specific data:
rr.ResolutionMetadata.DidProperties = map[string]string{
"method": "cosmos",
"methodSpecificId": strings.TrimPrefix(rr.Document.Id, DidPrefix),
}
// this will replace a did document verification material formatted in multibase to hex
for i, vm := range rr.Document.VerificationMethod {
if material, ok := vm.VerificationMaterial.(*types.VerificationMethod_PublicKeyMyltibase); ok {
if material.PublicKeyMyltibase[0:1] != "F" {
continue
}
vmHex := &types.VerificationMethod_PublicKeyHex{
PublicKeyHex: material.PublicKeyMyltibase[1:],
}
rr.Document.VerificationMethod[i].VerificationMaterial = vmHex
}
}
result := map[string]interface{}{
"didDocument": resolver.AriesDidDocument{
DidDocument: rr.Document,
Created: rr.Metadata.Created,
Updated: rr.Metadata.Updated,
},
}
// track the resolution
atomic.AddUint64(&rt.resolves, 1)
c.Response().Header().Set(echo.HeaderContentType, didLDJson)
return c.JSON(http.StatusOK, result)
})
e.GET("/", func(c echo.Context) error {
return c.HTML(http.StatusOK, fmt.Sprintf(`
<html><head></head><body style="font-family:courier; padding:.3rem .8rem">
<h1>Cosmos Cash DID Resolver</h1>
<p>started on %v</p>
<p>DIDs resolved since starting:</p>
<p style="font-size:124;margin:.3rem 0">%v</p>
<br/><br/>
Visit <a href="https://github.com/allinbits/cosmos-cash">Cosmos Cash</a> for more info
</body></html>`, rt.startTime.Format(time.RFC3339), rt.resolves))
})
e.StdLogger.Fatal(e.Start(*listenAddr))
}
|
[
"\"GRPC_SERVER_ADDRESS\"",
"\"LISTEN_ADDRESS\"",
"\"MRPS\""
] |
[] |
[
"MRPS",
"LISTEN_ADDRESS",
"GRPC_SERVER_ADDRESS"
] |
[]
|
["MRPS", "LISTEN_ADDRESS", "GRPC_SERVER_ADDRESS"]
|
go
| 3 | 0 | |
alerta/common/config.py
|
import os
import sys
import argparse
import ConfigParser
from alerta.common.utils import Bunch
CONF = Bunch() # config options can be accessed using CONF.verbose or CONF.use_syslog
prog = os.path.basename(sys.argv[0])
DEFAULTS = {
'config_file': '/etc/alerta/alerta.conf',
'timezone': 'Europe/London', # Australia/Sydney, America/Los_Angeles, etc.
'version': 'unknown',
'debug': 'no',
'verbose': 'no',
'log_dir': '/var/log/alerta',
'log_file': '%s.log' % prog,
'pid_dir': '/var/run/alerta',
'use_syslog': 'yes',
'use_stderr': 'no',
'foreground': 'no',
'user_id': 'alerta',
'server_threads': 4,
'disable_flag': '/var/run/alerta/%s.disable' % prog,
'loop_every': 30,
'global_timeout': 86400, # seconds
'console_limit': 1000, # max number of alerts sent to console
'history_limit': -10, # show last x most recent history entries
'dashboard_dir': '/',
}
config = ConfigParser.RawConfigParser(DEFAULTS)
config.set('DEFAULT', 'prog', prog)
_TRUE = ['yes', 'true', 'on']
_FALSE = ['no', 'false', 'off']
_boolean = _TRUE + _FALSE
def register_opts(opts, section=None):
'''
Options are registered to the 'DEFAULT' section
unless specified because it is assumed they are
system defaults eg. api_host, api_port.
'''
if not section:
section = 'DEFAULT'
elif not config.has_section(section):
config.add_section(section)
# True, False, numbers & lists
for k, v in opts.iteritems():
if type(v) == int:
v = str(v)
if type(v) == bool:
v = 'yes' if v else 'no'
if type(v) == list:
v = ','.join(v)
config.set(section, k, v)
parse_args(section=prog)
def parse_args(args=None, section=None, version='unknown', cli_parser=None, daemon=True):
if args is None:
args = sys.argv[1:]
section = section or prog
# get config file from command line, if defined
cfg_parser = argparse.ArgumentParser(
add_help=False
)
cfg_parser.add_argument(
'-c',
'--config-file',
help="Specify config file (default: %s)" % DEFAULTS['config_file'],
metavar="FILE",
default=DEFAULTS['config_file']
)
c, args = cfg_parser.parse_known_args(args)
config_file_order = [
c.config_file,
os.path.expanduser('~/.alerta.conf'),
os.environ.get('ALERTA_CONF', ''),
]
# read in system-wide defaults
config_files = config.read(config_file_order)
defaults = config.defaults().copy() # read in [DEFAULTS] section
defaults['config_file'] = ','.join(config_files)
if config_files:
if config.has_section(section): # read in program-specific sections
for name in config.options(section):
try:
defaults[name] = config.getint(section, name)
except ValueError:
if config.get(section, name).lower() in _boolean:
defaults[name] = config.getboolean(section, name)
else:
defaults[name] = config.get(section, name)
except TypeError:
defaults[name] = config.get(section, name)
# read in command line options
parents = [cfg_parser]
if cli_parser:
parents.append(cli_parser)
parser = argparse.ArgumentParser(
prog=prog,
# description='', # TODO(nsatterl): pass __doc__ from calling program?
parents=parents,
)
parser.add_argument(
'--version',
action='version',
version=version
)
parser.add_argument(
'--debug',
action='store_true',
help="Log level DEBUG and higher (default: WARNING)"
)
parser.add_argument(
'--verbose',
action='store_true',
help="Log level INFO and higher (default: WARNING)"
)
parser.add_argument(
'--log-dir',
metavar="DIR",
help="Log directory, prepended to --log-file"
)
parser.add_argument(
'--log-file',
metavar="FILE",
help="Log file name"
)
parser.add_argument(
'--pid-dir',
metavar="DIR",
help="PID directory"
)
parser.add_argument(
'--use-syslog',
action='store_true',
help="Send errors to syslog"
)
parser.add_argument(
'--use-stderr',
action='store_true',
help="Send to console stderr"
)
parser.add_argument(
'--yaml-config',
metavar="FILE",
action="store",
help="Path to the YAML configuration",
)
if daemon:
parser.add_argument(
'-f',
'--foreground',
action='store_true',
help="Do not fork, run in the foreground"
)
parser.set_defaults(**defaults)
args, extra = parser.parse_known_args(args)
copy = vars(args)
for k, v in vars(args).iteritems():
if type(v) == bool:
continue
try:
copy[k] = int(v)
continue
except TypeError:
continue # skip nulls
except ValueError:
pass
if v.lower() in _TRUE:
copy[k] = True
continue
elif v.lower() in _FALSE:
copy[k] = False
continue
if ',' in v:
copy[k] = v.split(',')
CONF.update(copy)
#print '[%s] %s' % (section, CONF)
|
[] |
[] |
[
"ALERTA_CONF"
] |
[]
|
["ALERTA_CONF"]
|
python
| 1 | 0 | |
moodle_notify.py
|
import requests
import datetime
import time
import os
from lotify.client import Client
def moodle_notify():
lotify = Client()
moodleToken = os.environ.get("MOODLE_TOKEN")
lineToken = os.environ.get("LINE_TOKEN")
url = f"{os.environ.get('MOODLE_URL')}webservice/rest/server.php"
currentTime = int(time.time())
dayTime = 86400
GMT8 = 28800
params = {"moodlewsrestformat": "json",
"wsfunction": "core_webservice_get_site_info", "wstoken": moodleToken}
userId = requests.get(url, params).json()["userid"]
params["wsfunction"] = "core_enrol_get_users_courses"
params["userid"] = userId
courses = requests.get(url, params).json()
params["wsfunction"] = "core_course_get_contents"
params.pop("userid")
typeParams = {"moodlewsrestformat": "json", "wstoken": moodleToken}
for course in courses:
params["courseid"] = course["id"]
courseContent = requests.get(url, params).json()
for i in courseContent:
modules = i["modules"]
for module in modules:
if module.get("contents") == None:
continue
for content in module["contents"]:
if int(content["timemodified"]) >= currentTime-dayTime:
lotify.send_message(
lineToken, f"{course['fullname']}\n{module['modplural']}: {module['name']}\nCheck it on moodle")
# assignments notify
typeParams["wsfunction"] = "mod_assign_get_assignments"
typeParams["courseids[0]"] = course["id"]
assignments = requests.get(url, typeParams).json()[
"courses"][0]["assignments"]
for assingment in assignments:
if int(assingment["timemodified"]) >= currentTime-dayTime and currentTime <= int(assingment["duedate"]):
dueDate = datetime.datetime.utcfromtimestamp(
int(assingment['duedate'])+GMT8).strftime('%Y-%m-%d %H:%M:%S')
lotify.send_message(
lineToken, f"{course['fullname']}\n作業: {assingment['name']}\nDue: {dueDate}\nCheck it on moodle")
if int(assingment["timemodified"]) >= currentTime-dayTime and assingment["duedate"] == 0:
lotify.send_message(
lineToken, f"{course['fullname']}\n作業: {assingment['name']}\nCheck it on moodle")
# quiz notify
typeParams["wsfunction"] = "mod_quiz_get_quizzes_by_courses"
quizzes = requests.get(url, typeParams).json()["quizzes"]
for quiz in quizzes:
if currentTime <= int(quiz["timeclose"]) and int(quiz["timeopen"]) >= currentTime-dayTime:
closeTime = datetime.datetime.utcfromtimestamp(
int(quiz['timeclose'])+GMT8).strftime('%Y-%m-%d %H:%M:%S')
lotify.send_message(
lineToken, f"{course['fullname']}\n考試: {quiz['name']}\nClose time: {closeTime}\nCheck it on moodle")
if __name__ == "__main__":
moodle_notify()
|
[] |
[] |
[
"MOODLE_TOKEN",
"LINE_TOKEN",
"MOODLE_URL"
] |
[]
|
["MOODLE_TOKEN", "LINE_TOKEN", "MOODLE_URL"]
|
python
| 3 | 0 | |
integration/integration_test.go
|
//go:build integration
// +build integration
// can be execute with go test -tags=integration ./integration/...
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/piperutils"
)
func TestPiperHelp(t *testing.T) {
t.Parallel()
piperHelpCmd := command.Command{}
var commandOutput bytes.Buffer
piperHelpCmd.Stdout(&commandOutput)
err := piperHelpCmd.RunExecutable(getPiperExecutable(), "--help")
assert.NoError(t, err, "Calling piper --help failed")
assert.Contains(t, commandOutput.String(), "Use \"piper [command] --help\" for more information about a command.")
}
func getPiperExecutable() string {
if p := os.Getenv("PIPER_INTEGRATION_EXECUTABLE"); len(p) > 0 {
fmt.Println("Piper executable for integration test: " + p)
return p
}
f := piperutils.Files{}
wd, _ := os.Getwd()
localPiper := path.Join(wd, "..", "piper")
exists, _ := f.FileExists(localPiper)
if exists {
fmt.Println("Piper executable for integration test: " + localPiper)
return localPiper
}
fmt.Println("Piper executable for integration test: Using 'piper' from PATH")
return "piper"
}
// copyDir copies a directory
func copyDir(source string, target string) error {
var err error
var fileInfo []os.FileInfo
var sourceInfo os.FileInfo
if sourceInfo, err = os.Stat(source); err != nil {
return err
}
if err = os.MkdirAll(target, sourceInfo.Mode()); err != nil {
return err
}
if fileInfo, err = ioutil.ReadDir(source); err != nil {
return err
}
for _, info := range fileInfo {
sourcePath := path.Join(source, info.Name())
targetPath := path.Join(target, info.Name())
if info.IsDir() {
if err = copyDir(sourcePath, targetPath); err != nil {
return err
}
} else {
if err = copyFile(sourcePath, targetPath); err != nil {
return err
}
}
}
return nil
}
func copyFile(source, target string) error {
var err error
var sourceFile *os.File
var targetFile *os.File
var sourceInfo os.FileInfo
if sourceFile, err = os.Open(source); err != nil {
return err
}
defer sourceFile.Close()
if targetFile, err = os.Create(target); err != nil {
return err
}
defer targetFile.Close()
if _, err = io.Copy(targetFile, sourceFile); err != nil {
return err
}
if sourceInfo, err = os.Stat(source); err != nil {
return err
}
return os.Chmod(target, sourceInfo.Mode())
}
func createTmpDir(prefix string) (string, error) {
dirName := os.TempDir()
tmpDir, err := filepath.EvalSymlinks(dirName)
if err != nil {
return "", err
}
tmpDir = filepath.Clean(tmpDir)
path, err := ioutil.TempDir(tmpDir, prefix)
if err != nil {
return "", err
}
return path, nil
}
|
[
"\"PIPER_INTEGRATION_EXECUTABLE\""
] |
[] |
[
"PIPER_INTEGRATION_EXECUTABLE"
] |
[]
|
["PIPER_INTEGRATION_EXECUTABLE"]
|
go
| 1 | 0 | |
misc/test/examples_test.go
|
// Copyright 2016-2017, Pulumi Corporation. All rights reserved.
package test
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
homedir "github.com/mitchellh/go-homedir"
"github.com/pulumi/pulumi/pkg/v2/testing/integration"
"github.com/pulumi/pulumi/sdk/v2/go/common/resource"
"github.com/stretchr/testify/assert"
)
func TestAccAwsGoEks(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-go-eks"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["url"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello Kubernetes bootcamp!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsGoFargate(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-go-fargate"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["url"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsGoS3Folder(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-go-s3-folder"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["websiteUrl"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, world!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsGoS3FolderComponent(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-go-s3-folder-component"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["websiteUrl"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, world!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsGoWebserver(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-go-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["publicIp"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsCsS3Folder(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-cs-s3-folder"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["Endpoint"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, world!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsFsS3Folder(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-fs-s3-folder"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["endpoint"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, world!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsContainers(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-containers"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["frontendURL"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsS3Folder(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-s3-folder"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, "http://"+stack.Outputs["websiteUrl"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsS3FolderComponent(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-s3-folder-component"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["websiteUrl"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsSqsSlack(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-sqs-slack"),
Config: map[string]string{
"slackToken": "token",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsWebserver(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPHelloWorld(t, stack.Outputs["publicHostName"], nil)
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsJsWebserverComponent(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-js-webserver-component"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPHelloWorld(t, stack.Outputs["webUrl"], nil)
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsPyAppSync(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-py-appsync"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsPyResources(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-py-resources"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsPyS3Folder(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-py-s3-folder"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, "http://"+stack.Outputs["website_url"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsPyStepFunctions(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-py-stepfunctions"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsPyWebserver(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-py-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, "http://"+stack.Outputs["public_dns"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsAirflow(t *testing.T) {
t.Skip("Skip due to failures initializing 20(!) instances")
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-airflow"),
Config: map[string]string{
"airflow:dbPassword": "secretP4ssword",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsApiGateway(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-apigateway"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["endpoint"].(string)
assertHTTPResultWithRetry(t, endpoint+"hello", nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "route")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsAppSync(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-appsync"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsAssumeRole(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-assume-role", "create-role"),
Config: map[string]string{
"create-role:unprivilegedUsername": "unpriv",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsContainers(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-containers"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 15 * time.Minute
endpoint := stack.Outputs["frontendURL"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsEc2Provisioners(t *testing.T) {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(getAwsRegion())},
)
assert.NoError(t, err)
svc := ec2.New(sess)
keyName, err := resource.NewUniqueHex("test-keyname", 8, 20)
assert.NoError(t, err)
t.Logf("Creating keypair %s.\n", keyName)
key, err := svc.CreateKeyPair(&ec2.CreateKeyPairInput{
KeyName: aws.String(keyName),
})
assert.NoError(t, err)
defer func() {
t.Logf("Deleting keypair %s.\n", keyName)
_, err := svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{
KeyName: aws.String(keyName),
})
assert.NoError(t, err)
}()
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-ec2-provisioners"),
Config: map[string]string{
"keyName": aws.StringValue(key.KeyName),
},
Secrets: map[string]string{
"privateKey": base64.StdEncoding.EncodeToString([]byte(aws.StringValue(key.KeyMaterial))),
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
catConfigStdout := stack.Outputs["catConfigStdout"].(string)
assert.Equal(t, "[test]\nx = 42\n", catConfigStdout)
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsEks(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-eks"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsEksHelloWorld(t *testing.T) {
t.Skip("Skip due to frequent failures: `timeout while waiting for state to become 'ACTIVE'`")
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-eks-hello-world"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["serviceHostname"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsHelloFargate(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-hello-fargate"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
maxWait := 10 * time.Minute
endpoint := stack.Outputs["url"].(string)
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsPulumiWebhooks(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-pulumi-webhooks"),
Config: map[string]string{
"cloud:provider": "aws",
"aws-ts-pulumi-webhooks:slackChannel": "general",
"aws-ts-pulumi-webhooks:slackToken": "12345",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsPulumiMiniflux(t *testing.T) {
t.Skip("Skip until ECS Service supports custom timeouts")
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-pulumi-miniflux"),
Config: map[string]string{
"aws-ts-pulumi-miniflux:db_name": "miniflux",
"aws-ts-pulumi-miniflux:db_username": "minifluxuser",
"aws-ts-pulumi-miniflux:db_password": "2Password2",
"aws-ts-pulumi-miniflux:admin_username": "adminuser",
"aws-ts-pulumi-miniflux:admin_password": "2Password2",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsResources(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-resources"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsS3LambdaCopyZip(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-s3-lambda-copyzip"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsSlackbot(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-slackbot"),
Config: map[string]string{
"mentionbot:slackToken": "XXX",
"mentionbot:verificationToken": "YYY",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsStepFunctions(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-stepfunctions"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsThumbnailer(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-thumbnailer"),
})
integration.ProgramTest(t, &test)
}
func TestAccAwsTsTwitterAthena(t *testing.T) {
test := getAWSBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "aws-ts-twitter-athena"),
Config: map[string]string{
"aws-ts-twitter-athena:twitterConsumerKey": "12345",
"aws-ts-twitter-athena:twitterConsumerSecret": "xyz",
"aws-ts-twitter-athena:twitterAccessTokenKey": "12345",
"aws-ts-twitter-athena:twitterAccessTokenSecret": "xyz",
"aws-ts-twitter-athena:twitterQuery": "smurfs",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureCsAppService(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-cs-appservice"),
Config: map[string]string{
"sqlPassword": "2@Password@2",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["Endpoint"], func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure App Service!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureCsWebserver(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-cs-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["IpAddress"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, World")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureFsAppService(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-fs-appservice"),
Config: map[string]string{
"sqlPassword": "2@Password@2",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["endpoint"], func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure App Service!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureGoAci(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-go-aci"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["endpoint"], func(body string) bool {
return assert.Contains(t, body, "Hello, containers!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureGoAks(t *testing.T) {
t.Skip("The credentials in ServicePrincipalProfile were invalid")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-go-aks"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["url"], func(body string) bool {
return assert.Contains(t, body, "Hello Kubernetes bootcamp!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureGoAppservice(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-go-appservice"),
Config: map[string]string{
"sqlPassword": "2@Password@2",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["endpoint"], func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure App Service!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureGoWebserverComponent(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-go-webserver-component"),
Config: map[string]string{
"username": "webmaster",
"password": "Password1234!",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureJsWebserver(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-js-webserver"),
Config: map[string]string{
"username": "testuser",
"password": "testTEST1234+-*/",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPHelloWorld(t, stack.Outputs["publicIP"], nil)
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyAks(t *testing.T) {
t.Skip("The credentials in ServicePrincipalProfile were invalid")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-aks"),
Config: map[string]string{
"password": "testTEST1234+_^$",
"sshkey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDeREOgHTUgPT00PTr7iQF9JwZQ4QF1VeaLk2nHKRvWYOCiky6hDtzhmLM0k0Ib9Y7cwFbhObR+8yZpCgfSX3Hc3w2I1n6lXFpMfzr+wdbpx97N4fc1EHGUr9qT3UM1COqN6e/BEosQcMVaXSCpjqL1jeNaRDAnAS2Y3q1MFeXAvj9rwq8EHTqqAc1hW9Lq4SjSiA98STil5dGw6DWRhNtf6zs4UBy8UipKsmuXtclR0gKnoEP83ahMJOpCIjuknPZhb+HsiNjFWf+Os9U6kaS5vGrbXC8nggrVE57ow88pLCBL+3mBk1vBg6bJuLBCp2WTqRzDMhSDQ3AcWqkucGqf dremy@remthinkpad",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyAppService(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-appservice"),
Config: map[string]string{
"sqlPassword": "2@Password@2",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["endpoint"], func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure App Service!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyAppServiceDocker(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-appservice-docker"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["hello_endpoint"], func(body string) bool {
return assert.Contains(t, body, "Hello, world!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyHdInsightSpark(t *testing.T) {
t.Skip("Skipping HDInsights tests due to a stuck cluster in the account")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-hdinsight-spark"),
Config: map[string]string{
"username": "testuser",
"password": "MyPassword123+-*/",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyVmScaleSet(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-vm-scaleset"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["public_address"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "nginx")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzurePyWebserver(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-py-webserver"),
Config: map[string]string{
"azure-web:username": "testuser",
"azure-web:password": "testTEST1234+-*/",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPHelloWorld(t, stack.Outputs["public_ip"], nil)
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsAppService(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-appservice"),
Config: map[string]string{
"sqlPassword": "2@Password@2",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["endpoint"], func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure App Service!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsAppServiceDocker(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-appservice-docker"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertAppServiceResult(t, stack.Outputs["getStartedEndpoint"], func(body string) bool {
return assert.Contains(t, body, "Azure App Service")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsArmTemplate(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-arm-template"),
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsFunctions(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-functions"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpoint"], nil, func(body string) bool {
return assert.Contains(t, body, "Greetings from Azure Functions!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsHdInsightSpark(t *testing.T) {
t.Skip("Skipping HDInsights tests due to a stuck cluster in the account")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-hdinsight-spark"),
Config: map[string]string{
"username": "testuser",
"password": "MyPassword123+-*/",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsStreamAnalytics(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-stream-analytics"),
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsVmScaleset(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-vm-scaleset"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["publicAddress"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "nginx")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsWebserver(t *testing.T) {
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-webserver"),
Config: map[string]string{
"username": "webmaster",
"password": "MySuperS3cretPassw0rd",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["ipAddress"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, World")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsAksHelm(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping Azure tests temporarily")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-aks-helm"),
Config: map[string]string{
"password": "testTEST1234+_^$",
"sshPublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDeREOgHTUgPT00PTr7iQF9JwZQ4QF1VeaLk2nHKRvWYOCiky6hDtzhmLM0k0Ib9Y7cwFbhObR+8yZpCgfSX3Hc3w2I1n6lXFpMfzr+wdbpx97N4fc1EHGUr9qT3UM1COqN6e/BEosQcMVaXSCpjqL1jeNaRDAnAS2Y3q1MFeXAvj9rwq8EHTqqAc1hW9Lq4SjSiA98STil5dGw6DWRhNtf6zs4UBy8UipKsmuXtclR0gKnoEP83ahMJOpCIjuknPZhb+HsiNjFWf+Os9U6kaS5vGrbXC8nggrVE57ow88pLCBL+3mBk1vBg6bJuLBCp2WTqRzDMhSDQ3AcWqkucGqf dremy@remthinkpad",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["serviceIP"], nil, func(body string) bool {
return assert.Contains(t, body, "It works!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsAksKeda(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping Azure tests temporarily")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-aks-keda"),
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsAksMulticluster(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping Azure tests temporarily")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-aks-multicluster"),
Config: map[string]string{
"password": "testTEST1234+_^$",
"sshPublicKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDeREOgHTUgPT00PTr7iQF9JwZQ4QF1VeaLk2nHKRvWYOCiky6hDtzhmLM0k0Ib9Y7cwFbhObR+8yZpCgfSX3Hc3w2I1n6lXFpMfzr+wdbpx97N4fc1EHGUr9qT3UM1COqN6e/BEosQcMVaXSCpjqL1jeNaRDAnAS2Y3q1MFeXAvj9rwq8EHTqqAc1hW9Lq4SjSiA98STil5dGw6DWRhNtf6zs4UBy8UipKsmuXtclR0gKnoEP83ahMJOpCIjuknPZhb+HsiNjFWf+Os9U6kaS5vGrbXC8nggrVE57ow88pLCBL+3mBk1vBg6bJuLBCp2WTqRzDMhSDQ3AcWqkucGqf dremy@remthinkpad",
},
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsCosmosDbLogicApp(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping Azure tests temporarily")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-cosmosdb-logicapp"),
})
integration.ProgramTest(t, &test)
}
func TestAccAzureTsWebserverComponent(t *testing.T) {
t.Skip("Skipping Azure tests temporarily")
test := getAzureBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "azure-ts-webserver-component"),
Config: map[string]string{
"username": "webmaster",
"password": "MySuperS3cretPassw0rd",
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudJsApi(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-js-api"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpoint"].(string)+"/hello", nil, func(body string) bool {
return assert.Contains(t, body, "{\"route\":\"hello\",\"count\":1}")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudJsContainers(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-js-containers"),
Config: map[string]string{
"cloud-aws:useFargate": "true",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["hostname"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello, Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudJsHttpServer(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-js-httpserver"),
Config: map[string]string{
"cloud:provider": "aws",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpoint"].(string)+"/hello", nil, func(body string) bool {
return assert.Contains(t, body, "{\"route\":\"/hello\",\"count\":1}")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudJsThumbnailer(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-js-thumbnailer"),
Config: map[string]string{
"cloud-aws:useFargate": "true",
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudJsThumbnailerMachineLearning(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-js-thumbnailer-machine-learning"),
Config: map[string]string{
// use us-west-2 to assure fargate
"cloud-aws:useFargate": "true",
"cloud-aws:computeIAMRolePolicyARNs": "arn:aws:iam::aws:policy/AWSLambdaFullAccess,arn:aws:iam::aws:" +
"policy/AmazonEC2ContainerServiceFullAccess,arn:aws:iam::aws:policy/AmazonRekognitionFullAccess",
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudTsUrlShortener(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-ts-url-shortener"),
Config: map[string]string{
// use us-west-2 to assure fargate
"redisPassword": "s3cr7Password",
"cloud:provider": "aws",
"cloud-aws:useFargate": "true",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpointUrl"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Short URL Manager")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudTsUrlShortenerCache(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-ts-url-shortener-cache"),
Config: map[string]string{
// use us-west-2 to assure fargate
"redisPassword": "s3cr7Password",
"cloud:provider": "aws",
"cloud-aws:useFargate": "true",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpointUrl"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Short URL Manager")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccCloudTsVotingApp(t *testing.T) {
test := getCloudBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "cloud-ts-voting-app"),
Config: map[string]string{
// use us-west-2 to assure fargate
"redisPassword": "s3cr7Password",
"cloud:provider": "aws",
"cloud-aws:useFargate": "true",
},
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["frontendURL"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Pulumi Voting App")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanPyK8s(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-py-k8s"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["ingress_ip"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanPyLoadbalancedDroplets(t *testing.T) {
t.Skip("Skip due to 'Error waiting for Load Balancer' failures")
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-py-loadbalanced-droplets"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpoint"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanTsK8s(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-ts-k8s"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["ingressIp"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanTsLoadbalancedDroplets(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-ts-loadbalanced-droplets"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["endpoint"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanCsK8s(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-cs-k8s"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["IngressIp"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccDigitalOceanCsLoadbalancedDroplets(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "digitalocean-cs-loadbalanced-droplets"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
assertHTTPResult(t, stack.Outputs["Endpoint"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Welcome to nginx!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccLinodeJsWebserver(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "linode-js-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["instanceIP"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello, World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpGoFunctions(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-go-functions"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["function"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpGoFunctionsRaw(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-go-functions-raw"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["function"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpGoGke(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-go-gke"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["url"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello Kubernetes bootcamp!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpGoInstance(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-go-instance"),
})
integration.ProgramTest(t, &test)
}
func TestAccGcpJsWebserver(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-js-webserver"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["instanceIP"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello, World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpPyFunctions(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-py-functions"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["fxn_url"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Space Needle, Seattle, WA")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpPyServerlessRaw(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-py-serverless-raw"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["go_endpoint"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
assertHTTPResult(t, stack.Outputs["python_endpoint"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpPyInstanceNginx(t *testing.T) {
t.Skip("Skip due to frequent failures: `35.239.87.214:80: connect: connection refused`")
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-py-instance-nginx"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["external_ip"].(string)
maxWait := time.Minute * 10
assertHTTPResultWithRetry(t, endpoint, nil, maxWait, func(body string) bool {
return assert.Contains(t, body, "Test Page for the Nginx HTTP Server on Fedora")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpTsFunctions(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-ts-functions"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["url"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Greetings from Google Cloud Functions!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpTsServerlessRaw(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-ts-serverless-raw"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["goEndpoint"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
assertHTTPResult(t, stack.Outputs["pythonEndpoint"].(string), nil, func(body string) bool {
return assert.Contains(t, body, "Hello World!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccGcpTsCloudRun(t *testing.T) {
test := getGoogleBase(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "gcp-ts-cloudrun"),
RunUpdateTest: false,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["rubyUrl"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Hello Pulumi!")
})
},
})
integration.ProgramTest(t, &test)
}
func TestAccPacketPyWebserver(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "packet-py-webserver"),
})
integration.ProgramTest(t, &test)
}
func TestAccPacketTsWebserver(t *testing.T) {
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "packet-ts-webserver"),
})
integration.ProgramTest(t, &test)
}
func TestAccKubernetesGuestbook(t *testing.T) {
_, err := homedir.Expand("~/.kube/config")
if err != nil {
t.Skipf("Missing KubeConfig to run test: %s", err)
}
tests := []integration.ProgramTestOptions{
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-go-guestbook", "simple"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["frontendIP"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-go-guestbook", "components"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["frontendIP"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-cs-guestbook", "simple"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["FrontendIp"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-cs-guestbook", "components"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["FrontendIp"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-py-guestbook", "simple"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["frontend_ip"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-ts-guestbook", "simple"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["frontendIp"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
integration.ProgramTestOptions{
Dir: path.Join(getCwd(t), "..", "..", "kubernetes-ts-guestbook", "components"),
NoParallel: true,
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
endpoint := stack.Outputs["frontendIp"].(string)
assertHTTPResult(t, endpoint, nil, func(body string) bool {
return assert.Contains(t, body, "Guestbook")
})
},
},
}
for _, ex := range tests {
example := ex
t.Run(example.Dir, func(t *testing.T) {
t.Log(example.StackName)
integration.ProgramTest(t, &example)
})
}
}
func skipIfShort(t *testing.T) {
if testing.Short() {
t.Skip("skipping long-running test in short mode")
}
}
func getAwsRegion() string {
awsRegion := os.Getenv("AWS_REGION")
if awsRegion == "" {
awsRegion = "us-west-1"
fmt.Println("Defaulting AWS_REGION to 'us-west-1'. You can override using the AWS_REGION environment variable")
}
return awsRegion
}
func getAzureEnvironment() string {
azureEnviron := os.Getenv("ARM_ENVIRONMENT")
if azureEnviron == "" {
azureEnviron = "public"
fmt.Println("Defaulting ARM_ENVIRONMENT to 'public'. You can override using the ARM_ENVIRONMENT variable")
}
return azureEnviron
}
func getAzureLocation() string {
azureLocation := os.Getenv("ARM_LOCATION")
if azureLocation == "" {
azureLocation = "westus"
fmt.Println("Defaulting ARM_LOCATION to 'westus'. You can override using the ARM_LOCATION variable")
}
return azureLocation
}
func getGoogleProject() string {
project := os.Getenv("GOOGLE_PROJECT")
if project == "" {
project = "pulumi-ci-gcp-provider"
fmt.Println("Defaulting GOOGLE_PROJECT to 'pulumi-ci-gcp-provider'. You can override using the GOOGLE_PROJECT variable")
}
return project
}
func getGoogleZone() string {
zone := os.Getenv("GOOGLE_ZONE")
if zone == "" {
zone = "us-central1-a"
fmt.Println("Defaulting GOOGLE_ZONE to 'us-central1-a'. You can override using the GOOGLE_ZONE variable")
}
return zone
}
func getGkeVersion() string {
gkeEngineVersion := os.Getenv("GKE_ENGINE_VERSION")
if gkeEngineVersion == "" {
gkeEngineVersion = "1.13.7-gke.24"
fmt.Println("Defaulting GKE_ENGINE_VERSION to '1.13.7-gke.24'. You can override using the GKE_ENGINE_VERSION variable")
}
return gkeEngineVersion
}
func getCwd(t *testing.T) string {
cwd, err := os.Getwd()
if err != nil {
t.FailNow()
}
return cwd
}
func getBaseOptions(t *testing.T) integration.ProgramTestOptions {
overrides, err := integration.DecodeMapString(os.Getenv("PULUMI_TEST_NODE_OVERRIDES"))
if err != nil {
t.FailNow()
}
base := integration.ProgramTestOptions{
Tracing: "https://tracing.pulumi-engineering.com/collector/api/v1/spans",
ExpectRefreshChanges: true,
Overrides: overrides,
Quick: true,
SkipRefresh: true,
RetryFailedSteps: true,
}
return base
}
func getAWSBase(t *testing.T) integration.ProgramTestOptions {
awsRegion := getAwsRegion()
base := getBaseOptions(t)
awsBase := base.With(integration.ProgramTestOptions{
Config: map[string]string{
"aws:region": awsRegion,
},
})
return awsBase
}
func getAzureBase(t *testing.T) integration.ProgramTestOptions {
azureEnviron := getAzureEnvironment()
azureLocation := getAzureLocation()
base := getBaseOptions(t)
azureBase := base.With(integration.ProgramTestOptions{
Config: map[string]string{
"azure:environment": azureEnviron,
"azure:location": azureLocation,
},
})
return azureBase
}
func getGoogleBase(t *testing.T) integration.ProgramTestOptions {
googleZone := getGoogleZone()
googleProject := getGoogleProject()
base := getBaseOptions(t)
gkeBase := base.With(integration.ProgramTestOptions{
Config: map[string]string{
"gcp:project": googleProject,
"gcp:zone": googleZone,
},
})
return gkeBase
}
func getCloudBase(t *testing.T) integration.ProgramTestOptions {
awsRegion := getAwsRegion()
base := getBaseOptions(t)
azureBase := base.With(integration.ProgramTestOptions{
Config: map[string]string{
"aws:region": awsRegion,
},
})
return azureBase
}
func assertHTTPResult(t *testing.T, output interface{}, headers map[string]string, check func(string) bool) bool {
return assertHTTPResultWithRetry(t, output, headers, 5*time.Minute, check)
}
func assertHTTPResultWithRetry(t *testing.T, output interface{}, headers map[string]string, maxWait time.Duration, check func(string) bool) bool {
return assertHTTPResultShapeWithRetry(t, output, headers, maxWait, func(string) bool { return true }, check)
}
func assertAppServiceResult(t *testing.T, output interface{}, check func(string) bool) bool {
ready := func(body string) bool {
// We got a welcome page from Azure App Service. This means the resource is deployed but our custom code is not
// there yet. Wait a bit more and retry later.
welcomePage := strings.Contains(body, "Your app service is up and running.")
return !welcomePage
}
return assertHTTPResultShapeWithRetry(t, output, nil, 5*time.Minute, ready, check)
}
func assertHTTPResultShapeWithRetry(t *testing.T, output interface{}, headers map[string]string, maxWait time.Duration,
ready func(string) bool, check func(string) bool) bool {
hostname, ok := output.(string)
if !assert.True(t, ok, fmt.Sprintf("expected `%s` output", output)) {
return false
}
if !(strings.HasPrefix(hostname, "http://") || strings.HasPrefix(hostname, "https://")) {
hostname = fmt.Sprintf("http://%s", hostname)
}
startTime := time.Now()
count, sleep := 0, 0
for true {
now := time.Now()
req, err := http.NewRequest("GET", hostname, nil)
if !assert.NoError(t, err) {
return false
}
for k, v := range headers {
// Host header cannot be set via req.Header.Set(), and must be set
// directly.
if strings.ToLower(k) == "host" {
req.Host = v
continue
}
req.Header.Set(k, v)
}
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err == nil && resp.StatusCode == 200 {
if !assert.NotNil(t, resp.Body, "resp.body was nil") {
return false
}
// Read the body
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if !assert.NoError(t, err) {
return false
}
bodyText := string(body)
// Even if we got 200 and a response, it may not be ready for assertion yet - that's specific per test.
if ready(bodyText) {
// Verify it matches expectations
return check(bodyText)
}
}
if now.Sub(startTime) >= maxWait {
fmt.Printf("Timeout after %v. Unable to http.get %v successfully.", maxWait, hostname)
return false
}
count++
// delay 10s, 20s, then 30s and stay at 30s
if sleep > 30 {
sleep = 30
} else {
sleep += 10
}
time.Sleep(time.Duration(sleep) * time.Second)
fmt.Printf("Http Error: %v\n", err)
fmt.Printf(" Retry: %v, elapsed wait: %v, max wait %v\n", count, now.Sub(startTime), maxWait)
}
return false
}
func assertHTTPHelloWorld(t *testing.T, output interface{}, headers map[string]string) bool {
return assertHTTPResult(t, output, headers, func(s string) bool {
return assert.Equal(t, "Hello, World!\n", s)
})
}
|
[
"\"AWS_REGION\"",
"\"ARM_ENVIRONMENT\"",
"\"ARM_LOCATION\"",
"\"GOOGLE_PROJECT\"",
"\"GOOGLE_ZONE\"",
"\"GKE_ENGINE_VERSION\"",
"\"PULUMI_TEST_NODE_OVERRIDES\""
] |
[] |
[
"GKE_ENGINE_VERSION",
"GOOGLE_ZONE",
"AWS_REGION",
"GOOGLE_PROJECT",
"ARM_ENVIRONMENT",
"PULUMI_TEST_NODE_OVERRIDES",
"ARM_LOCATION"
] |
[]
|
["GKE_ENGINE_VERSION", "GOOGLE_ZONE", "AWS_REGION", "GOOGLE_PROJECT", "ARM_ENVIRONMENT", "PULUMI_TEST_NODE_OVERRIDES", "ARM_LOCATION"]
|
go
| 7 | 0 | |
tests/testutils/repo/bzr.py
|
import os
import subprocess
import pytest
from buildstream._testing import Repo
from buildstream._testing._utils.site import BZR, BZR_ENV, HAVE_BZR
class Bzr(Repo):
def __init__(self, directory, subdir="repo"):
if not HAVE_BZR:
pytest.skip("bzr is not available")
super().__init__(directory, subdir)
self.bzr = BZR
self.env = os.environ.copy()
self.env.update(BZR_ENV)
def create(self, directory):
# Work around race condition in bzr's creation of ~/.bazaar in
# ensure_config_dir_exists() when running tests in parallel.
bazaar_config_dir = os.path.expanduser("~/.bazaar")
os.makedirs(bazaar_config_dir, exist_ok=True)
branch_dir = os.path.join(self.repo, "trunk")
subprocess.call([self.bzr, "init-repo", self.repo], env=self.env)
subprocess.call([self.bzr, "init", branch_dir], env=self.env)
self.copy_directory(directory, branch_dir)
subprocess.call([self.bzr, "add", "."], env=self.env, cwd=branch_dir)
subprocess.call([self.bzr, "commit", '--message="Initial commit"'], env=self.env, cwd=branch_dir)
return self.latest_commit()
def source_config(self, ref=None):
config = {"kind": "bzr", "url": "file://" + self.repo, "track": "trunk"}
if ref is not None:
config["ref"] = ref
return config
def latest_commit(self):
return subprocess.check_output(
[self.bzr, "version-info", "--custom", "--template={revno}", os.path.join(self.repo, "trunk")],
env=self.env,
universal_newlines=True,
).strip()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
traffic_ops/ort/atstccfg/config/config.go
|
package config
/*
* 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 (
"errors"
"fmt"
"math"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/apache/trafficcontrol/lib/go-log"
toclient "github.com/apache/trafficcontrol/traffic_ops/client"
flag "github.com/ogier/pflag"
)
const AppName = "atstccfg"
const Version = "0.1"
const UserAgent = AppName + "/" + Version
const APIVersion = "1.2"
const TempSubdir = AppName + "_cache"
const TempCookieFileName = "cookies"
const TOCookieName = "mojolicious"
const GlobalProfileName = "GLOBAL"
const ExitCodeSuccess = 0
const ExitCodeErrGeneric = 1
const ExitCodeNotFound = 104
const ExitCodeBadRequest = 100
var ErrNotFound = errors.New("not found")
var ErrBadRequest = errors.New("bad request")
type Cfg struct {
CacheFileMaxAge time.Duration
LogLocationErr string
LogLocationInfo string
LogLocationWarn string
NumRetries int
TempDir string
TOInsecure bool
TOPass string
TOTimeout time.Duration
TOURL *url.URL
TOUser string
ListPlugins bool
PrintGeneratedFiles bool
}
type TCCfg struct {
Cfg
TOClient **toclient.Session
}
func (cfg Cfg) ErrorLog() log.LogLocation { return log.LogLocation(cfg.LogLocationErr) }
func (cfg Cfg) WarningLog() log.LogLocation { return log.LogLocation(cfg.LogLocationWarn) }
func (cfg Cfg) InfoLog() log.LogLocation { return log.LogLocation(cfg.LogLocationInfo) }
func (cfg Cfg) DebugLog() log.LogLocation { return log.LogLocation(log.LogLocationNull) } // atstccfg doesn't use the debug logger, use Info instead.
func (cfg Cfg) EventLog() log.LogLocation { return log.LogLocation(log.LogLocationNull) } // atstccfg doesn't use the event logger.
// GetCfg gets the application configuration, from arguments and environment variables.
// Note if PrintGeneratedFiles is configured, the config will be returned with PrintGeneratedFiles true and all other values set to their defaults. This is because other values may have requirements and return errors, where if PrintGeneratedFiles is set by the user, no other setting should be considered.
func GetCfg() (Cfg, error) {
toURLPtr := flag.StringP("traffic-ops-url", "u", "", "Traffic Ops URL. Must be the full URL, including the scheme. Required. May also be set with the environment variable TO_URL.")
toUserPtr := flag.StringP("traffic-ops-user", "U", "", "Traffic Ops username. Required. May also be set with the environment variable TO_USER.")
toPassPtr := flag.StringP("traffic-ops-password", "P", "", "Traffic Ops password. Required. May also be set with the environment variable TO_PASS.")
noCachePtr := flag.BoolP("no-cache", "n", false, "Whether not to use existing cache files. Optional. Cache files will still be created, existing ones just won't be used.")
numRetriesPtr := flag.IntP("num-retries", "r", 5, "The number of times to retry getting a file if it fails.")
logLocationErrPtr := flag.StringP("log-location-error", "e", "stderr", "Where to log errors. May be a file path, stdout, stderr, or null.")
logLocationWarnPtr := flag.StringP("log-location-warning", "w", "stderr", "Where to log warnings. May be a file path, stdout, stderr, or null.")
logLocationInfoPtr := flag.StringP("log-location-info", "i", "stderr", "Where to log information messages. May be a file path, stdout, stderr, or null.")
printGeneratedFilesPtr := flag.BoolP("print-generated-files", "g", false, "Whether to print a list of files which are generated (and not proxied to Traffic Ops).")
toInsecurePtr := flag.BoolP("traffic-ops-insecure", "s", false, "Whether to ignore HTTPS certificate errors from Traffic Ops. It is HIGHLY RECOMMENDED to never use this in a production environment, but only for debugging.")
toTimeoutMSPtr := flag.IntP("traffic-ops-timeout-milliseconds", "t", 10000, "Timeout in seconds for Traffic Ops requests.")
cacheFileMaxAgeSecondsPtr := flag.IntP("cache-file-max-age-seconds", "a", 900, "Maximum age to use cached files.")
versionPtr := flag.BoolP("version", "v", false, "Print version information and exit.")
listPluginsPtr := flag.BoolP("list-plugins", "l", false, "Print the list of plugins.")
helpPtr := flag.BoolP("help", "h", false, "Print usage information and exit")
flag.Parse()
if *versionPtr {
fmt.Println(AppName + " v" + Version)
os.Exit(0)
} else if *helpPtr {
flag.PrintDefaults()
os.Exit(0)
} else if *printGeneratedFilesPtr {
return Cfg{PrintGeneratedFiles: true}, nil
} else if *listPluginsPtr {
return Cfg{ListPlugins: true}, nil
}
toURL := *toURLPtr
toUser := *toUserPtr
toPass := *toPassPtr
noCache := *noCachePtr
numRetries := *numRetriesPtr
logLocationErr := *logLocationErrPtr
logLocationWarn := *logLocationWarnPtr
logLocationInfo := *logLocationInfoPtr
toInsecure := *toInsecurePtr
toTimeout := time.Millisecond * time.Duration(*toTimeoutMSPtr)
cacheFileMaxAge := time.Second * time.Duration(*cacheFileMaxAgeSecondsPtr)
listPlugins := *listPluginsPtr
urlSourceStr := "argument" // for error messages
if toURL == "" {
urlSourceStr = "environment variable"
toURL = os.Getenv("TO_URL")
}
if toUser == "" {
toUser = os.Getenv("TO_USER")
}
if toPass == "" {
toPass = os.Getenv("TO_PASS")
}
if strings.TrimSpace(toURL) == "" {
return Cfg{}, errors.New("Missing required argument --traffic-ops-url or TO_URL environment variable. Usage: ./" + AppName + " --traffic-ops-url myurl --traffic-ops-user myuser --traffic-ops-password mypass")
}
if strings.TrimSpace(toUser) == "" {
return Cfg{}, errors.New("Missing required argument --traffic-ops-user or TO_USER environment variable. Usage: ./" + AppName + " --traffic-ops-url myurl --traffic-ops-user myuser --traffic-ops-password mypass")
}
if strings.TrimSpace(toPass) == "" {
return Cfg{}, errors.New("Missing required argument --traffic-ops-password or TO_PASS environment variable. Usage: ./" + AppName + " --traffic-ops-url myurl --traffic-ops-user myuser --traffic-ops-password mypass")
}
toURLParsed, err := url.Parse(toURL)
if err != nil {
return Cfg{}, errors.New("parsing Traffic Ops URL from " + urlSourceStr + " '" + toURL + "': " + err.Error())
} else if err := ValidateURL(toURLParsed); err != nil {
return Cfg{}, errors.New("invalid Traffic Ops URL from " + urlSourceStr + " '" + toURL + "': " + err.Error())
}
tmpDir := os.TempDir()
tmpDir = filepath.Join(tmpDir, TempSubdir)
cfg := Cfg{
CacheFileMaxAge: cacheFileMaxAge,
LogLocationErr: logLocationErr,
LogLocationWarn: logLocationWarn,
LogLocationInfo: logLocationInfo,
NumRetries: numRetries,
TempDir: tmpDir,
TOInsecure: toInsecure,
TOPass: toPass,
TOTimeout: toTimeout,
TOURL: toURLParsed,
TOUser: toUser,
ListPlugins: listPlugins,
}
if err := log.InitCfg(cfg); err != nil {
return Cfg{}, errors.New("Initializing loggers: " + err.Error() + "\n")
}
if noCache {
if err := os.RemoveAll(tmpDir); err != nil {
log.Errorln("deleting cache directory '" + tmpDir + "': " + err.Error())
}
}
if err := os.MkdirAll(tmpDir, 0700); err != nil {
return Cfg{}, errors.New("creating temp directory '" + tmpDir + "': " + err.Error())
}
if err := ValidateDirWriteable(tmpDir); err != nil {
return Cfg{}, errors.New("validating temp directory is writeable '" + tmpDir + "': " + err.Error())
}
return cfg, nil
}
func ValidateURL(u *url.URL) error {
if u == nil {
return errors.New("nil url")
}
if u.Scheme != "http" && u.Scheme != "https" {
return errors.New("scheme expected 'http' or 'https', actual '" + u.Scheme + "'")
}
if strings.TrimSpace(u.Host) == "" {
return errors.New("no host")
}
return nil
}
func ValidateDirWriteable(dir string) error {
testFileName := "testwrite.txt"
testFilePath := filepath.Join(dir, testFileName)
if err := os.RemoveAll(testFilePath); err != nil {
// TODO don't log? This can be normal
log.Infoln("error removing temp test file '" + testFilePath + "' (ok if it didn't exist): " + err.Error())
}
fl, err := os.Create(testFilePath)
if err != nil {
return errors.New("creating temp test file '" + testFilePath + "': " + err.Error())
}
defer fl.Close()
if _, err := fl.WriteString("test"); err != nil {
return errors.New("writing to temp test file '" + testFilePath + "': " + err.Error())
}
return nil
}
func RetryBackoffSeconds(currentRetry int) int {
// TODO make configurable?
return int(math.Pow(2.0, float64(currentRetry)))
}
|
[
"\"TO_URL\"",
"\"TO_USER\"",
"\"TO_PASS\""
] |
[] |
[
"TO_URL",
"TO_PASS",
"TO_USER"
] |
[]
|
["TO_URL", "TO_PASS", "TO_USER"]
|
go
| 3 | 0 | |
src/cmd/go/internal/work/gccgo.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package work
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/str"
)
// The Gccgo toolchain.
type gccgoToolchain struct{}
var GccgoName, GccgoBin string
var gccgoErr error
func init() {
GccgoName = os.Getenv("GCCGO")
if GccgoName == "" {
GccgoName = "gccgo"
}
GccgoBin, gccgoErr = exec.LookPath(GccgoName)
}
func (gccgoToolchain) compiler() string {
checkGccgoBin()
return GccgoBin
}
func (gccgoToolchain) linker() string {
checkGccgoBin()
return GccgoBin
}
func checkGccgoBin() {
if gccgoErr == nil {
return
}
fmt.Fprintf(os.Stderr, "cmd/go: gccgo: %s\n", gccgoErr)
os.Exit(2)
}
func (tools gccgoToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, output []byte, err error) {
p := a.Package
objdir := a.Objdir
out := "_go_.o"
ofile = objdir + out
gcargs := []string{"-g"}
gcargs = append(gcargs, b.gccArchArgs()...)
if pkgpath := gccgoPkgpath(p); pkgpath != "" {
gcargs = append(gcargs, "-fgo-pkgpath="+pkgpath)
}
if p.Internal.LocalPrefix != "" {
gcargs = append(gcargs, "-fgo-relative-import-path="+p.Internal.LocalPrefix)
}
args := str.StringList(tools.compiler(), "-c", gcargs, "-o", ofile, forcedGccgoflags)
if importcfg != nil {
if b.gccSupportsFlag(args[:1], "-fgo-importcfg=/dev/null") {
if err := b.writeFile(objdir+"importcfg", importcfg); err != nil {
return "", nil, err
}
args = append(args, "-fgo-importcfg="+objdir+"importcfg")
} else {
root := objdir + "_importcfgroot_"
if err := buildImportcfgSymlinks(b, root, importcfg); err != nil {
return "", nil, err
}
args = append(args, "-I", root)
}
}
args = append(args, a.Package.Internal.Gccgoflags...)
for _, f := range gofiles {
args = append(args, mkAbs(p.Dir, f))
}
output, err = b.runOut(p.Dir, nil, args)
return ofile, output, err
}
// buildImportcfgSymlinks builds in root a tree of symlinks
// implementing the directives from importcfg.
// This serves as a temporary transition mechanism until
// we can depend on gccgo reading an importcfg directly.
// (The Go 1.9 and later gc compilers already do.)
func buildImportcfgSymlinks(b *Builder, root string, importcfg []byte) error {
for lineNum, line := range strings.Split(string(importcfg), "\n") {
lineNum++ // 1-based
line = strings.TrimSpace(line)
if line == "" {
continue
}
if line == "" || strings.HasPrefix(line, "#") {
continue
}
var verb, args string
if i := strings.Index(line, " "); i < 0 {
verb = line
} else {
verb, args = line[:i], strings.TrimSpace(line[i+1:])
}
var before, after string
if i := strings.Index(args, "="); i >= 0 {
before, after = args[:i], args[i+1:]
}
switch verb {
default:
base.Fatalf("importcfg:%d: unknown directive %q", lineNum, verb)
case "packagefile":
if before == "" || after == "" {
return fmt.Errorf(`importcfg:%d: invalid packagefile: syntax is "packagefile path=filename": %s`, lineNum, line)
}
archive := gccgoArchive(root, before)
if err := b.Mkdir(filepath.Dir(archive)); err != nil {
return err
}
if err := b.Symlink(after, archive); err != nil {
return err
}
case "importmap":
if before == "" || after == "" {
return fmt.Errorf(`importcfg:%d: invalid importmap: syntax is "importmap old=new": %s`, lineNum, line)
}
beforeA := gccgoArchive(root, before)
afterA := gccgoArchive(root, after)
if err := b.Mkdir(filepath.Dir(beforeA)); err != nil {
return err
}
if err := b.Mkdir(filepath.Dir(afterA)); err != nil {
return err
}
if err := b.Symlink(afterA, beforeA); err != nil {
return err
}
case "packageshlib":
return fmt.Errorf("gccgo -importcfg does not support shared libraries")
}
}
return nil
}
func (tools gccgoToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
p := a.Package
var ofiles []string
for _, sfile := range sfiles {
base := filepath.Base(sfile)
ofile := a.Objdir + base[:len(base)-len(".s")] + ".o"
ofiles = append(ofiles, ofile)
sfile = mkAbs(p.Dir, sfile)
defs := []string{"-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch}
if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" {
defs = append(defs, `-D`, `GOPKGPATH=`+pkgpath)
}
defs = tools.maybePIC(defs)
defs = append(defs, b.gccArchArgs()...)
err := b.run(a, p.Dir, p.ImportPath, nil, tools.compiler(), "-xassembler-with-cpp", "-I", a.Objdir, "-c", "-o", ofile, defs, sfile)
if err != nil {
return nil, err
}
}
return ofiles, nil
}
func gccgoArchive(basedir, imp string) string {
end := filepath.FromSlash(imp + ".a")
afile := filepath.Join(basedir, end)
// add "lib" to the final element
return filepath.Join(filepath.Dir(afile), "lib"+filepath.Base(afile))
}
func (gccgoToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
p := a.Package
objdir := a.Objdir
var absOfiles []string
for _, f := range ofiles {
absOfiles = append(absOfiles, mkAbs(objdir, f))
}
return b.run(a, p.Dir, p.ImportPath, nil, "ar", "rc", mkAbs(objdir, afile), absOfiles)
}
func (tools gccgoToolchain) link(b *Builder, root *Action, out, importcfg string, allactions []*Action, buildmode, desc string) error {
// gccgo needs explicit linking with all package dependencies,
// and all LDFLAGS from cgo dependencies.
afiles := []string{}
shlibs := []string{}
ldflags := b.gccArchArgs()
cgoldflags := []string{}
usesCgo := false
cxx := false
objc := false
fortran := false
if root.Package != nil {
cxx = len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0
objc = len(root.Package.MFiles) > 0
fortran = len(root.Package.FFiles) > 0
}
readCgoFlags := func(flagsFile string) error {
flags, err := ioutil.ReadFile(flagsFile)
if err != nil {
return err
}
const ldflagsPrefix = "_CGO_LDFLAGS="
for _, line := range strings.Split(string(flags), "\n") {
if strings.HasPrefix(line, ldflagsPrefix) {
newFlags := strings.Fields(line[len(ldflagsPrefix):])
for _, flag := range newFlags {
// Every _cgo_flags file has -g and -O2 in _CGO_LDFLAGS
// but they don't mean anything to the linker so filter
// them out.
if flag != "-g" && !strings.HasPrefix(flag, "-O") {
cgoldflags = append(cgoldflags, flag)
}
}
}
}
return nil
}
newID := 0
readAndRemoveCgoFlags := func(archive string) (string, error) {
newID++
newArchive := root.Objdir + fmt.Sprintf("_pkg%d_.a", newID)
if err := b.copyFile(newArchive, archive, 0666, false); err != nil {
return "", err
}
if cfg.BuildN || cfg.BuildX {
b.Showcmd("", "ar d %s _cgo_flags", newArchive)
if cfg.BuildN {
// TODO(rsc): We could do better about showing the right _cgo_flags even in -n mode.
// Either the archive is already built and we can read them out,
// or we're printing commands to build the archive and can
// forward the _cgo_flags directly to this step.
return "", nil
}
}
err := b.run(root, root.Objdir, desc, nil, "ar", "x", newArchive, "_cgo_flags")
if err != nil {
return "", err
}
err = b.run(root, ".", desc, nil, "ar", "d", newArchive, "_cgo_flags")
if err != nil {
return "", err
}
err = readCgoFlags(filepath.Join(root.Objdir, "_cgo_flags"))
if err != nil {
return "", err
}
return newArchive, nil
}
// If using -linkshared, find the shared library deps.
haveShlib := make(map[string]bool)
targetBase := filepath.Base(root.Target)
if cfg.BuildLinkshared {
for _, a := range root.Deps {
p := a.Package
if p == nil || p.Shlib == "" {
continue
}
// The .a we are linking into this .so
// will have its Shlib set to this .so.
// Don't start thinking we want to link
// this .so into itself.
base := filepath.Base(p.Shlib)
if base != targetBase {
haveShlib[base] = true
}
}
}
// Arrange the deps into afiles and shlibs.
addedShlib := make(map[string]bool)
for _, a := range root.Deps {
p := a.Package
if p != nil && p.Shlib != "" && haveShlib[filepath.Base(p.Shlib)] {
// This is a package linked into a shared
// library that we will put into shlibs.
continue
}
if haveShlib[filepath.Base(a.Target)] {
// This is a shared library we want to link againt.
if !addedShlib[a.Target] {
shlibs = append(shlibs, a.Target)
addedShlib[a.Target] = true
}
continue
}
if p != nil {
target := a.built
if p.UsesCgo() || p.UsesSwig() {
var err error
target, err = readAndRemoveCgoFlags(target)
if err != nil {
continue
}
}
afiles = append(afiles, target)
}
}
for _, a := range allactions {
// Gather CgoLDFLAGS, but not from standard packages.
// The go tool can dig up runtime/cgo from GOROOT and
// think that it should use its CgoLDFLAGS, but gccgo
// doesn't use runtime/cgo.
if a.Package == nil {
continue
}
if !a.Package.Standard {
cgoldflags = append(cgoldflags, a.Package.CgoLDFLAGS...)
}
if len(a.Package.CgoFiles) > 0 {
usesCgo = true
}
if a.Package.UsesSwig() {
usesCgo = true
}
if len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0 {
cxx = true
}
if len(a.Package.MFiles) > 0 {
objc = true
}
if len(a.Package.FFiles) > 0 {
fortran = true
}
}
ldflags = append(ldflags, "-Wl,--whole-archive")
ldflags = append(ldflags, afiles...)
ldflags = append(ldflags, "-Wl,--no-whole-archive")
ldflags = append(ldflags, cgoldflags...)
ldflags = append(ldflags, envList("CGO_LDFLAGS", "")...)
if root.Package != nil {
ldflags = append(ldflags, root.Package.CgoLDFLAGS...)
}
ldflags = str.StringList("-Wl,-(", ldflags, "-Wl,-)")
if root.buildID != "" {
// On systems that normally use gold or the GNU linker,
// use the --build-id option to write a GNU build ID note.
switch cfg.Goos {
case "android", "dragonfly", "linux", "netbsd":
ldflags = append(ldflags, fmt.Sprintf("-Wl,--build-id=0x%x", root.buildID))
}
}
for _, shlib := range shlibs {
ldflags = append(
ldflags,
"-L"+filepath.Dir(shlib),
"-Wl,-rpath="+filepath.Dir(shlib),
"-l"+strings.TrimSuffix(
strings.TrimPrefix(filepath.Base(shlib), "lib"),
".so"))
}
var realOut string
switch buildmode {
case "exe":
if usesCgo && cfg.Goos == "linux" {
ldflags = append(ldflags, "-Wl,-E")
}
case "c-archive":
// Link the Go files into a single .o, and also link
// in -lgolibbegin.
//
// We need to use --whole-archive with -lgolibbegin
// because it doesn't define any symbols that will
// cause the contents to be pulled in; it's just
// initialization code.
//
// The user remains responsible for linking against
// -lgo -lpthread -lm in the final link. We can't use
// -r to pick them up because we can't combine
// split-stack and non-split-stack code in a single -r
// link, and libgo picks up non-split-stack code from
// libffi.
ldflags = append(ldflags, "-Wl,-r", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive")
if nopie := b.gccNoPie([]string{tools.linker()}); nopie != "" {
ldflags = append(ldflags, nopie)
}
// We are creating an object file, so we don't want a build ID.
if root.buildID == "" {
ldflags = b.disableBuildID(ldflags)
}
realOut = out
out = out + ".o"
case "c-shared":
ldflags = append(ldflags, "-shared", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive", "-lgo", "-lgcc_s", "-lgcc", "-lc", "-lgcc")
case "shared":
ldflags = append(ldflags, "-zdefs", "-shared", "-nostdlib", "-lgo", "-lgcc_s", "-lgcc", "-lc")
default:
base.Fatalf("-buildmode=%s not supported for gccgo", buildmode)
}
switch buildmode {
case "exe", "c-shared":
if cxx {
ldflags = append(ldflags, "-lstdc++")
}
if objc {
ldflags = append(ldflags, "-lobjc")
}
if fortran {
fc := os.Getenv("FC")
if fc == "" {
fc = "gfortran"
}
// support gfortran out of the box and let others pass the correct link options
// via CGO_LDFLAGS
if strings.Contains(fc, "gfortran") {
ldflags = append(ldflags, "-lgfortran")
}
}
}
if err := b.run(root, ".", desc, nil, tools.linker(), "-o", out, ldflags, forcedGccgoflags, root.Package.Internal.Gccgoflags); err != nil {
return err
}
switch buildmode {
case "c-archive":
if err := b.run(root, ".", desc, nil, "ar", "rc", realOut, out); err != nil {
return err
}
}
return nil
}
func (tools gccgoToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error {
return tools.link(b, root, out, importcfg, root.Deps, ldBuildmode, root.Package.ImportPath)
}
func (tools gccgoToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error {
return tools.link(b, root, out, importcfg, allactions, "shared", out)
}
func (tools gccgoToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
p := a.Package
inc := filepath.Join(cfg.GOROOT, "pkg", "include")
cfile = mkAbs(p.Dir, cfile)
defs := []string{"-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch}
defs = append(defs, b.gccArchArgs()...)
if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" {
defs = append(defs, `-D`, `GOPKGPATH="`+pkgpath+`"`)
}
switch cfg.Goarch {
case "386", "amd64":
defs = append(defs, "-fsplit-stack")
}
defs = tools.maybePIC(defs)
return b.run(a, p.Dir, p.ImportPath, nil, envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)), "-Wall", "-g",
"-I", a.Objdir, "-I", inc, "-o", ofile, defs, "-c", cfile)
}
// maybePIC adds -fPIC to the list of arguments if needed.
func (tools gccgoToolchain) maybePIC(args []string) []string {
switch cfg.BuildBuildmode {
case "c-shared", "shared", "plugin":
args = append(args, "-fPIC")
}
return args
}
func gccgoPkgpath(p *load.Package) string {
if p.Internal.Build.IsCommand() && !p.Internal.ForceLibrary {
return ""
}
return p.ImportPath
}
func gccgoCleanPkgpath(p *load.Package) string {
clean := func(r rune) rune {
switch {
case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
'0' <= r && r <= '9':
return r
}
return '_'
}
return strings.Map(clean, gccgoPkgpath(p))
}
|
[
"\"GCCGO\"",
"\"FC\""
] |
[] |
[
"FC",
"GCCGO"
] |
[]
|
["FC", "GCCGO"]
|
go
| 2 | 0 | |
metadata_service/__init__.py
|
import ast
import importlib
import logging
import os
import sys
from typing import Dict, Any # noqa: F401
from flask import Flask, Blueprint
from flask_restful import Api
from metadata_service.api.column import ColumnDescriptionAPI
from metadata_service.api.healthcheck import healthcheck
from metadata_service.api.popular_tables import PopularTablesAPI
from metadata_service.api.system import Neo4jDetailAPI
from metadata_service.api.table \
import TableDetailAPI, TableOwnerAPI, TableTagAPI, TableDescriptionAPI
from metadata_service.api.tag import TagAPI
from metadata_service.api.user import UserDetailAPI, UserFollowAPI, UserOwnAPI, UserReadAPI
# For customized flask use below arguments to override.
FLASK_APP_MODULE_NAME = os.getenv('FLASK_APP_MODULE_NAME')
FLASK_APP_CLASS_NAME = os.getenv('FLASK_APP_CLASS_NAME')
FLASK_APP_KWARGS_DICT_STR = os.getenv('FLASK_APP_KWARGS_DICT')
def create_app(*, config_module_class: str) -> Flask:
"""
Creates app in function so that flask with flask extensions can be
initialized with specific config. Here it defines the route of APIs
so that it can be seen in one place where implementation is separated.
Config is being fetched via module.class name where module.class name
can be passed through environment variable.
This is to make config fetched through runtime PYTHON_PATH so that
Config class can be easily injected.
More on: http://flask.pocoo.org/docs/1.0/config/
:param config_module_class: name of the config (TODO: Implement config.py)
:return: Flask
"""
if FLASK_APP_MODULE_NAME and FLASK_APP_CLASS_NAME:
print('Using requested Flask module {module_name} and class {class_name}'
.format(module_name=FLASK_APP_MODULE_NAME, class_name=FLASK_APP_CLASS_NAME), file=sys.stderr)
class_obj = getattr(importlib.import_module(FLASK_APP_MODULE_NAME), FLASK_APP_CLASS_NAME)
flask_kwargs_dict = {} # type: Dict[str, Any]
if FLASK_APP_KWARGS_DICT_STR:
print('Using kwargs {kwargs} to instantiate Flask'.format(kwargs=FLASK_APP_KWARGS_DICT_STR),
file=sys.stderr)
flask_kwargs_dict = ast.literal_eval(FLASK_APP_KWARGS_DICT_STR)
app = class_obj(__name__, **flask_kwargs_dict)
else:
app = Flask(__name__)
config_module_class = \
os.getenv('METADATA_SVC_CONFIG_MODULE_CLASS') or config_module_class
app.config.from_object(config_module_class)
logging.basicConfig(format=app.config.get('LOG_FORMAT'), datefmt=app.config.get('LOG_DATE_FORMAT'))
logging.getLogger().setLevel(app.config.get('LOG_LEVEL'))
logging.info('Created app with config name {}'.format(config_module_class))
logging.info('Using backend {}'.format(app.config.get('PROXY_CLIENT')))
api_bp = Blueprint('api', __name__)
api_bp.add_url_rule('/healthcheck', 'healthcheck', healthcheck)
api = Api(api_bp)
api.add_resource(PopularTablesAPI, '/popular_tables/')
api.add_resource(TableDetailAPI, '/table/<path:table_uri>')
api.add_resource(TableDescriptionAPI,
'/table/<path:table_uri>/description',
'/table/<path:table_uri>/description/<path:description_val>')
api.add_resource(TableTagAPI,
'/table/<path:table_uri>/tag',
'/table/<path:table_uri>/tag/<tag>')
api.add_resource(TableOwnerAPI,
'/table/<path:table_uri>/owner/<owner>')
api.add_resource(ColumnDescriptionAPI,
'/table/<path:table_uri>/column/<column_name>/description',
'/table/<path:table_uri>/column/<column_name>/description/<path:description_val>')
api.add_resource(Neo4jDetailAPI,
'/latest_updated_ts')
api.add_resource(TagAPI,
'/tags/')
api.add_resource(UserDetailAPI,
'/user/<path:user_id>')
api.add_resource(UserFollowAPI,
'/user/<path:user_id>/follow/',
'/user/<path:user_id>/follow/<resource_type>/<path:table_uri>')
api.add_resource(UserOwnAPI,
'/user/<path:user_id>/own/',
'/user/<path:user_id>/own/<resource_type>/<path:table_uri>')
api.add_resource(UserReadAPI,
'/user/<path:user_id>/read/',
'/user/<path:user_id>/read/<resource_type>/<path:table_uri>')
app.register_blueprint(api_bp)
return app
|
[] |
[] |
[
"FLASK_APP_KWARGS_DICT",
"FLASK_APP_MODULE_NAME",
"METADATA_SVC_CONFIG_MODULE_CLASS",
"FLASK_APP_CLASS_NAME"
] |
[]
|
["FLASK_APP_KWARGS_DICT", "FLASK_APP_MODULE_NAME", "METADATA_SVC_CONFIG_MODULE_CLASS", "FLASK_APP_CLASS_NAME"]
|
python
| 4 | 0 | |
fastai2/launch.py
|
import subprocess, torch
from fastai2.basics import *
from fastscript import *
@call_parse
def main(
gpus:Param("The GPUs to use for distributed training", str)='all',
script:Param("Script to run", str, opt=False)='',
args:Param("Args to pass to script", nargs='...', opt=False)=''
):
"PyTorch distributed training launch helper that spawns multiple distributed processes"
# Loosely based on torch.distributed.launch
current_env = os.environ.copy()
gpus = list(range(torch.cuda.device_count())) if gpus=='all' else list(gpus)
current_env["WORLD_SIZE"] = str(len(gpus))
current_env["MASTER_ADDR"] = '127.0.0.1'
current_env["MASTER_PORT"] = '29500'
processes = []
for i,gpu in enumerate(gpus):
current_env["RANK"] = str(i)
cmd = [sys.executable, "-u", script, f"--gpu={gpu}"] + args
process = subprocess.Popen(cmd, env=current_env)
processes.append(process)
for process in processes: process.wait()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
main.go
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/amine-bambrik-p8/go-lang-web-service/handlers"
)
func createServer() {
handlers.HookHandlers()
port := os.Getenv("PORT")
if port == "" {
port = "8081"
}
//db.InitialMigration()
log.Printf("Server started on localhost:%s\n", port)
log.Print("Press Ctrl+C to Stop it")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func main() {
createServer()
}
|
[
"\"PORT\""
] |
[] |
[
"PORT"
] |
[]
|
["PORT"]
|
go
| 1 | 0 | |
pkg/skaffold/util/cmd_test.go
|
/*
Copyright 2019 The Skaffold 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 util
import (
"context"
"fmt"
"os"
"os/exec"
"testing"
"github.com/GoogleContainerTools/skaffold/testutil"
)
func helperCommand(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
}
// adapted from https://npf.io/2015/06/testing-exec-command
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)
}
cmd, args := args[0], args[1:]
switch cmd {
case "skaffold":
var iargs []interface{}
for _, s := range args {
iargs = append(iargs, s)
}
fmt.Println(iargs...)
default:
fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
os.Exit(2)
}
os.Exit(0)
}
func TestCmd_RunCmdOut(t *testing.T) {
tests := []struct {
description string
cmd *exec.Cmd
want string
shouldErr bool
}{
{
description: "skaffold test",
cmd: helperCommand("skaffold", "dev"),
want: "dev\n",
shouldErr: false,
},
{
description: "unknown command test",
cmd: helperCommand("foo", "bar"),
want: "",
shouldErr: true,
},
}
for _, test := range tests {
testutil.Run(t, test.description, func(t *testutil.T) {
got, err := RunCmdOut(context.Background(), test.cmd)
t.CheckErrorAndDeepEqual(test.shouldErr, err, test.want, string(got))
})
}
}
|
[
"\"GO_WANT_HELPER_PROCESS\""
] |
[] |
[
"GO_WANT_HELPER_PROCESS"
] |
[]
|
["GO_WANT_HELPER_PROCESS"]
|
go
| 1 | 0 | |
conanfile.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
from conans import ConanFile, CMake, tools
class LibwebpConan(ConanFile):
name = "libwebp"
version = "1.0.0"
description = "library to encode and decode images in WebP format"
url = "http://github.com/bincrafters/conan-libwebp"
homepage = "https://github.com/webmproject/libwebp"
author = "Bincrafters <[email protected]>"
license = "BSD 3-Clause"
exports = ["LICENSE.md"]
exports_sources = ['CMakeLists.txt',
'0001-install-pkg-config-files-during-the-CMake-build.patch']
generators = 'cmake'
_source_subfolder = "source_subfolder"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False], "fPIC": [True, False],
"with_simd": [True, False], "near_lossless": [True, False],
"swap_16bit_csp": [True, False]}
default_options = {'shared': False, 'fPIC': True, 'with_simd': True, 'near_lossless': True, 'swap_16bit_csp': False}
def source(self):
source_url = "https://github.com/webmproject/libwebp"
tools.get("{0}/archive/v{1}.tar.gz".format(source_url, self.version))
extracted_dir = self.name + "-" + self.version
os.rename(extracted_dir, self._source_subfolder)
tools.patch(base_path=self._source_subfolder,
patch_file='0001-install-pkg-config-files-during-the-CMake-build.patch')
os.rename(os.path.join(self._source_subfolder, "CMakeLists.txt"),
os.path.join(self._source_subfolder, "CMakeListsOriginal.txt"))
shutil.copy("CMakeLists.txt",
os.path.join(self._source_subfolder, "CMakeLists.txt"))
def configure(self):
del self.settings.compiler.libcxx
def config_options(self):
if self.settings.os == 'Windows':
del self.options.fPIC
@property
def _version_components(self):
return [int(x) for x in self.version.split('.')]
def _configure_cmake(self):
cmake = CMake(self)
# should be an option but it doesn't work yet
cmake.definitions["WEBP_ENABLE_SIMD"] = self.options.with_simd
if self._version_components[0] >= 1:
cmake.definitions["WEBP_NEAR_LOSSLESS"] = self.options.near_lossless
else:
cmake.definitions["WEBP_ENABLE_NEAR_LOSSLESS"] = self.options.near_lossless
cmake.definitions['WEBP_ENABLE_SWAP_16BIT_CSP'] = self.options.swap_16bit_csp
# avoid finding system libs
cmake.definitions['CMAKE_DISABLE_FIND_PACKAGE_GIF'] = True
cmake.definitions['CMAKE_DISABLE_FIND_PACKAGE_PNG'] = True
cmake.definitions['CMAKE_DISABLE_FIND_PACKAGE_TIFF'] = True
cmake.definitions['CMAKE_DISABLE_FIND_PACKAGE_JPEG'] = True
if self.settings.os == "Android":
if 'CMAKE_ANDROID_ARCH_ABI' in cmake.definitions:
cmake.definitions['ANDROID_ABI'] = cmake.definitions['CMAKE_ANDROID_ARCH_ABI']
if 'ANDROID_NDK_HOME' in os.environ:
cmake.definitions['ANDROID_NDK'] = os.environ.get('ANDROID_NDK_HOME')
cmake.configure(source_folder=self._source_subfolder)
return cmake
def build(self):
# WEBP_EXTERN is not specified on Windows
# Set it to dllexport for building (see CMakeLists.txt) and to dllimport otherwise
if self.options.shared and self.settings.compiler == "Visual Studio":
tools.replace_in_file(os.path.join(self._source_subfolder, 'src', 'webp', 'types.h'),
'#ifndef WEBP_EXTERN',
"""#ifndef WEBP_EXTERN
#ifdef _MSC_VER
#ifdef WEBP_DLL
#define WEBP_EXTERN __declspec(dllexport)
#else
#define WEBP_EXTERN __declspec(dllimport)
#endif
#endif /* _MSC_VER */
#endif
#ifndef WEBP_EXTERN""")
# cmake misses dll (RUNTIME) copy
tools.replace_in_file(os.path.join(self._source_subfolder, "CMakeListsOriginal.txt"),
"LIBRARY DESTINATION lib",
"RUNTIME DESTINATION bin\nLIBRARY DESTINATION lib")
if self._version_components[0] >= 1:
# allow to build webpmux
tools.replace_in_file(os.path.join(self._source_subfolder, "CMakeListsOriginal.txt"),
"if(WEBP_BUILD_GIF2WEBP OR WEBP_BUILD_IMG2WEBP)",
"if(TRUE)")
cmake = self._configure_cmake()
cmake.build()
def package(self):
cmake = self._configure_cmake()
cmake.install()
self.copy("COPYING", dst="licenses", src=self._source_subfolder)
self.copy("FindWEBP.cmake", dst=".", src=".")
def package_info(self):
self.cpp_info.libs = ['webpmux', 'webpdemux', 'webpdecoder', 'webp']
if self.options.shared and self.settings.os == "Windows" and self.settings.compiler != 'Visual Studio':
self.cpp_info.libs = [lib + '.dll' for lib in self.cpp_info.libs]
|
[] |
[] |
[
"ANDROID_NDK_HOME"
] |
[]
|
["ANDROID_NDK_HOME"]
|
python
| 1 | 0 | |
association_test.go
|
package orm_test
import (
"fmt"
"os"
"reflect"
"sort"
"testing"
"ireul.com/orm"
)
func TestBelongsTo(t *testing.T) {
post := Post{
Title: "post belongs to",
Body: "body belongs to",
Category: Category{Name: "Category 1"},
MainCategory: Category{Name: "Main Category 1"},
}
if err := DB.Save(&post).Error; err != nil {
t.Error("Got errors when save post", err)
}
if post.Category.ID == 0 || post.MainCategory.ID == 0 {
t.Errorf("Category's primary key should be updated")
}
if post.CategoryId.Int64 == 0 || post.MainCategoryId == 0 {
t.Errorf("post's foreign key should be updated")
}
// Query
var category1 Category
DB.Model(&post).Association("Category").Find(&category1)
if category1.Name != "Category 1" {
t.Errorf("Query belongs to relations with Association")
}
var mainCategory1 Category
DB.Model(&post).Association("MainCategory").Find(&mainCategory1)
if mainCategory1.Name != "Main Category 1" {
t.Errorf("Query belongs to relations with Association")
}
var category11 Category
DB.Model(&post).Related(&category11)
if category11.Name != "Category 1" {
t.Errorf("Query belongs to relations with Related")
}
if DB.Model(&post).Association("Category").Count() != 1 {
t.Errorf("Post's category count should be 1")
}
if DB.Model(&post).Association("MainCategory").Count() != 1 {
t.Errorf("Post's main category count should be 1")
}
// Append
var category2 = Category{
Name: "Category 2",
}
DB.Model(&post).Association("Category").Append(&category2)
if category2.ID == 0 {
t.Errorf("Category should has ID when created with Append")
}
var category21 Category
DB.Model(&post).Related(&category21)
if category21.Name != "Category 2" {
t.Errorf("Category should be updated with Append")
}
if DB.Model(&post).Association("Category").Count() != 1 {
t.Errorf("Post's category count should be 1")
}
// Replace
var category3 = Category{
Name: "Category 3",
}
DB.Model(&post).Association("Category").Replace(&category3)
if category3.ID == 0 {
t.Errorf("Category should has ID when created with Replace")
}
var category31 Category
DB.Model(&post).Related(&category31)
if category31.Name != "Category 3" {
t.Errorf("Category should be updated with Replace")
}
if DB.Model(&post).Association("Category").Count() != 1 {
t.Errorf("Post's category count should be 1")
}
// Delete
DB.Model(&post).Association("Category").Delete(&category2)
if DB.Model(&post).Related(&Category{}).RecordNotFound() {
t.Errorf("Should not delete any category when Delete a unrelated Category")
}
if post.Category.Name == "" {
t.Errorf("Post's category should not be reseted when Delete a unrelated Category")
}
DB.Model(&post).Association("Category").Delete(&category3)
if post.Category.Name != "" {
t.Errorf("Post's category should be reseted after Delete")
}
var category41 Category
DB.Model(&post).Related(&category41)
if category41.Name != "" {
t.Errorf("Category should be deleted with Delete")
}
if count := DB.Model(&post).Association("Category").Count(); count != 0 {
t.Errorf("Post's category count should be 0 after Delete, but got %v", count)
}
// Clear
DB.Model(&post).Association("Category").Append(&Category{
Name: "Category 2",
})
if DB.Model(&post).Related(&Category{}).RecordNotFound() {
t.Errorf("Should find category after append")
}
if post.Category.Name == "" {
t.Errorf("Post's category should has value after Append")
}
DB.Model(&post).Association("Category").Clear()
if post.Category.Name != "" {
t.Errorf("Post's category should be cleared after Clear")
}
if !DB.Model(&post).Related(&Category{}).RecordNotFound() {
t.Errorf("Should not find any category after Clear")
}
if count := DB.Model(&post).Association("Category").Count(); count != 0 {
t.Errorf("Post's category count should be 0 after Clear, but got %v", count)
}
// Check Association mode with soft delete
category6 := Category{
Name: "Category 6",
}
DB.Model(&post).Association("Category").Append(&category6)
if count := DB.Model(&post).Association("Category").Count(); count != 1 {
t.Errorf("Post's category count should be 1 after Append, but got %v", count)
}
DB.Delete(&category6)
if count := DB.Model(&post).Association("Category").Count(); count != 0 {
t.Errorf("Post's category count should be 0 after the category has been deleted, but got %v", count)
}
if err := DB.Model(&post).Association("Category").Find(&Category{}).Error; err == nil {
t.Errorf("Post's category is not findable after Delete")
}
if count := DB.Unscoped().Model(&post).Association("Category").Count(); count != 1 {
t.Errorf("Post's category count should be 1 when query with Unscoped, but got %v", count)
}
if err := DB.Unscoped().Model(&post).Association("Category").Find(&Category{}).Error; err != nil {
t.Errorf("Post's category should be findable when query with Unscoped, got %v", err)
}
}
func TestBelongsToOverrideForeignKey1(t *testing.T) {
type Profile struct {
orm.Model
Name string
}
type User struct {
orm.Model
Profile Profile `orm:"ForeignKey:ProfileRefer"`
ProfileRefer int
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "belongs_to" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"ProfileRefer"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestBelongsToOverrideForeignKey2(t *testing.T) {
type Profile struct {
orm.Model
Refer string
Name string
}
type User struct {
orm.Model
Profile Profile `orm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
ProfileID int
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "belongs_to" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"ProfileID"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestHasOne(t *testing.T) {
user := User{
Name: "has one",
CreditCard: CreditCard{Number: "411111111111"},
}
if err := DB.Save(&user).Error; err != nil {
t.Error("Got errors when save user", err.Error())
}
if user.CreditCard.UserId.Int64 == 0 {
t.Errorf("CreditCard's foreign key should be updated")
}
// Query
var creditCard1 CreditCard
DB.Model(&user).Related(&creditCard1)
if creditCard1.Number != "411111111111" {
t.Errorf("Query has one relations with Related")
}
var creditCard11 CreditCard
DB.Model(&user).Association("CreditCard").Find(&creditCard11)
if creditCard11.Number != "411111111111" {
t.Errorf("Query has one relations with Related")
}
if DB.Model(&user).Association("CreditCard").Count() != 1 {
t.Errorf("User's credit card count should be 1")
}
// Append
var creditcard2 = CreditCard{
Number: "411111111112",
}
DB.Model(&user).Association("CreditCard").Append(&creditcard2)
if creditcard2.ID == 0 {
t.Errorf("Creditcard should has ID when created with Append")
}
var creditcard21 CreditCard
DB.Model(&user).Related(&creditcard21)
if creditcard21.Number != "411111111112" {
t.Errorf("CreditCard should be updated with Append")
}
if DB.Model(&user).Association("CreditCard").Count() != 1 {
t.Errorf("User's credit card count should be 1")
}
// Replace
var creditcard3 = CreditCard{
Number: "411111111113",
}
DB.Model(&user).Association("CreditCard").Replace(&creditcard3)
if creditcard3.ID == 0 {
t.Errorf("Creditcard should has ID when created with Replace")
}
var creditcard31 CreditCard
DB.Model(&user).Related(&creditcard31)
if creditcard31.Number != "411111111113" {
t.Errorf("CreditCard should be updated with Replace")
}
if DB.Model(&user).Association("CreditCard").Count() != 1 {
t.Errorf("User's credit card count should be 1")
}
// Delete
DB.Model(&user).Association("CreditCard").Delete(&creditcard2)
var creditcard4 CreditCard
DB.Model(&user).Related(&creditcard4)
if creditcard4.Number != "411111111113" {
t.Errorf("Should not delete credit card when Delete a unrelated CreditCard")
}
if DB.Model(&user).Association("CreditCard").Count() != 1 {
t.Errorf("User's credit card count should be 1")
}
DB.Model(&user).Association("CreditCard").Delete(&creditcard3)
if !DB.Model(&user).Related(&CreditCard{}).RecordNotFound() {
t.Errorf("Should delete credit card with Delete")
}
if DB.Model(&user).Association("CreditCard").Count() != 0 {
t.Errorf("User's credit card count should be 0 after Delete")
}
// Clear
var creditcard5 = CreditCard{
Number: "411111111115",
}
DB.Model(&user).Association("CreditCard").Append(&creditcard5)
if DB.Model(&user).Related(&CreditCard{}).RecordNotFound() {
t.Errorf("Should added credit card with Append")
}
if DB.Model(&user).Association("CreditCard").Count() != 1 {
t.Errorf("User's credit card count should be 1")
}
DB.Model(&user).Association("CreditCard").Clear()
if !DB.Model(&user).Related(&CreditCard{}).RecordNotFound() {
t.Errorf("Credit card should be deleted with Clear")
}
if DB.Model(&user).Association("CreditCard").Count() != 0 {
t.Errorf("User's credit card count should be 0 after Clear")
}
// Check Association mode with soft delete
var creditcard6 = CreditCard{
Number: "411111111116",
}
DB.Model(&user).Association("CreditCard").Append(&creditcard6)
if count := DB.Model(&user).Association("CreditCard").Count(); count != 1 {
t.Errorf("User's credit card count should be 1 after Append, but got %v", count)
}
DB.Delete(&creditcard6)
if count := DB.Model(&user).Association("CreditCard").Count(); count != 0 {
t.Errorf("User's credit card count should be 0 after credit card deleted, but got %v", count)
}
if err := DB.Model(&user).Association("CreditCard").Find(&CreditCard{}).Error; err == nil {
t.Errorf("User's creditcard is not findable after Delete")
}
if count := DB.Unscoped().Model(&user).Association("CreditCard").Count(); count != 1 {
t.Errorf("User's credit card count should be 1 when query with Unscoped, but got %v", count)
}
if err := DB.Unscoped().Model(&user).Association("CreditCard").Find(&CreditCard{}).Error; err != nil {
t.Errorf("User's creditcard should be findable when query with Unscoped, got %v", err)
}
}
func TestHasOneOverrideForeignKey1(t *testing.T) {
type Profile struct {
orm.Model
Name string
UserRefer uint
}
type User struct {
orm.Model
Profile Profile `orm:"ForeignKey:UserRefer"`
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "has_one" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserRefer"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestHasOneOverrideForeignKey2(t *testing.T) {
type Profile struct {
orm.Model
Name string
UserID uint
}
type User struct {
orm.Model
Refer string
Profile Profile `orm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "has_one" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserID"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestHasMany(t *testing.T) {
post := Post{
Title: "post has many",
Body: "body has many",
Comments: []*Comment{{Content: "Comment 1"}, {Content: "Comment 2"}},
}
if err := DB.Save(&post).Error; err != nil {
t.Error("Got errors when save post", err)
}
for _, comment := range post.Comments {
if comment.PostId == 0 {
t.Errorf("comment's PostID should be updated")
}
}
var compareComments = func(comments []Comment, contents []string) bool {
var commentContents []string
for _, comment := range comments {
commentContents = append(commentContents, comment.Content)
}
sort.Strings(commentContents)
sort.Strings(contents)
return reflect.DeepEqual(commentContents, contents)
}
// Query
if DB.First(&Comment{}, "content = ?", "Comment 1").Error != nil {
t.Errorf("Comment 1 should be saved")
}
var comments1 []Comment
DB.Model(&post).Association("Comments").Find(&comments1)
if !compareComments(comments1, []string{"Comment 1", "Comment 2"}) {
t.Errorf("Query has many relations with Association")
}
var comments11 []Comment
DB.Model(&post).Related(&comments11)
if !compareComments(comments11, []string{"Comment 1", "Comment 2"}) {
t.Errorf("Query has many relations with Related")
}
if DB.Model(&post).Association("Comments").Count() != 2 {
t.Errorf("Post's comments count should be 2")
}
// Append
DB.Model(&post).Association("Comments").Append(&Comment{Content: "Comment 3"})
var comments2 []Comment
DB.Model(&post).Related(&comments2)
if !compareComments(comments2, []string{"Comment 1", "Comment 2", "Comment 3"}) {
t.Errorf("Append new record to has many relations")
}
if DB.Model(&post).Association("Comments").Count() != 3 {
t.Errorf("Post's comments count should be 3 after Append")
}
// Delete
DB.Model(&post).Association("Comments").Delete(comments11)
var comments3 []Comment
DB.Model(&post).Related(&comments3)
if !compareComments(comments3, []string{"Comment 3"}) {
t.Errorf("Delete an existing resource for has many relations")
}
if DB.Model(&post).Association("Comments").Count() != 1 {
t.Errorf("Post's comments count should be 1 after Delete 2")
}
// Replace
DB.Model(&Post{Id: 999}).Association("Comments").Replace()
var comments4 []Comment
DB.Model(&post).Related(&comments4)
if len(comments4) == 0 {
t.Errorf("Replace for other resource should not clear all comments")
}
DB.Model(&post).Association("Comments").Replace(&Comment{Content: "Comment 4"}, &Comment{Content: "Comment 5"})
var comments41 []Comment
DB.Model(&post).Related(&comments41)
if !compareComments(comments41, []string{"Comment 4", "Comment 5"}) {
t.Errorf("Replace has many relations")
}
// Clear
DB.Model(&Post{Id: 999}).Association("Comments").Clear()
var comments5 []Comment
DB.Model(&post).Related(&comments5)
if len(comments5) == 0 {
t.Errorf("Clear should not clear all comments")
}
DB.Model(&post).Association("Comments").Clear()
var comments51 []Comment
DB.Model(&post).Related(&comments51)
if len(comments51) != 0 {
t.Errorf("Clear has many relations")
}
// Check Association mode with soft delete
var comment6 = Comment{
Content: "comment 6",
}
DB.Model(&post).Association("Comments").Append(&comment6)
if count := DB.Model(&post).Association("Comments").Count(); count != 1 {
t.Errorf("post's comments count should be 1 after Append, but got %v", count)
}
DB.Delete(&comment6)
if count := DB.Model(&post).Association("Comments").Count(); count != 0 {
t.Errorf("post's comments count should be 0 after comment been deleted, but got %v", count)
}
var comments6 []Comment
if DB.Model(&post).Association("Comments").Find(&comments6); len(comments6) != 0 {
t.Errorf("post's comments count should be 0 when find with Find, but got %v", len(comments6))
}
if count := DB.Unscoped().Model(&post).Association("Comments").Count(); count != 1 {
t.Errorf("post's comments count should be 1 when query with Unscoped, but got %v", count)
}
var comments61 []Comment
if DB.Unscoped().Model(&post).Association("Comments").Find(&comments61); len(comments61) != 1 {
t.Errorf("post's comments count should be 1 when query with Unscoped, but got %v", len(comments61))
}
}
func TestHasManyOverrideForeignKey1(t *testing.T) {
type Profile struct {
orm.Model
Name string
UserRefer uint
}
type User struct {
orm.Model
Profile []Profile `orm:"ForeignKey:UserRefer"`
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "has_many" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserRefer"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestHasManyOverrideForeignKey2(t *testing.T) {
type Profile struct {
orm.Model
Name string
UserID uint
}
type User struct {
orm.Model
Refer string
Profile []Profile `orm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
}
if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok {
if relation.Relationship.Kind != "has_many" ||
!reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserID"}) ||
!reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) {
t.Errorf("Override belongs to foreign key with tag")
}
}
}
func TestManyToMany(t *testing.T) {
DB.Raw("delete from languages")
var languages = []Language{{Name: "ZH"}, {Name: "EN"}}
user := User{Name: "Many2Many", Languages: languages}
DB.Save(&user)
// Query
var newLanguages []Language
DB.Model(&user).Related(&newLanguages, "Languages")
if len(newLanguages) != len([]string{"ZH", "EN"}) {
t.Errorf("Query many to many relations")
}
DB.Model(&user).Association("Languages").Find(&newLanguages)
if len(newLanguages) != len([]string{"ZH", "EN"}) {
t.Errorf("Should be able to find many to many relations")
}
if DB.Model(&user).Association("Languages").Count() != len([]string{"ZH", "EN"}) {
t.Errorf("Count should return correct result")
}
// Append
DB.Model(&user).Association("Languages").Append(&Language{Name: "DE"})
if DB.Where("name = ?", "DE").First(&Language{}).RecordNotFound() {
t.Errorf("New record should be saved when append")
}
languageA := Language{Name: "AA"}
DB.Save(&languageA)
DB.Model(&User{Id: user.Id}).Association("Languages").Append(&languageA)
languageC := Language{Name: "CC"}
DB.Save(&languageC)
DB.Model(&user).Association("Languages").Append(&[]Language{{Name: "BB"}, languageC})
DB.Model(&User{Id: user.Id}).Association("Languages").Append(&[]Language{{Name: "DD"}, {Name: "EE"}})
totalLanguages := []string{"ZH", "EN", "DE", "AA", "BB", "CC", "DD", "EE"}
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages) {
t.Errorf("All appended languages should be saved")
}
// Delete
user.Languages = []Language{}
DB.Model(&user).Association("Languages").Find(&user.Languages)
var language Language
DB.Where("name = ?", "EE").First(&language)
DB.Model(&user).Association("Languages").Delete(language, &language)
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 || len(user.Languages) != len(totalLanguages)-1 {
t.Errorf("Relations should be deleted with Delete")
}
if DB.Where("name = ?", "EE").First(&Language{}).RecordNotFound() {
t.Errorf("Language EE should not be deleted")
}
DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages)
user2 := User{Name: "Many2Many_User2", Languages: languages}
DB.Save(&user2)
DB.Model(&user).Association("Languages").Delete(languages, &languages)
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 || len(user.Languages) != len(totalLanguages)-3 {
t.Errorf("Relations should be deleted with Delete")
}
if DB.Model(&user2).Association("Languages").Count() == 0 {
t.Errorf("Other user's relations should not be deleted")
}
// Replace
var languageB Language
DB.Where("name = ?", "BB").First(&languageB)
DB.Model(&user).Association("Languages").Replace(languageB)
if len(user.Languages) != 1 || DB.Model(&user).Association("Languages").Count() != 1 {
t.Errorf("Relations should be replaced")
}
DB.Model(&user).Association("Languages").Replace()
if len(user.Languages) != 0 || DB.Model(&user).Association("Languages").Count() != 0 {
t.Errorf("Relations should be replaced with empty")
}
DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
if len(user.Languages) != 2 || DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
t.Errorf("Relations should be replaced")
}
// Clear
DB.Model(&user).Association("Languages").Clear()
if len(user.Languages) != 0 || DB.Model(&user).Association("Languages").Count() != 0 {
t.Errorf("Relations should be cleared")
}
// Check Association mode with soft delete
var language6 = Language{
Name: "language 6",
}
DB.Model(&user).Association("Languages").Append(&language6)
if count := DB.Model(&user).Association("Languages").Count(); count != 1 {
t.Errorf("user's languages count should be 1 after Append, but got %v", count)
}
DB.Delete(&language6)
if count := DB.Model(&user).Association("Languages").Count(); count != 0 {
t.Errorf("user's languages count should be 0 after language been deleted, but got %v", count)
}
var languages6 []Language
if DB.Model(&user).Association("Languages").Find(&languages6); len(languages6) != 0 {
t.Errorf("user's languages count should be 0 when find with Find, but got %v", len(languages6))
}
if count := DB.Unscoped().Model(&user).Association("Languages").Count(); count != 1 {
t.Errorf("user's languages count should be 1 when query with Unscoped, but got %v", count)
}
var languages61 []Language
if DB.Unscoped().Model(&user).Association("Languages").Find(&languages61); len(languages61) != 1 {
t.Errorf("user's languages count should be 1 when query with Unscoped, but got %v", len(languages61))
}
}
func TestRelated(t *testing.T) {
user := User{
Name: "jinzhu",
BillingAddress: Address{Address1: "Billing Address - Address 1"},
ShippingAddress: Address{Address1: "Shipping Address - Address 1"},
Emails: []Email{{Email: "[email protected]"}, {Email: "jinzhu-2@[email protected]"}},
CreditCard: CreditCard{Number: "1234567890"},
Company: Company{Name: "company1"},
}
if err := DB.Save(&user).Error; err != nil {
t.Errorf("No error should happen when saving user")
}
if user.CreditCard.ID == 0 {
t.Errorf("After user save, credit card should have id")
}
if user.BillingAddress.ID == 0 {
t.Errorf("After user save, billing address should have id")
}
if user.Emails[0].Id == 0 {
t.Errorf("After user save, billing address should have id")
}
var emails []Email
DB.Model(&user).Related(&emails)
if len(emails) != 2 {
t.Errorf("Should have two emails")
}
var emails2 []Email
DB.Model(&user).Where("email = ?", "[email protected]").Related(&emails2)
if len(emails2) != 1 {
t.Errorf("Should have two emails")
}
var emails3 []*Email
DB.Model(&user).Related(&emails3)
if len(emails3) != 2 {
t.Errorf("Should have two emails")
}
var user1 User
DB.Model(&user).Related(&user1.Emails)
if len(user1.Emails) != 2 {
t.Errorf("Should have only one email match related condition")
}
var address1 Address
DB.Model(&user).Related(&address1, "BillingAddressId")
if address1.Address1 != "Billing Address - Address 1" {
t.Errorf("Should get billing address from user correctly")
}
user1 = User{}
DB.Model(&address1).Related(&user1, "BillingAddressId")
if DB.NewRecord(user1) {
t.Errorf("Should get user from address correctly")
}
var user2 User
DB.Model(&emails[0]).Related(&user2)
if user2.Id != user.Id || user2.Name != user.Name {
t.Errorf("Should get user from email correctly")
}
var creditcard CreditCard
var user3 User
DB.First(&creditcard, "number = ?", "1234567890")
DB.Model(&creditcard).Related(&user3)
if user3.Id != user.Id || user3.Name != user.Name {
t.Errorf("Should get user from credit card correctly")
}
if !DB.Model(&CreditCard{}).Related(&User{}).RecordNotFound() {
t.Errorf("RecordNotFound for Related")
}
var company Company
if DB.Model(&user).Related(&company, "Company").RecordNotFound() || company.Name != "company1" {
t.Errorf("RecordNotFound for Related")
}
}
func TestForeignKey(t *testing.T) {
for _, structField := range DB.NewScope(&User{}).GetStructFields() {
for _, foreignKey := range []string{"BillingAddressID", "ShippingAddressId", "CompanyID"} {
if structField.Name == foreignKey && !structField.IsForeignKey {
t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey))
}
}
}
for _, structField := range DB.NewScope(&Email{}).GetStructFields() {
for _, foreignKey := range []string{"UserId"} {
if structField.Name == foreignKey && !structField.IsForeignKey {
t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey))
}
}
}
for _, structField := range DB.NewScope(&Post{}).GetStructFields() {
for _, foreignKey := range []string{"CategoryId", "MainCategoryId"} {
if structField.Name == foreignKey && !structField.IsForeignKey {
t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey))
}
}
}
for _, structField := range DB.NewScope(&Comment{}).GetStructFields() {
for _, foreignKey := range []string{"PostId"} {
if structField.Name == foreignKey && !structField.IsForeignKey {
t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey))
}
}
}
}
func testForeignKey(t *testing.T, source interface{}, sourceFieldName string, target interface{}, targetFieldName string) {
if dialect := os.Getenv("orm_DIALECT"); dialect == "" || dialect == "sqlite" {
// sqlite does not support ADD CONSTRAINT in ALTER TABLE
return
}
targetScope := DB.NewScope(target)
targetTableName := targetScope.TableName()
modelScope := DB.NewScope(source)
modelField, ok := modelScope.FieldByName(sourceFieldName)
if !ok {
t.Fatalf(fmt.Sprintf("Failed to get field by name: %v", sourceFieldName))
}
targetField, ok := targetScope.FieldByName(targetFieldName)
if !ok {
t.Fatalf(fmt.Sprintf("Failed to get field by name: %v", targetFieldName))
}
dest := fmt.Sprintf("%v(%v)", targetTableName, targetField.DBName)
err := DB.Model(source).AddForeignKey(modelField.DBName, dest, "CASCADE", "CASCADE").Error
if err != nil {
t.Fatalf(fmt.Sprintf("Failed to create foreign key: %v", err))
}
}
func TestLongForeignKey(t *testing.T) {
testForeignKey(t, &NotSoLongTableName{}, "ReallyLongThingID", &ReallyLongTableNameToTestMySQLNameLengthLimit{}, "ID")
}
func TestLongForeignKeyWithShortDest(t *testing.T) {
testForeignKey(t, &ReallyLongThingThatReferencesShort{}, "ShortID", &Short{}, "ID")
}
func TestHasManyChildrenWithOneStruct(t *testing.T) {
category := Category{
Name: "main",
Categories: []Category{
{Name: "sub1"},
{Name: "sub2"},
},
}
DB.Save(&category)
}
func TestAutoSaveBelongsToAssociation(t *testing.T) {
type Company struct {
orm.Model
Name string
}
type User struct {
orm.Model
Name string
CompanyID uint
Company Company `orm:"association_autoupdate:false;association_autocreate:false;"`
}
DB.Where("name = ?", "auto_save_association").Delete(&Company{})
DB.AutoMigrate(&Company{}, &User{})
DB.Save(&User{Name: "jinzhu", Company: Company{Name: "auto_save_association"}})
if !DB.Where("name = ?", "auto_save_association").First(&Company{}).RecordNotFound() {
t.Errorf("Company auto_save_association should not have been saved when autosave is false")
}
// if foreign key is set, this should be saved even if association isn't
company := Company{Name: "auto_save_association"}
DB.Save(&company)
company.Name = "auto_save_association_new_name"
user := User{Name: "jinzhu", Company: company}
DB.Save(&user)
if !DB.Where("name = ?", "auto_save_association_new_name").First(&Company{}).RecordNotFound() {
t.Errorf("Company should not have been updated")
}
if DB.Where("id = ? AND company_id = ?", user.ID, company.ID).First(&User{}).RecordNotFound() {
t.Errorf("User's foreign key should have been saved")
}
user2 := User{Name: "jinzhu_2", Company: Company{Name: "auto_save_association_2"}}
DB.Set("orm:association_autocreate", true).Save(&user2)
if DB.Where("name = ?", "auto_save_association_2").First(&Company{}).RecordNotFound() {
t.Errorf("Company auto_save_association_2 should been created when autocreate is true")
}
user2.Company.Name = "auto_save_association_2_newname"
DB.Set("orm:association_autoupdate", true).Save(&user2)
if DB.Where("name = ?", "auto_save_association_2_newname").First(&Company{}).RecordNotFound() {
t.Errorf("Company should been updated")
}
}
func TestAutoSaveHasOneAssociation(t *testing.T) {
type Company struct {
orm.Model
UserID uint
Name string
}
type User struct {
orm.Model
Name string
Company Company `orm:"association_autoupdate:false;association_autocreate:false;"`
}
DB.Where("name = ?", "auto_save_has_one_association").Delete(&Company{})
DB.AutoMigrate(&Company{}, &User{})
DB.Save(&User{Name: "jinzhu", Company: Company{Name: "auto_save_has_one_association"}})
if !DB.Where("name = ?", "auto_save_has_one_association").First(&Company{}).RecordNotFound() {
t.Errorf("Company auto_save_has_one_association should not have been saved when autosave is false")
}
company := Company{Name: "auto_save_has_one_association"}
DB.Save(&company)
company.Name = "auto_save_has_one_association_new_name"
user := User{Name: "jinzhu", Company: company}
DB.Save(&user)
if !DB.Where("name = ?", "auto_save_has_one_association_new_name").First(&Company{}).RecordNotFound() {
t.Errorf("Company should not have been updated")
}
if !DB.Where("name = ? AND user_id = ?", "auto_save_has_one_association", user.ID).First(&Company{}).RecordNotFound() {
t.Errorf("Company should not have been updated")
}
if user.Company.UserID == 0 {
t.Errorf("UserID should be assigned")
}
company.Name = "auto_save_has_one_association_2_new_name"
DB.Set("orm:association_autoupdate", true).Save(&user)
if DB.Where("name = ? AND user_id = ?", "auto_save_has_one_association_new_name", user.ID).First(&Company{}).RecordNotFound() {
t.Errorf("Company should been updated")
}
user2 := User{Name: "jinzhu_2", Company: Company{Name: "auto_save_has_one_association_2"}}
DB.Set("orm:association_autocreate", true).Save(&user2)
if DB.Where("name = ?", "auto_save_has_one_association_2").First(&Company{}).RecordNotFound() {
t.Errorf("Company auto_save_has_one_association_2 should been created when autocreate is true")
}
}
func TestAutoSaveMany2ManyAssociation(t *testing.T) {
type Company struct {
orm.Model
Name string
}
type User struct {
orm.Model
Name string
Companies []Company `orm:"many2many:user_companies;association_autoupdate:false;association_autocreate:false;"`
}
DB.AutoMigrate(&Company{}, &User{})
DB.Save(&User{Name: "jinzhu", Companies: []Company{{Name: "auto_save_m2m_association"}}})
if !DB.Where("name = ?", "auto_save_m2m_association").First(&Company{}).RecordNotFound() {
t.Errorf("Company auto_save_m2m_association should not have been saved when autosave is false")
}
company := Company{Name: "auto_save_m2m_association"}
DB.Save(&company)
company.Name = "auto_save_m2m_association_new_name"
user := User{Name: "jinzhu", Companies: []Company{company, {Name: "auto_save_m2m_association_new_name_2"}}}
DB.Save(&user)
if !DB.Where("name = ?", "auto_save_m2m_association_new_name").First(&Company{}).RecordNotFound() {
t.Errorf("Company should not have been updated")
}
if !DB.Where("name = ?", "auto_save_m2m_association_new_name_2").First(&Company{}).RecordNotFound() {
t.Errorf("Company should not been created")
}
if DB.Model(&user).Association("Companies").Count() != 1 {
t.Errorf("Relationship should been saved")
}
DB.Set("orm:association_autoupdate", true).Set("orm:association_autocreate", true).Save(&user)
if DB.Where("name = ?", "auto_save_m2m_association_new_name").First(&Company{}).RecordNotFound() {
t.Errorf("Company should been updated")
}
if DB.Where("name = ?", "auto_save_m2m_association_new_name_2").First(&Company{}).RecordNotFound() {
t.Errorf("Company should been created")
}
if DB.Model(&user).Association("Companies").Count() != 2 {
t.Errorf("Relationship should been updated")
}
}
|
[
"\"orm_DIALECT\""
] |
[] |
[
"orm_DIALECT"
] |
[]
|
["orm_DIALECT"]
|
go
| 1 | 0 | |
predict92_loc.py
|
import os
from os import path, makedirs, listdir
# import sys
import numpy as np
np.random.seed(1)
import random
random.seed(1)
import torch
from torch import nn
# from torch.backends import cudnn
from torch.autograd import Variable
# import pandas as pd
from tqdm import tqdm
import timeit
import cv2
from zoo.models import Dpn92_Unet_Loc
from utils import *
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
test_dir = 'test/images'
pred_folder = 'pred92_loc_tuned'
models_folder = 'weights'
if __name__ == '__main__':
t0 = timeit.default_timer()
makedirs(pred_folder, exist_ok=True)
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
# os.environ["CUDA_VISIBLE_DEVICES"] = sys.argv[1]
# cudnn.benchmark = True
models = []
for seed in [0, 1, 2]:
snap_to_load = 'dpn92_loc_{}_tuned_best'.format(seed)
model = Dpn92_Unet_Loc().cuda()
print("=> loading checkpoint '{}'".format(snap_to_load))
checkpoint = torch.load(path.join(models_folder, snap_to_load), map_location='cpu')
loaded_dict = checkpoint['state_dict']
sd = model.state_dict()
for k in model.state_dict():
if k in loaded_dict and sd[k].size() == loaded_dict[k].size():
sd[k] = loaded_dict[k]
loaded_dict = sd
model.load_state_dict(loaded_dict)
print("loaded checkpoint '{}' (epoch {}, best_score {})"
.format(snap_to_load, checkpoint['epoch'], checkpoint['best_score']))
model.eval()
models.append(model)
with torch.no_grad():
for f in tqdm(sorted(listdir(test_dir))):
if '_pre_' in f:
fn = path.join(test_dir, f)
img = cv2.imread(fn, cv2.IMREAD_COLOR)
img = preprocess_inputs(img)
inp = []
inp.append(img)
inp.append(img[::-1, ...])
inp.append(img[:, ::-1, ...])
inp.append(img[::-1, ::-1, ...])
inp = np.asarray(inp, dtype='float')
inp = torch.from_numpy(inp.transpose((0, 3, 1, 2))).float()
inp = Variable(inp).cuda()
pred = []
for model in models:
msk = model(inp)
msk = torch.sigmoid(msk)
msk = msk.cpu().numpy()
pred.append(msk[0, ...])
pred.append(msk[1, :, ::-1, :])
pred.append(msk[2, :, :, ::-1])
pred.append(msk[3, :, ::-1, ::-1])
pred_full = np.asarray(pred).mean(axis=0)
msk = pred_full * 255
msk = msk.astype('uint8').transpose(1, 2, 0)
cv2.imwrite(path.join(pred_folder, '{0}'.format(f.replace('.png', '_part1.png'))), msk[..., 0], [cv2.IMWRITE_PNG_COMPRESSION, 9])
elapsed = timeit.default_timer() - t0
print('Time: {:.3f} min'.format(elapsed / 60))
|
[] |
[] |
[
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
|
python
| 2 | 0 | |
source/py4dlib/examples/ShowPolygonNumber.py
|
# -*- coding: utf-8 -*-
#
# ShowPolygonNumber.py
# py4dlib.examples
#
# Created by André Berg on 2013-07-29.
# Copyright 2013 Berg Media. All rights reserved.
#
# [email protected]
#
# ShowPolygonNumber
#
# Create and attach text splines to polygons.
#
# Summary:
#
# Example script that shows how to get point and polygon selections
# and how to create objects and attach them to polygons in local and
# global coordinate systems.
#
# pylint: disable-msg=F0401
"""
Name-US:Show Polygon Number
Description-US:Create and attach text splines indicating the polygon number to each selected polygon.
"""
import os
__version__ = (0, 2)
__date__ = '2013-07-29'
__updated__ = '2013-08-08'
DEBUG = 0 or ('DebugLevel' in os.environ and os.environ['DebugLevel'] > 0)
TESTRUN = 0 or ('TestRunLevel' in os.environ and os.environ['TestRunLevel'] > 0)
try:
import c4d #@UnresolvedImport
from c4d import documents
except ImportError:
if TESTRUN == 1:
pass
if DEBUG:
import py4dlib
reload(py4dlib.mesh)
reload(py4dlib.maths)
from py4dlib.maths import BuildMatrix3, IsZeroVector, BBox
from py4dlib.mesh import CalcPolyNormal, CalcPolyCentroid, CalcPolyArea, PolyToListList
from py4dlib.mesh import GetSelectedPoints, GetSelectedPolys
from py4dlib.objects import CreateObject, InsertUnderNull
from py4dlib.utils import ClearConsole, PPLLString
# group text spline objects under op else insert at root
GROUP_UNDER = True
TEXT_SIZE = 1
def main(doc): # IGNORE:W0621
doc.StartUndo()
sel = doc.GetSelection()
if sel is None: return False
c4d.StopAllThreads()
# loop through all objects
for op in sel:
if not isinstance(op, c4d.PolygonObject):
if DEBUG:
print("%s: not a polygon object. Skipping..." % str(op.GetName()))
continue
print("object name: %s" % op.GetName())
pointsel = op.GetPointS()
pointselcnt = pointsel.GetCount()
pointcnt = op.GetPointCount()
allpoints = op.GetAllPoints()
print("number of selected points = %s (%s total)" % (pointselcnt, pointcnt))
polysel = op.GetPolygonS()
polyselcnt = polysel.GetCount()
polycnt = op.GetPolygonCount()
allpolys = op.GetAllPolygons()
print("number of selected polygons = %s (%s total)" % (polyselcnt, polycnt))
pnts = GetSelectedPoints(op)
plys = GetSelectedPolys(op)
if len(plys) == 0:
# nothing selected? use all polys
plys = list(xrange(0, polycnt))
print("selected points = %s" % pnts)
print("selected polys = %s" % plys)
for pnt in pnts:
print("%d: %s" % (pnt, allpoints[pnt]))
pmarks = []
op_mg = op.GetMg()
op_name = op.GetName()
pgrp_name = "%s - Polygon #s" % op_name
pgrp = doc.SearchObject(pgrp_name)
if pgrp:
pgrp.Remove()
for ply in plys:
poly = allpolys[ply]
a = allpoints[poly.a]
b = allpoints[poly.b]
c = allpoints[poly.c]
d = allpoints[poly.d]
pids = [a, b, c]
plen = 3
if c != d:
pids.append(d)
plen = 4
cv1 = a - b
cv2 = b - c
cv3 = c - d
cv4 = d - a
if plen == 4:
cva = (cv3 - cv1)
cvb = (cv4 - cv2)
else:
cva = cv3 - cv1
cvb = cv3 - cv2
if plen == 4:
cv = c4d.Vector(cva.x, cvb.y/2, cva.z)
else:
if cvb.y == 0:
cv = cvb
else:
cv = cva
if IsZeroVector(cv):
if cv == cva:
cv = cvb
else:
cv = cva
AXIS_ZY = 1
base = "x"
axis = AXIS_ZY
if DEBUG:
print("pids = %r" % pids)
print("%d: %s, points as list<list>:" % (ply, poly))
print("%s" % (PPLLString(PolyToListList(poly, op))))
# calculate polygon normals
pnormal = CalcPolyNormal(poly, op)
if DEBUG: print("normal: %s" % (pnormal))
# calculate polygon area and bounding box
parea = CalcPolyArea(poly, op)
pbb = BBox.FromPolygon(poly, op)
pbb_slen = pbb.size.GetLength()
parea = (parea / pbb_slen / 2.0) * TEXT_SIZE
if DEBUG:
print("pbb_slen: %s" % pbb_slen)
print("area: %s" % (parea))
# create text spline objects
pname = "%d" % ply
pmark = CreateObject(c4d.Osplinetext, pname)
pmark[c4d.PRIM_TEXT_TEXT] = pname # Text
pmark[c4d.PRIM_TEXT_HEIGHT] = parea # Font Height
pmark[c4d.PRIM_PLANE] = axis # Orientation
if GROUP_UNDER:
ppos = CalcPolyCentroid(poly, op)
else:
# put in scene globally and don't group under op
ppos = CalcPolyCentroid(poly, op) * op_mg
# match position and orientation
pmg = BuildMatrix3(pnormal, cv, off=ppos, base=base)
pmg.v2 = -pmg.v2
# create translation matrix to center the text letters
tm = c4d.utils.MatrixMove(c4d.Vector(0, -parea/3, 0))
pmg *= tm
pmark.SetMg(pmg)
pmarks.append(pmark)
# group spline text objects under null for each op
pgrp = InsertUnderNull(pmarks, name=pgrp_name)
if GROUP_UNDER:
pgrp.InsertUnder(op)
# tell C4D to update internal state
c4d.EventAdd()
doc.EndUndo()
if __name__ == '__main__':
ClearConsole()
doc = documents.GetActiveDocument()
main(doc)
# 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.
|
[] |
[] |
[
"DebugLevel",
"TestRunLevel"
] |
[]
|
["DebugLevel", "TestRunLevel"]
|
python
| 2 | 0 | |
br/cmd/tidb-lightning/main.go
|
// Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"runtime/debug"
"syscall"
"github.com/pingcap/tidb/br/pkg/lightning"
"github.com/pingcap/tidb/br/pkg/lightning/config"
"github.com/pingcap/tidb/br/pkg/lightning/log"
"go.uber.org/zap"
)
func main() {
globalCfg := config.Must(config.LoadGlobalConfig(os.Args[1:], nil))
fmt.Fprintf(os.Stdout, "Verbose debug logs will be written to %s\n\n", globalCfg.App.Config.File)
app := lightning.New(globalCfg)
sc := make(chan os.Signal, 1)
signal.Notify(sc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
sig := <-sc
log.L().Info("got signal to exit", zap.Stringer("signal", sig))
app.Stop()
}()
logger := log.L()
// Lightning allocates too many transient objects and heap size is small,
// so garbage collections happen too frequently and lots of time is spent in GC component.
//
// In a test of loading the table `order_line.csv` of 14k TPCC.
// The time need of `encode kv data and write` step reduce from 52m4s to 37m30s when change
// GOGC from 100 to 500, the total time needed reduce near 15m too.
// The cost of this is the memory of lightning at runtime grow from about 200M to 700M, but it's acceptable.
// So we set the gc percentage as 500 default to reduce the GC frequency instead of 100.
//
// Local mode need much more memory than importer/tidb mode, if the gc percentage is too high,
// lightning memory usage will also be high.
if globalCfg.TikvImporter.Backend != config.BackendLocal {
gogc := os.Getenv("GOGC")
if gogc == "" {
old := debug.SetGCPercent(500)
log.L().Debug("set gc percentage", zap.Int("old", old), zap.Int("new", 500))
}
}
err := app.GoServe()
if err != nil {
logger.Error("failed to start HTTP server", zap.Error(err))
fmt.Fprintln(os.Stderr, "failed to start HTTP server:", err)
return
}
err = func() error {
if globalCfg.App.ServerMode {
return app.RunServer()
}
cfg := config.NewConfig()
if err := cfg.LoadFromGlobal(globalCfg); err != nil {
return err
}
return app.RunOnce(context.Background(), cfg, nil)
}()
if err != nil {
logger.Error("tidb lightning encountered error stack info", zap.Error(err))
fmt.Fprintln(os.Stderr, "tidb lightning encountered error: ", err)
} else {
logger.Info("tidb lightning exit")
fmt.Fprintln(os.Stdout, "tidb lightning exit")
}
// call Sync() with log to stdout may return error in some case, so just skip it
if globalCfg.App.File != "" {
syncErr := logger.Sync()
if syncErr != nil {
fmt.Fprintln(os.Stderr, "sync log failed", syncErr)
}
}
if err != nil {
exit(1)
}
}
// main_test.go override exit to pass unit test.
var exit = os.Exit
|
[
"\"GOGC\""
] |
[] |
[
"GOGC"
] |
[]
|
["GOGC"]
|
go
| 1 | 0 | |
compile/benchmark_test.go
|
// Copyright (c) 2018 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package compile
import (
"bytes"
"io/ioutil"
"os"
"path"
"testing"
"gate.computer/wag/buffer"
"gate.computer/wag/compile/event"
"gate.computer/wag/internal/loader"
"gate.computer/wag/internal/test/library"
"gate.computer/wag/section"
)
var lib = *library.Load("../testsuite/testdata/library.wasm", true, func(load *loader.L) library.L {
mod := loadInitialSections(nil, load)
lib := mod.asLibrary()
return &lib
}).(*Library)
var benchDir = "../wag-bench" // Relative to project root directory.
func init() {
if s := os.Getenv("WAG_BENCH_DIR"); s != "" {
benchDir = path.Join("..", s)
}
}
var (
benchTextBuf = make([]byte, 16*1024*1024)
benchDataBuf = make([]byte, 32*1024*1024)
)
func BenchmarkLoad000(b *testing.B) { bench(b, "000", "run") }
func BenchmarkLoad000E(b *testing.B) { benchE(b, "000", "run", func(event.Event) {}) }
func BenchmarkLoad001(b *testing.B) { bench(b, "001", "main") } // Gain hello example, debug build
func BenchmarkLoad002(b *testing.B) { bench(b, "002", "main") } // Gain hello example, release build
func BenchmarkLoad003(b *testing.B) { bench(b, "003", "_start") } // DOOM
func bench(b *testing.B, filename, entrySymbol string) {
benchE(b, filename, entrySymbol, nil)
}
func benchE(b *testing.B, filename, entrySymbol string, eventHandler func(event.Event)) {
b.Helper()
wasm, err := ioutil.ReadFile(path.Join("..", benchDir, filename) + ".wasm")
if err != nil {
if os.IsNotExist(err) {
b.Skip(err)
} else {
b.Fatal(err)
}
}
load := loader.New(bytes.NewReader(wasm), 0)
loadInitialSections(nil, load)
initLen := load.Tell()
if err := section.SkipCustomSections(load, nil); err != nil {
b.Fatal(err)
}
codePos := load.Tell()
codePayloadLen, err := section.CopyStandardSection(ioutil.Discard, load, section.Code, nil)
if err != nil {
b.Fatal(err)
}
if err := section.SkipCustomSections(load, nil); err != nil {
b.Fatal(err)
}
dataPos := load.Tell()
var mod Module
b.Run("Init", func(b *testing.B) {
b.SetBytes(initLen)
for i := 0; i < b.N; i++ {
mod = loadInitialSections(nil, loader.New(bytes.NewReader(wasm), 0))
for i := 0; i < mod.NumImportFuncs(); i++ {
// Arbitrary (but existing) implementation.
mod.SetImportFunc(i, uint32(lib.NumImportFuncs()))
}
}
})
b.Run("Code", func(b *testing.B) {
b.SetBytes(codePayloadLen)
for i := 0; i < b.N; i++ {
code := CodeConfig{
Text: buffer.NewStatic(benchTextBuf[:0:len(benchTextBuf)]),
EventHandler: eventHandler,
}
code.LastInitFunc, _, _ = mod.ExportFunc(entrySymbol)
loadCodeSection(&code, loader.New(bytes.NewReader(wasm[codePos:]), 0), mod, &lib.l)
}
})
b.Run("Data", func(b *testing.B) {
for i := 0; i < b.N; i++ {
data := DataConfig{
GlobalsMemory: buffer.NewStatic(benchDataBuf[:0:len(benchDataBuf)]),
}
loadDataSection(&data, loader.New(bytes.NewReader(wasm[dataPos:]), 0), mod)
}
})
}
|
[
"\"WAG_BENCH_DIR\""
] |
[] |
[
"WAG_BENCH_DIR"
] |
[]
|
["WAG_BENCH_DIR"]
|
go
| 1 | 0 | |
src/test/java/com/microfocus/application/automation/tools/octane/tests/detection/UFTExtensionTest.java
|
/*
* Certain versions of software and/or documents ("Material") accessible here may contain branding from
* Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017,
* the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP
* and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE
* marks are the property of their respective owners.
* __________________________________________________________________
* MIT License
*
* (c) Copyright 2012-2021 Micro Focus or one of its affiliates.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* ___________________________________________________________________
*/
package com.microfocus.application.automation.tools.octane.tests.detection;
import com.microfocus.application.automation.tools.model.AlmServerSettingsModel;
import com.microfocus.application.automation.tools.uft.model.FilterTestsModel;
import com.microfocus.application.automation.tools.octane.tests.TestUtils;
import com.microfocus.application.automation.tools.octane.tests.detection.ResultFieldsXmlReader.TestAttributes;
import com.microfocus.application.automation.tools.octane.tests.detection.ResultFieldsXmlReader.TestResultContainer;
import com.microfocus.application.automation.tools.run.RunFromAlmBuilder;
import com.microfocus.application.automation.tools.run.RunFromFileBuilder;
import com.microfocus.application.automation.tools.uft.model.SpecifyParametersModel;
import hudson.model.AbstractBuild;
import hudson.model.FreeStyleProject;
import hudson.scm.SubversionSCM;
import hudson.tasks.Maven;
import hudson.tasks.junit.JUnitResultArchiver;
import org.junit.*;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.ToolInstallations;
import org.mockito.Mockito;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
@SuppressWarnings("squid:S2699")
public class UFTExtensionTest {
@ClassRule
public static final JenkinsRule rule = new JenkinsRule();
private ResultFieldsDetectionService detectionService;
@Before
public void before() {
detectionService = new ResultFieldsDetectionService();
}
@Test
public void testMockOneBuilder() throws Exception {
String projectName = "root-job-" + UUID.randomUUID().toString();
FreeStyleProject project = rule.createFreeStyleProject(projectName);
project.getBuildersList().add(new RunFromFileBuilder("notExistingTest"));
AbstractBuild buildMock = Mockito.mock(AbstractBuild.class);
Mockito.when(buildMock.getProject()).thenReturn(project);
ResultFields fields = detectionService.getDetectedFields(buildMock);
assertUFTFields(fields);
}
@Test
public void testMockMoreBuilders() throws Exception {
String projectName = "root-job-" + UUID.randomUUID().toString();
FreeStyleProject project = rule.createFreeStyleProject(projectName);
FilterTestsModel filterTestsModel = new FilterTestsModel("testName", false, false, false, false, false);
SpecifyParametersModel parametersModel = new SpecifyParametersModel("[]");
AlmServerSettingsModel almServerSettingsModel = new AlmServerSettingsModel("server2", "serverURL", new ArrayList<>(), new ArrayList<>());
project.getBuildersList().add(new Maven(String.format("--settings \"%s\\conf\\settings.xml\" test -Dmaven.repo.local=%s\\m2-temp",
TestUtils.getMavenHome(),System.getenv("TEMP")), ToolInstallations.configureMaven3().getName(), null, null, "-Dmaven.test.failure.ignore=true"));
project.getBuildersList().add(new RunFromAlmBuilder("notExistingServer", "JOB", "sa", "", "domain", "project", "notExistingTests", "", "", "", "", "","", false, false, false, filterTestsModel, parametersModel, almServerSettingsModel));
AbstractBuild buildMock = Mockito.mock(AbstractBuild.class);
Mockito.when(buildMock.getProject()).thenReturn(project);
ResultFields fields = detectionService.getDetectedFields(buildMock);
assertUFTFields(fields);
}
@Test
public void testFileBuilder() throws Exception {
String projectName = "root-job-" + UUID.randomUUID().toString();
FreeStyleProject project = rule.createFreeStyleProject(projectName);
project.getBuildersList().add(new RunFromFileBuilder(""));
//UFT plugin will not find any test -> that will cause failing the scheduled build
//but as detection runs after completion of run, we are sure, that it did not fail because of detection service
AbstractBuild build = project.scheduleBuild2(0).get();
ResultFields fields = detectionService.getDetectedFields(build);
assertUFTFields(fields);
}
@Ignore
@Test
public void testUFTEndToEnd() throws Exception {
String projectName = "root-job-" + UUID.randomUUID().toString();
FreeStyleProject project = rule.createFreeStyleProject(projectName);
//TODO solve storing of example test
SubversionSCM scm = new SubversionSCM("http://localhost:8083/svn/selenium/branches/uft");
project.setScm(scm);
project.getBuildersList().add(new RunFromFileBuilder("Calculator"));
project.getPublishersList().add(new JUnitResultArchiver("Results*.xml"));
//this will actually run the UFT test
AbstractBuild build = TestUtils.runAndCheckBuild(project);
File mqmTestsXml = new File(build.getRootDir(), "mqmTests.xml");
ResultFieldsXmlReader xmlReader = new ResultFieldsXmlReader(new FileReader(mqmTestsXml));
TestResultContainer container = xmlReader.readXml();
assertUFTFields(container.getResultFields());
assertUFTTestAttributes(container.getTestAttributes());
}
private void assertUFTFields(ResultFields fields) {
Assert.assertNotNull(fields);
Assert.assertEquals("UFT", fields.getFramework());
Assert.assertEquals("UFT", fields.getTestingTool());
Assert.assertNull(fields.getTestLevel());
}
private void assertUFTTestAttributes(List<TestAttributes> testAttributes) {
for (TestAttributes test : testAttributes) {
Assert.assertTrue(test.getModuleName().isEmpty());
Assert.assertTrue(test.getPackageName().isEmpty());
Assert.assertTrue(test.getClassName().isEmpty());
Assert.assertTrue(!test.getTestName().isEmpty());
}
}
}
|
[
"\"TEMP\""
] |
[] |
[
"TEMP"
] |
[]
|
["TEMP"]
|
java
| 1 | 0 | |
build.go
|
package mri
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/Masterminds/semver"
"github.com/paketo-buildpacks/packit"
"github.com/paketo-buildpacks/packit/chronos"
"github.com/paketo-buildpacks/packit/pexec"
"github.com/paketo-buildpacks/packit/postal"
"github.com/paketo-buildpacks/packit/scribe"
)
//go:generate faux --interface EntryResolver --output fakes/entry_resolver.go
type EntryResolver interface {
Resolve(string, []packit.BuildpackPlanEntry, []interface{}) (packit.BuildpackPlanEntry, []packit.BuildpackPlanEntry)
MergeLayerTypes(string, []packit.BuildpackPlanEntry) (launch, build bool)
}
//go:generate faux --interface DependencyManager --output fakes/dependency_manager.go
type DependencyManager interface {
Resolve(path, id, version, stack string) (postal.Dependency, error)
Install(dependency postal.Dependency, cnbPath, layerPath string) error
GenerateBillOfMaterials(dependencies ...postal.Dependency) []packit.BOMEntry
}
//go:generate faux --interface Executable --output fakes/executable.go
type Executable interface {
Execute(pexec.Execution) error
}
func Build(entries EntryResolver, dependencies DependencyManager, logger scribe.Emitter, clock chronos.Clock, gem Executable) packit.BuildFunc {
return func(context packit.BuildContext) (packit.BuildResult, error) {
logger.Title("%s %s", context.BuildpackInfo.Name, context.BuildpackInfo.Version)
logger.Process("Resolving MRI version")
entry, allEntries := entries.Resolve("mri", context.Plan.Entries, []interface{}{"BP_MRI_VERSION", "buildpack.yml"})
logger.Candidates(allEntries)
// NOTE: this is to override that the dependency is called "ruby" in the
// buildpack.toml. We can remove this once we update our own dependencies
// and can name it however we like.
entry.Name = "ruby"
version, _ := entry.Metadata["version"].(string)
dependency, err := dependencies.Resolve(filepath.Join(context.CNBPath, "buildpack.toml"), entry.Name, version, context.Stack)
if err != nil {
return packit.BuildResult{}, err
}
// NOTE: this is to override that the dependency is called "ruby" in the
// buildpack.toml. We can remove this once we update our own dependencies
// and can name it however we like.
dependency.ID = "mri"
dependency.Name = "MRI"
logger.SelectedDependency(entry, dependency, clock.Now())
source, _ := entry.Metadata["version-source"].(string)
if source == "buildpack.yml" {
nextMajorVersion := semver.MustParse(context.BuildpackInfo.Version).IncMajor()
logger.Subprocess("WARNING: Setting the MRI version through buildpack.yml will be deprecated soon in MRI Buildpack v%s.", nextMajorVersion.String())
logger.Subprocess("Please specify the version through the $BP_MRI_VERSION environment variable instead. See README.md for more information.")
logger.Break()
}
mriLayer, err := context.Layers.Get(MRI)
if err != nil {
return packit.BuildResult{}, err
}
bom := dependencies.GenerateBillOfMaterials(dependency)
launch, build := entries.MergeLayerTypes("mri", context.Plan.Entries)
var buildMetadata packit.BuildMetadata
if build {
buildMetadata.BOM = bom
}
var launchMetadata packit.LaunchMetadata
if launch {
launchMetadata.BOM = bom
}
cachedSHA, ok := mriLayer.Metadata[DepKey].(string)
if ok && cachedSHA == dependency.SHA256 {
logger.Process("Reusing cached layer %s", mriLayer.Path)
logger.Break()
mriLayer.Launch, mriLayer.Build, mriLayer.Cache = launch, build, build
return packit.BuildResult{
Layers: []packit.Layer{mriLayer},
Build: buildMetadata,
Launch: launchMetadata,
}, nil
}
logger.Process("Executing build process")
mriLayer, err = mriLayer.Reset()
if err != nil {
return packit.BuildResult{}, err
}
mriLayer.Launch, mriLayer.Build, mriLayer.Cache = launch, build, build
logger.Subprocess("Installing MRI %s", dependency.Version)
duration, err := clock.Measure(func() error {
return dependencies.Install(dependency, context.CNBPath, mriLayer.Path)
})
if err != nil {
return packit.BuildResult{}, err
}
logger.Action("Completed in %s", duration.Round(time.Millisecond))
logger.Break()
mriLayer.Metadata = map[string]interface{}{
DepKey: dependency.SHA256,
"built_at": clock.Now().Format(time.RFC3339Nano),
}
os.Setenv("PATH", fmt.Sprintf("%s:%s", filepath.Join(mriLayer.Path, "bin"), os.Getenv("PATH")))
buffer := bytes.NewBuffer(nil)
err = gem.Execute(pexec.Execution{
Args: []string{"env", "path"},
Stdout: buffer,
})
if err != nil {
return packit.BuildResult{}, err
}
mriLayer.SharedEnv.Override("GEM_PATH", strings.TrimSpace(buffer.String()))
logger.EnvironmentVariables(mriLayer)
return packit.BuildResult{
Layers: []packit.Layer{mriLayer},
Build: buildMetadata,
Launch: launchMetadata,
}, nil
}
}
|
[
"\"PATH\""
] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
go
| 1 | 0 | |
226.invert-binary-tree.py
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is not None:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
common/oauth_client.py
|
import os
import urllib.parse
from datetime import timedelta
import flask
import requests
from cachetools import TTLCache
from flask import current_app, session, request, redirect, abort, jsonify
from flask_oauthlib.client import OAuth
from werkzeug import security
from urllib.parse import urlparse
from common.rpc.auth import get_endpoint
from common.rpc.secrets import get_secret
from common.url_for import get_host, url_for
AUTHORIZED_ROLES = ("staff", "instructor", "grader")
REDIRECT_KEY = "REDIRECT_KEY"
USER_CACHE = TTLCache(1000, timedelta(minutes=30).total_seconds())
def get_user():
"""Get some information on the currently logged in user.
:return: a dictionary representing user data (see
`here <https://okpy.github.io/documentation/ok-api.html#users-view-a-specific-user>`_
for an example)
"""
key = session.get("access_token")
if key in USER_CACHE:
data = USER_CACHE[key]
else:
data = current_app.remote.get("user")
# only cache if the access token is found
if key:
USER_CACHE[key] = data
return data.data["data"]
def is_logged_in():
"""Get whether the current user is logged into the current session.
:return: ``True`` if the user is logged in, ``False`` otherwise
"""
return "access_token" in session
def is_staff(course):
"""Get whether the current user is enrolled as staff, instructor, or grader
for ``course``.
:param course: the course code to check
:type course: str
:return: ``True`` if the user is on staff, ``False`` otherwise
"""
return is_enrolled(course, roles=AUTHORIZED_ROLES)
def is_enrolled(course, *, roles=None):
"""Check whether the current user is enrolled as any of the ``roles`` for
``course``.
:param course: the course code to check
:type course: str
:param roles: the roles to check for the user
:type roles: list-like
:return: ``True`` if the user is any of ``roles``, ``False`` otherwise
"""
try:
endpoint = get_endpoint(course=course)
for participation in get_user()["participations"]:
if roles and participation["role"] not in roles:
continue
if participation["course"]["offering"] != endpoint:
continue
return True
return False
except Exception as e:
# fail safe!
print(e)
return False
def login():
"""Store the current URL as the redirect target on success, then redirect
to the login endpoint for the current app.
:return: a :func:`~flask.redirect` to the login endpoint for the current
:class:`~flask.Flask` app.
"""
session[REDIRECT_KEY] = urlparse(request.url)._replace(netloc=get_host()).geturl()
return redirect(url_for("login"))
def create_oauth_client(
app: flask.Flask,
consumer_key,
secret_key=None,
success_callback=None,
return_response=None,
):
"""Add Okpy OAuth for ``consumer_key`` to the current ``app``.
Specifically, adds an endpoint ``/oauth/login`` that redirects to the Okpy
login process, ``/oauth/authorized`` that receives the successful result
of authentication, ``/api/user`` that acts as a test endpoint, and a
:meth:`~flask_oauthlib.client.OAuthRemoteApp.tokengetter`.
:param app: the app to add OAuth endpoints to
:type app: ~flask.Flask
:param consumer_key: the OAuth client consumer key
:type consumer_key: str
:param secret_key: the OAuth client secret, inferred using
:func:`~common.rpc.secrets.get_secret` if omitted
:type secret_key: str
:param success_callback: an optional function to call upon login
:type success_callback: func
:param return_response: an optional function to send the OAuth response to
:type return_response: func
"""
oauth = OAuth(app)
if os.getenv("ENV") == "prod":
if secret_key is None:
app.secret_key = get_secret(secret_name="OKPY_OAUTH_SECRET")
else:
app.secret_key = secret_key
else:
consumer_key = "local-dev-all"
app.secret_key = "kmSPJYPzKJglOOOmr7q0irMfBVMRFXN"
if not app.debug:
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
)
remote = oauth.remote_app(
"ok-server", # Server Name
consumer_key=consumer_key,
consumer_secret=app.secret_key,
request_token_params={"scope": "all", "state": lambda: security.gen_salt(10)},
base_url="https://okpy.org/api/v3/",
request_token_url=None,
access_token_method="POST",
access_token_url="https://okpy.org/oauth/token",
authorize_url="https://okpy.org/oauth/authorize",
)
def check_req(uri, headers, body):
"""Add access_token to the URL Request."""
if "access_token" not in uri and session.get("access_token"):
params = {"access_token": session.get("access_token")[0]}
url_parts = list(urllib.parse.urlparse(uri))
query = dict(urllib.parse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urllib.parse.urlencode(query)
uri = urllib.parse.urlunparse(url_parts)
return uri, headers, body
remote.pre_request = check_req
@app.route("/oauth/login")
def login():
if app.debug:
response = remote.authorize(callback=url_for("authorized", _external=True))
else:
response = remote.authorize(
url_for("authorized", _external=True, _scheme="https")
)
return response
@app.route("/oauth/authorized")
def authorized():
resp = remote.authorized_response()
if resp is None:
return "Access denied: error=%s" % (request.args["error"])
if isinstance(resp, dict) and "access_token" in resp:
session["access_token"] = (resp["access_token"], "")
if return_response:
return_response(resp)
if success_callback:
success_callback()
target = session.get(REDIRECT_KEY)
if target:
session.pop(REDIRECT_KEY)
return redirect(target)
return redirect(url_for("index"))
@app.route("/api/user", methods=["POST"])
def client_method():
if "access_token" not in session:
abort(401)
token = session["access_token"][0]
r = requests.get("https://okpy.org/api/v3/user/?access_token={}".format(token))
if not r.ok:
abort(401)
return jsonify(r.json())
@remote.tokengetter
def get_oauth_token():
return session.get("access_token")
app.remote = remote
|
[] |
[] |
[
"ENV"
] |
[]
|
["ENV"]
|
python
| 1 | 0 | |
vendor/code.cloudfoundry.org/cli/command/v2/delete_space_command.go
|
package v2
import (
"os"
"code.cloudfoundry.org/cli/cf/cmd"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
)
type DeleteSpaceCommand struct {
RequiredArgs flag.Space `positional-args:"yes"`
Force bool `short:"f" description:"Force deletion without confirmation"`
Org string `short:"o" description:"Delete space within specified org"`
usage interface{} `usage:"CF_NAME delete-space SPACE [-o ORG] [-f]"`
}
func (_ DeleteSpaceCommand) Setup(config command.Config, ui command.UI) error {
return nil
}
func (_ DeleteSpaceCommand) Execute(args []string) error {
cmd.Main(os.Getenv("CF_TRACE"), os.Args)
return nil
}
|
[
"\"CF_TRACE\""
] |
[] |
[
"CF_TRACE"
] |
[]
|
["CF_TRACE"]
|
go
| 1 | 0 | |
python/jimmy_plot/deprecated/front_end_preds/auc.py
|
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import util
from statistics import mean
from enum import Enum
#PARAMETERS
HOME = os.environ['HOME']
PREDICTOR = 'HarvardPowerPredictor_1'
CLASS = 'DESKTOP'
TEST = 'crc'
path = HOME + '/output_11_6/gem5_out/' + CLASS + '_' + PREDICTOR + '/' + TEST + '.txt'
#PARAMETERS
SIG_SWEEP = 500
hit_auc = []
false_positive_auc = []
false_negative_auc = []
xvar_auc = []
false_pos_x_auc=[]
for i in range(3,SIG_SWEEP,10):
SIGNATURE_LENGTH = i
stats = open(path, 'r')
harvard = util.Harvard(TABLE_HEIGHT=128,SIGNATURE_LENGTH=SIGNATURE_LENGTH,HYSTERESIS=0.005,EMERGENCY_V=1.358)
cycle_dump = util.Cycle_Dump(stats)
action = [False]
VE = [False]
while True:
cycle_dump.reset()
EOF = cycle_dump.parseCycle()
harvard.tick(cycle_dump)
if EOF:
break
VE.append(False)
VE.append(harvard.VEflag)
action.append(harvard.prev_cycle_predict != -1)
action.append(harvard.curr_cycle_predict != -1)
xvar,hits,false_neg,false_pos_x,false_pos = util.accuracy(action,VE, LEAD_TIME_CAP=50)
hit_auc.append(hits)
false_positive_auc.append(false_pos)
false_negative_auc.append(false_neg)
xvar_auc.append(xvar)
false_pos_x_auc.append(false_pos_x)
xvar_max = max([max(i) for i in xvar_auc])
false_pos_x_auc_max = max([max(i) for i in false_pos_x_auc])
for i in range(len(xvar_auc)):
if len(hit_auc[i]) < xvar_max:
hit_auc[i].extend([hit_auc[i][-1]] * (xvar_max-len(hit_auc[i])))
if len(false_negative_auc[i]) < xvar_max:
false_negative_auc[i].extend([false_negative_auc[i][-1]] * (xvar_max-len(false_negative_auc[i])))
if len(false_positive_auc[i]) < false_pos_x_auc_max:
false_positive_auc[i].extend([false_positive_auc[i][-1]] * (false_pos_x_auc_max-len(false_positive_auc[i])))
for i in range(len(xvar_auc)):
hit_auc[i] = sum(hit_auc[i])/xvar_max
false_negative_auc[i] = sum(false_negative_auc[i])/xvar_max
false_positive_auc[i] = sum(false_positive_auc[i])/false_pos_x_auc_max
f, ax1 = plt.subplots()
f.set_size_inches(10.5, 13.5)
xvar,hits,false_neg,false_pos_x,false_pos = util.accuracy(action,VE, LEAD_TIME_CAP=50)
hit_auc = [x - mean(hit_auc) for x in hit_auc]
false_negative_auc = [x - mean(false_negative_auc) for x in false_negative_auc]
false_positive_auc = [x - mean(false_positive_auc) for x in false_positive_auc]
#ax1.set_xlim([0,max(xvar)])
ax1.plot(range(3,SIG_SWEEP,10), hit_auc, color='black', linewidth=1.0, label='hits')
ax1.plot(range(3,SIG_SWEEP,10), false_negative_auc, color='red', linewidth=1.0, label='false negatives')
ax1.plot(range(3,SIG_SWEEP,10), false_positive_auc, color='blue', linewidth=1.0, label='false positives')
ax1.legend()
ax1.set_title('AUC over Signature Length' + '(' + PREDICTOR + ', ' + CLASS + ', ' + TEST + str(len(VE)) +')', fontsize=14)
ax1.set_xlabel('Signature Length', fontsize=14)
plt.savefig(HOME+'/plot/11-4_auc' + '_' + PREDICTOR + '_' + CLASS + '_' + TEST +'.png')
|
[] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
python
| 1 | 0 | |
libgo/go/runtime/crash_test.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime_test
import (
"bytes"
"flag"
"fmt"
"internal/testenv"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
)
var toRemove []string
func TestMain(m *testing.M) {
status := m.Run()
for _, file := range toRemove {
os.RemoveAll(file)
}
os.Exit(status)
}
var testprog struct {
sync.Mutex
dir string
target map[string]buildexe
}
type buildexe struct {
exe string
err error
}
func runTestProg(t *testing.T, binary, name string, env ...string) string {
if *flagQuick {
t.Skip("-quick")
}
testenv.MustHaveGoBuild(t)
exe, err := buildTestProg(t, binary)
if err != nil {
t.Fatal(err)
}
cmd := testenv.CleanCmdEnv(exec.Command(exe, name))
cmd.Env = append(cmd.Env, env...)
if testing.Short() {
cmd.Env = append(cmd.Env, "RUNTIME_TEST_SHORT=1")
}
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b
if err := cmd.Start(); err != nil {
t.Fatalf("starting %s %s: %v", binary, name, err)
}
// If the process doesn't complete within 1 minute,
// assume it is hanging and kill it to get a stack trace.
p := cmd.Process
done := make(chan bool)
go func() {
scale := 1
// This GOARCH/GOOS test is copied from cmd/dist/test.go.
// TODO(iant): Have cmd/dist update the environment variable.
if runtime.GOARCH == "arm" || runtime.GOOS == "windows" {
scale = 2
}
if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
if sc, err := strconv.Atoi(s); err == nil {
scale = sc
}
}
select {
case <-done:
case <-time.After(time.Duration(scale) * time.Minute):
p.Signal(sigquit)
}
}()
if err := cmd.Wait(); err != nil {
t.Logf("%s %s exit status: %v", binary, name, err)
}
close(done)
return b.String()
}
func buildTestProg(t *testing.T, binary string, flags ...string) (string, error) {
if *flagQuick {
t.Skip("-quick")
}
checkStaleRuntime(t)
testprog.Lock()
defer testprog.Unlock()
if testprog.dir == "" {
dir, err := ioutil.TempDir("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
testprog.dir = dir
toRemove = append(toRemove, dir)
}
if testprog.target == nil {
testprog.target = make(map[string]buildexe)
}
name := binary
if len(flags) > 0 {
name += "_" + strings.Join(flags, "_")
}
target, ok := testprog.target[name]
if ok {
return target.exe, target.err
}
exe := filepath.Join(testprog.dir, name+".exe")
cmd := exec.Command(testenv.GoToolPath(t), append([]string{"build", "-o", exe}, flags...)...)
cmd.Dir = "testdata/" + binary
out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
if err != nil {
target.err = fmt.Errorf("building %s %v: %v\n%s", binary, flags, err, out)
testprog.target[name] = target
return "", target.err
}
target.exe = exe
testprog.target[name] = target
return exe, nil
}
var (
staleRuntimeOnce sync.Once // guards init of staleRuntimeErr
staleRuntimeErr error
)
func checkStaleRuntime(t *testing.T) {
staleRuntimeOnce.Do(func() {
if runtime.Compiler == "gccgo" {
return
}
// 'go run' uses the installed copy of runtime.a, which may be out of date.
out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.Stale}}", "runtime")).CombinedOutput()
if err != nil {
staleRuntimeErr = fmt.Errorf("failed to execute 'go list': %v\n%v", err, string(out))
return
}
if string(out) != "false\n" {
t.Logf("go list -f {{.Stale}} runtime:\n%s", out)
out, err := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "list", "-gcflags=all="+os.Getenv("GO_GCFLAGS"), "-f", "{{.StaleReason}}", "runtime")).CombinedOutput()
if err != nil {
t.Logf("go list -f {{.StaleReason}} failed: %v", err)
}
t.Logf("go list -f {{.StaleReason}} runtime:\n%s", out)
staleRuntimeErr = fmt.Errorf("Stale runtime.a. Run 'go install runtime'.")
}
})
if staleRuntimeErr != nil {
t.Fatal(staleRuntimeErr)
}
}
func testCrashHandler(t *testing.T, cgo bool) {
type crashTest struct {
Cgo bool
}
var output string
if cgo {
output = runTestProg(t, "testprogcgo", "Crash")
} else {
output = runTestProg(t, "testprog", "Crash")
}
want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
if output != want {
t.Fatalf("output:\n%s\n\nwanted:\n%s", output, want)
}
}
func TestCrashHandler(t *testing.T) {
testCrashHandler(t, false)
}
func testDeadlock(t *testing.T, name string) {
output := runTestProg(t, "testprog", name)
want := "fatal error: all goroutines are asleep - deadlock!\n"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestSimpleDeadlock(t *testing.T) {
testDeadlock(t, "SimpleDeadlock")
}
func TestInitDeadlock(t *testing.T) {
testDeadlock(t, "InitDeadlock")
}
func TestLockedDeadlock(t *testing.T) {
testDeadlock(t, "LockedDeadlock")
}
func TestLockedDeadlock2(t *testing.T) {
testDeadlock(t, "LockedDeadlock2")
}
func TestGoexitDeadlock(t *testing.T) {
output := runTestProg(t, "testprog", "GoexitDeadlock")
want := "no goroutines (main called runtime.Goexit) - deadlock!"
if !strings.Contains(output, want) {
t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
}
}
func TestStackOverflow(t *testing.T) {
if runtime.Compiler == "gccgo" {
t.Skip("gccgo does not do stack overflow checking")
}
output := runTestProg(t, "testprog", "StackOverflow")
want := "runtime: goroutine stack exceeds 1474560-byte limit\nfatal error: stack overflow"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestThreadExhaustion(t *testing.T) {
output := runTestProg(t, "testprog", "ThreadExhaustion")
want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestRecursivePanic(t *testing.T) {
output := runTestProg(t, "testprog", "RecursivePanic")
want := `wrap: bad
panic: again
`
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestGoexitCrash(t *testing.T) {
output := runTestProg(t, "testprog", "GoexitExit")
want := "no goroutines (main called runtime.Goexit) - deadlock!"
if !strings.Contains(output, want) {
t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
}
}
func TestGoexitDefer(t *testing.T) {
c := make(chan struct{})
go func() {
defer func() {
r := recover()
if r != nil {
t.Errorf("non-nil recover during Goexit")
}
c <- struct{}{}
}()
runtime.Goexit()
}()
// Note: if the defer fails to run, we will get a deadlock here
<-c
}
func TestGoNil(t *testing.T) {
output := runTestProg(t, "testprog", "GoNil")
want := "go of nil func value"
if !strings.Contains(output, want) {
t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
}
}
func TestMainGoroutineID(t *testing.T) {
output := runTestProg(t, "testprog", "MainGoroutineID")
want := "panic: test\n\ngoroutine 1 [running]:\n"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestNoHelperGoroutines(t *testing.T) {
output := runTestProg(t, "testprog", "NoHelperGoroutines")
matches := regexp.MustCompile(`goroutine [0-9]+ \[`).FindAllStringSubmatch(output, -1)
if len(matches) != 1 || matches[0][0] != "goroutine 1 [" {
t.Fatalf("want to see only goroutine 1, see:\n%s", output)
}
}
func TestBreakpoint(t *testing.T) {
output := runTestProg(t, "testprog", "Breakpoint")
// If runtime.Breakpoint() is inlined, then the stack trace prints
// "runtime.Breakpoint(...)" instead of "runtime.Breakpoint()".
// For gccgo, no parens.
want := "runtime.Breakpoint"
if !strings.Contains(output, want) {
t.Fatalf("output:\n%s\n\nwant output containing: %s", output, want)
}
}
func TestGoexitInPanic(t *testing.T) {
// see issue 8774: this code used to trigger an infinite recursion
output := runTestProg(t, "testprog", "GoexitInPanic")
want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
// Issue 14965: Runtime panics should be of type runtime.Error
func TestRuntimePanicWithRuntimeError(t *testing.T) {
testCases := [...]func(){
0: func() {
var m map[uint64]bool
m[1234] = true
},
1: func() {
ch := make(chan struct{})
close(ch)
close(ch)
},
2: func() {
var ch = make(chan struct{})
close(ch)
ch <- struct{}{}
},
3: func() {
var s = make([]int, 2)
_ = s[2]
},
4: func() {
n := -1
_ = make(chan bool, n)
},
5: func() {
close((chan bool)(nil))
},
}
for i, fn := range testCases {
got := panicValue(fn)
if _, ok := got.(runtime.Error); !ok {
t.Errorf("test #%d: recovered value %v(type %T) does not implement runtime.Error", i, got, got)
}
}
}
func panicValue(fn func()) (recovered interface{}) {
defer func() {
recovered = recover()
}()
fn()
return
}
func TestPanicAfterGoexit(t *testing.T) {
// an uncaught panic should still work after goexit
output := runTestProg(t, "testprog", "PanicAfterGoexit")
want := "panic: hello"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestRecoveredPanicAfterGoexit(t *testing.T) {
output := runTestProg(t, "testprog", "RecoveredPanicAfterGoexit")
want := "fatal error: no goroutines (main called runtime.Goexit) - deadlock!"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestRecoverBeforePanicAfterGoexit(t *testing.T) {
// 1. defer a function that recovers
// 2. defer a function that panics
// 3. call goexit
// Goexit should run the #2 defer. Its panic
// should be caught by the #1 defer, and execution
// should resume in the caller. Like the Goexit
// never happened!
defer func() {
r := recover()
if r == nil {
panic("bad recover")
}
}()
defer func() {
panic("hello")
}()
runtime.Goexit()
}
func TestNetpollDeadlock(t *testing.T) {
t.Parallel()
output := runTestProg(t, "testprognet", "NetpollDeadlock")
want := "done\n"
if !strings.HasSuffix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestPanicTraceback(t *testing.T) {
t.Parallel()
output := runTestProg(t, "testprog", "PanicTraceback")
want := "panic: hello"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
// Check functions in the traceback.
fns := []string{"main.pt1.func1", "panic", "main.pt2.func1", "panic", "main.pt2", "main.pt1"}
if runtime.Compiler == "gccgo" {
fns = []string{"main.pt1..func1", "panic", "main.pt2..func1", "panic", "main.pt2", "main.pt1"}
}
for _, fn := range fns {
var re *regexp.Regexp
if runtime.Compiler != "gccgo" {
re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `\(.*\n`)
} else {
re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(fn) + `.*\n`)
}
idx := re.FindStringIndex(output)
if idx == nil {
t.Fatalf("expected %q function in traceback:\n%s", fn, output)
}
output = output[idx[1]:]
}
}
func testPanicDeadlock(t *testing.T, name string, want string) {
// test issue 14432
output := runTestProg(t, "testprog", name)
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestPanicDeadlockGosched(t *testing.T) {
testPanicDeadlock(t, "GoschedInPanic", "panic: errorThatGosched\n\n")
}
func TestPanicDeadlockSyscall(t *testing.T) {
testPanicDeadlock(t, "SyscallInPanic", "1\n2\npanic: 3\n\n")
}
func TestPanicLoop(t *testing.T) {
output := runTestProg(t, "testprog", "PanicLoop")
if want := "panic while printing panic value"; !strings.Contains(output, want) {
t.Errorf("output does not contain %q:\n%s", want, output)
}
}
func TestMemPprof(t *testing.T) {
testenv.MustHaveGoRun(t)
if runtime.Compiler == "gccgo" {
t.Skip("gccgo may not have the pprof tool")
}
exe, err := buildTestProg(t, "testprog")
if err != nil {
t.Fatal(err)
}
got, err := testenv.CleanCmdEnv(exec.Command(exe, "MemProf")).CombinedOutput()
if err != nil {
t.Fatal(err)
}
fn := strings.TrimSpace(string(got))
defer os.Remove(fn)
for try := 0; try < 2; try++ {
cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-alloc_space", "-top"))
// Check that pprof works both with and without explicit executable on command line.
if try == 0 {
cmd.Args = append(cmd.Args, exe, fn)
} else {
cmd.Args = append(cmd.Args, fn)
}
found := false
for i, e := range cmd.Env {
if strings.HasPrefix(e, "PPROF_TMPDIR=") {
cmd.Env[i] = "PPROF_TMPDIR=" + os.TempDir()
found = true
break
}
}
if !found {
cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
}
top, err := cmd.CombinedOutput()
t.Logf("%s:\n%s", cmd.Args, top)
if err != nil {
t.Error(err)
} else if !bytes.Contains(top, []byte("MemProf")) {
t.Error("missing MemProf in pprof output")
}
}
}
var concurrentMapTest = flag.Bool("run_concurrent_map_tests", false, "also run flaky concurrent map tests")
func TestConcurrentMapWrites(t *testing.T) {
if !*concurrentMapTest {
t.Skip("skipping without -run_concurrent_map_tests")
}
testenv.MustHaveGoRun(t)
output := runTestProg(t, "testprog", "concurrentMapWrites")
want := "fatal error: concurrent map writes"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestConcurrentMapReadWrite(t *testing.T) {
if !*concurrentMapTest {
t.Skip("skipping without -run_concurrent_map_tests")
}
testenv.MustHaveGoRun(t)
output := runTestProg(t, "testprog", "concurrentMapReadWrite")
want := "fatal error: concurrent map read and map write"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
func TestConcurrentMapIterateWrite(t *testing.T) {
if !*concurrentMapTest {
t.Skip("skipping without -run_concurrent_map_tests")
}
testenv.MustHaveGoRun(t)
output := runTestProg(t, "testprog", "concurrentMapIterateWrite")
want := "fatal error: concurrent map iteration and map write"
if !strings.HasPrefix(output, want) {
t.Fatalf("output does not start with %q:\n%s", want, output)
}
}
type point struct {
x, y *int
}
func (p *point) negate() {
*p.x = *p.x * -1
*p.y = *p.y * -1
}
// Test for issue #10152.
func TestPanicInlined(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Fatalf("recover failed")
}
buf := make([]byte, 2048)
n := runtime.Stack(buf, false)
buf = buf[:n]
want := []byte("(*point).negate(")
if runtime.Compiler == "gccgo" {
want = []byte("point.negate")
}
if !bytes.Contains(buf, want) {
t.Logf("%s", buf)
t.Fatalf("expecting stack trace to contain call to %s", want)
}
}()
pt := new(point)
pt.negate()
}
// Test for issues #3934 and #20018.
// We want to delay exiting until a panic print is complete.
func TestPanicRace(t *testing.T) {
testenv.MustHaveGoRun(t)
exe, err := buildTestProg(t, "testprog")
if err != nil {
t.Fatal(err)
}
// The test is intentionally racy, and in my testing does not
// produce the expected output about 0.05% of the time.
// So run the program in a loop and only fail the test if we
// get the wrong output ten times in a row.
const tries = 10
retry:
for i := 0; i < tries; i++ {
got, err := testenv.CleanCmdEnv(exec.Command(exe, "PanicRace")).CombinedOutput()
if err == nil {
t.Logf("try %d: program exited successfully, should have failed", i+1)
continue
}
if i > 0 {
t.Logf("try %d:\n", i+1)
}
t.Logf("%s\n", got)
wants := []string{
"panic: crash",
"PanicRace",
"created by ",
}
if runtime.Compiler == "gccgo" {
// gccgo will dump a function name like main.$nested30.
// Match on the file name instead.
wants[1] = "panicrace"
}
for _, want := range wants {
if !bytes.Contains(got, []byte(want)) {
t.Logf("did not find expected string %q", want)
continue retry
}
}
// Test generated expected output.
return
}
t.Errorf("test ran %d times without producing expected output", tries)
}
func TestBadTraceback(t *testing.T) {
if runtime.Compiler == "gccgo" {
t.Skip("gccgo does not do a hex dump")
}
output := runTestProg(t, "testprog", "BadTraceback")
for _, want := range []string{
"runtime: unexpected return pc",
"called from 0xbad",
"00000bad", // Smashed LR in hex dump
"<main.badLR", // Symbolization in hex dump (badLR1 or badLR2)
} {
if !strings.Contains(output, want) {
t.Errorf("output does not contain %q:\n%s", want, output)
}
}
}
func TestTimePprof(t *testing.T) {
if runtime.Compiler == "gccgo" {
t.Skip("gccgo may not have the pprof tool")
}
fn := runTestProg(t, "testprog", "TimeProf")
fn = strings.TrimSpace(fn)
defer os.Remove(fn)
cmd := testenv.CleanCmdEnv(exec.Command(testenv.GoToolPath(t), "tool", "pprof", "-top", "-nodecount=1", fn))
cmd.Env = append(cmd.Env, "PPROF_TMPDIR="+os.TempDir())
top, err := cmd.CombinedOutput()
t.Logf("%s", top)
if err != nil {
t.Error(err)
} else if bytes.Contains(top, []byte("ExternalCode")) {
t.Error("profiler refers to ExternalCode")
}
}
// Test that runtime.abort does so.
func TestAbort(t *testing.T) {
// Pass GOTRACEBACK to ensure we get runtime frames.
output := runTestProg(t, "testprog", "Abort", "GOTRACEBACK=system")
if want := "runtime.abort"; !strings.Contains(output, want) {
t.Errorf("output does not contain %q:\n%s", want, output)
}
if strings.Contains(output, "BAD") {
t.Errorf("output contains BAD:\n%s", output)
}
// Check that it's a signal traceback.
want := "PC="
// For systems that use a breakpoint, check specifically for that.
if runtime.Compiler == "gc" {
switch runtime.GOARCH {
case "386", "amd64":
switch runtime.GOOS {
case "plan9":
want = "sys: breakpoint"
case "windows":
want = "Exception 0x80000003"
default:
want = "SIGTRAP"
}
}
}
if !strings.Contains(output, want) {
t.Errorf("output does not contain %q:\n%s", want, output)
}
}
// For TestRuntimePanic: test a panic in the runtime package without
// involving the testing harness.
func init() {
if os.Getenv("GO_TEST_RUNTIME_PANIC") == "1" {
defer func() {
if r := recover(); r != nil {
// We expect to crash, so exit 0
// to indicate failure.
os.Exit(0)
}
}()
runtime.PanicForTesting(nil, 1)
// We expect to crash, so exit 0 to indicate failure.
os.Exit(0)
}
}
func TestRuntimePanic(t *testing.T) {
testenv.MustHaveExec(t)
cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestRuntimePanic"))
cmd.Env = append(cmd.Env, "GO_TEST_RUNTIME_PANIC=1")
out, err := cmd.CombinedOutput()
t.Logf("%s", out)
if err == nil {
t.Error("child process did not fail")
} else if want := "runtime.unexportedPanicForTesting"; !bytes.Contains(out, []byte(want)) {
t.Errorf("output did not contain expected string %q", want)
}
}
// Test that g0 stack overflows are handled gracefully.
func TestG0StackOverflow(t *testing.T) {
testenv.MustHaveExec(t)
switch runtime.GOOS {
case "darwin", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "android":
t.Skipf("g0 stack is wrong on pthread platforms (see golang.org/issue/26061)")
}
if os.Getenv("TEST_G0_STACK_OVERFLOW") != "1" {
cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestG0StackOverflow", "-test.v"))
cmd.Env = append(cmd.Env, "TEST_G0_STACK_OVERFLOW=1")
out, err := cmd.CombinedOutput()
// Don't check err since it's expected to crash.
if n := strings.Count(string(out), "morestack on g0\n"); n != 1 {
t.Fatalf("%s\n(exit status %v)", out, err)
}
// Check that it's a signal-style traceback.
if runtime.GOOS != "windows" {
if want := "PC="; !strings.Contains(string(out), want) {
t.Errorf("output does not contain %q:\n%s", want, out)
}
}
return
}
runtime.G0StackOverflow()
}
|
[
"\"GO_TEST_TIMEOUT_SCALE\"",
"\"GO_GCFLAGS\"",
"\"GO_GCFLAGS\"",
"\"GO_TEST_RUNTIME_PANIC\"",
"\"TEST_G0_STACK_OVERFLOW\""
] |
[] |
[
"GO_GCFLAGS",
"GO_TEST_TIMEOUT_SCALE",
"GO_TEST_RUNTIME_PANIC",
"TEST_G0_STACK_OVERFLOW"
] |
[]
|
["GO_GCFLAGS", "GO_TEST_TIMEOUT_SCALE", "GO_TEST_RUNTIME_PANIC", "TEST_G0_STACK_OVERFLOW"]
|
go
| 4 | 0 | |
build/mage/release/formula.go
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package release
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"os"
"strings"
"text/template"
"github.com/elastic/harp/build/artifact"
)
var formulaTemplate = strings.TrimSpace(`# typed: false
# frozen_string_literal: true
# Code generated by Harp build tool
class {{ .Formula }} < Formula
desc "{{ .Description }}"
homepage "https://{{ .Repository }}"
license "Apache-2.0"
stable do
on_macos do
if Hardware::CPU.intel?
url "https://{{ .Repository }}/releases/download/cmd%2F{{ .Bin }}%2F{{ .Release }}/{{ .Bin }}-darwin-amd64-{{ .Release }}.tar.xz"
sha256 "{{ sha256file (printf "dist/%s-darwin-amd64-%s.tar.xz" .Bin .Release) }}"
elsif Hardware::CPU.arm?
url "https://{{ .Repository }}/releases/download/cmd%2F{{ .Bin }}%2F{{ .Release }}/{{ .Bin }}-darwin-arm64-{{ .Release }}.tar.xz"
sha256 "{{ sha256file (printf "dist/%s-darwin-arm64-%s.tar.xz" .Bin .Release) }}"
end
end
on_linux do
if Hardware::CPU.intel?
if Hardware::CPU.is_64_bit?
url "https://{{ .Repository }}/releases/download/cmd%2F{{ .Bin }}%2F{{ .Release }}/{{ .Bin }}-linux-amd64-{{ .Release }}.tar.xz"
sha256 "{{ sha256file (printf "dist/%s-linux-amd64-%s.tar.xz" .Bin .Release) }}"
end
elsif Hardware::CPU.arm?
if Hardware::CPU.is_64_bit?
url "https://{{ .Repository }}/releases/download/cmd%2F{{ .Bin }}%2F{{ .Release }}/{{ .Bin }}-linux-arm64-{{ .Release }}.tar.xz"
sha256 "{{ sha256file (printf "dist/%s-linux-arm64-%s.tar.xz" .Bin .Release) }}"
else
url "https://{{ .Repository }}/releases/download/cmd%2F{{ .Bin }}%2F{{ .Release }}/{{ .Bin }}-linux-arm7-{{ .Release }}.tar.xz"
sha256 "{{ sha256file (printf "dist/%s-linux-arm7-%s.tar.xz" .Bin .Release) }}"
end
end
end
end
# Source definition
head do
url "https://{{ .Repository }}.git", :branch => "main"
# build dependencies
depends_on "go" => :build
depends_on "mage" => :build
end
def install
ENV.deparallelize
if build.head?
# Prepare build environment
ENV["GOPATH"] = buildpath
(buildpath/"src/{{ .Repository }}").install Dir["{*,.git,.gitignore}"]
# Mage tools
ENV.prepend_path "PATH", buildpath/"tools/bin"
# In {{ .Repository }} command
cd "src/{{ .Repository }}/cmd/{{ .Bin }}" do
system "go", "mod", "vendor"
system "mage", "compile"
end
# Install builded command
cd "src/{{ .Repository }}/cmd/{{ .Bin }}/bin" do
# Install binaries
if OS.mac? && Hardware::CPU.arm?
bin.install "{{ .Bin }}-darwin-arm64" => "{{ .Bin }}"
elsif OS.mac?
bin.install "{{ .Bin }}-darwin-amd64" => "{{ .Bin }}"
elsif OS.linux?
bin.install "{{ .Bin }}-linux-amd64" => "{{ .Bin }}"
end
end
elsif OS.mac? && Hardware::CPU.arm?
# Install binaries
bin.install "{{ .Bin }}-darwin-arm64" => "{{ .Bin }}"
elsif OS.mac?
bin.install "{{ .Bin }}-darwin-amd64" => "{{ .Bin }}"
elsif OS.linux?
bin.install "{{ .Bin }}-linux-amd64" => "{{ .Bin }}"
end
# Final message
ohai "Install success!"
end
def caveats
<<~EOS
If you have previously built {{ .Bin }} from source, make sure you're not using
$GOPATH/bin/{{ .Bin }} instead of this one. If that's the case you can simply run
rm -f $GOPATH/bin/{{ .Bin }}
EOS
end
test do
assert_match version.to_s, shell_output("#{bin}/{{ .Bin }} version")
end
end
`)
type formulaModel struct {
Repository string
Bin string
Formula string
Description string
Release string
}
// HomebrewFormula generates HomeBrew formula for given command.
func HomebrewFormula(cmd *artifact.Command) func() error {
sha256sum := func(filename string) (string, error) {
// Open file
f, err := os.Open(filename)
if err != nil {
return "", err
}
// Prepare hasher
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
// No error
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
return func() error {
// Compile template
formulaTpl, err := template.New("Formula").Funcs(map[string]interface{}{
"sha256file": sha256sum,
}).Parse(formulaTemplate)
if err != nil {
return err
}
// Merge data
var buf bytes.Buffer
if errTmpl := formulaTpl.Execute(&buf, &formulaModel{
Repository: cmd.Package,
Bin: cmd.Kebab(),
Formula: cmd.Camel(),
Description: cmd.Description,
Release: os.Getenv("RELEASE"),
}); errTmpl != nil {
return errTmpl
}
// Write output to Stdout
_, errWrite := buf.WriteTo(os.Stdout)
return errWrite
}
}
|
[
"\"RELEASE\""
] |
[] |
[
"RELEASE"
] |
[]
|
["RELEASE"]
|
go
| 1 | 0 | |
scripts/report_gen.py
|
#!/usr/bin/env python3
# Copyright 2019, Alex Wiens <[email protected]>, Achim Lösch <[email protected]>
# SPDX-License-Identifier: BSD-2-Clause
import os
import os.path
import subprocess
import test as schedtest
import plot
def hostname():
return subprocess.getoutput("hostname")
if __name__ == "__main__":
cwd = os.getcwd()
testname = os.path.basename(cwd)
host = os.environ if "SCHED_HOST" in os.environ else hostname()
for testtype in ["sim","exp"]:
test = schedtest.SchedTest.loadTest(testtype, testname=testname, resultdir=cwd, host=host)
if test != None and test.loadTestLog():
test.generate_report()
else:
print("log for",testtype,"not found")
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.conf;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.ZooKeeperHiveHelper;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceAudience.LimitedPrivate;
import org.apache.hadoop.hive.common.type.TimestampTZUtil;
import org.apache.hadoop.hive.conf.Validator.PatternSet;
import org.apache.hadoop.hive.conf.Validator.RangeValidator;
import org.apache.hadoop.hive.conf.Validator.RatioValidator;
import org.apache.hadoop.hive.conf.Validator.SizeValidator;
import org.apache.hadoop.hive.conf.Validator.StringSet;
import org.apache.hadoop.hive.conf.Validator.TimeValidator;
import org.apache.hadoop.hive.conf.Validator.WritableDirectoryValidator;
import org.apache.hadoop.hive.shims.ShimLoader;
import org.apache.hadoop.hive.shims.Utils;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hive.common.HiveCompat;
import org.apache.hive.common.util.SuppressFBWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Hive Configuration.
*/
public class HiveConf extends Configuration {
protected String hiveJar;
protected Properties origProp;
protected String auxJars;
private static final Logger LOG = LoggerFactory.getLogger(HiveConf.class);
private static boolean loadMetastoreConfig = false;
private static boolean loadHiveServer2Config = false;
private static URL hiveDefaultURL = null;
private static URL hiveSiteURL = null;
private static URL hivemetastoreSiteUrl = null;
private static URL hiveServer2SiteUrl = null;
private static byte[] confVarByteArray = null;
private static final Map<String, ConfVars> vars = new HashMap<String, ConfVars>();
private static final Map<String, ConfVars> metaConfs = new HashMap<String, ConfVars>();
private final List<String> restrictList = new ArrayList<String>();
private final Set<String> hiddenSet = new HashSet<String>();
private final List<String> rscList = new ArrayList<>();
private Pattern modWhiteListPattern = null;
private volatile boolean isSparkConfigUpdated = false;
private static final int LOG_PREFIX_LENGTH = 64;
public enum ResultFileFormat {
INVALID_FORMAT {
@Override
public String toString() {
return "invalid result file format";
}
},
TEXTFILE {
@Override
public String toString() {
return "TextFile";
}
},
SEQUENCEFILE {
@Override
public String toString() {
return "SequenceFile";
}
},
RCFILE {
@Override
public String toString() {
return "RCfile";
}
},
LLAP {
@Override
public String toString() {
return "Llap";
}
};
public static ResultFileFormat getInvalid() {
return INVALID_FORMAT;
}
public static EnumSet<ResultFileFormat> getValidSet() {
return EnumSet.complementOf(EnumSet.of(getInvalid()));
}
public static ResultFileFormat from(String value) {
try {
return valueOf(value.toUpperCase());
} catch (Exception e) {
return getInvalid();
}
}
}
public ResultFileFormat getResultFileFormat() {
return ResultFileFormat.from(this.getVar(ConfVars.HIVEQUERYRESULTFILEFORMAT));
}
public boolean getSparkConfigUpdated() {
return isSparkConfigUpdated;
}
public void setSparkConfigUpdated(boolean isSparkConfigUpdated) {
this.isSparkConfigUpdated = isSparkConfigUpdated;
}
public interface EncoderDecoder<K, V> {
V encode(K key);
K decode(V value);
}
public static class URLEncoderDecoder implements EncoderDecoder<String, String> {
@Override
public String encode(String key) {
try {
return URLEncoder.encode(key, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return key;
}
}
@Override
public String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
public static class EncoderDecoderFactory {
public static final URLEncoderDecoder URL_ENCODER_DECODER = new URLEncoderDecoder();
}
static {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = HiveConf.class.getClassLoader();
}
hiveDefaultURL = classLoader.getResource("hive-default.xml");
// Look for hive-site.xml on the CLASSPATH and log its location if found.
hiveSiteURL = findConfigFile(classLoader, "hive-site.xml", true);
hivemetastoreSiteUrl = findConfigFile(classLoader, "hivemetastore-site.xml", false);
hiveServer2SiteUrl = findConfigFile(classLoader, "hiveserver2-site.xml", false);
for (ConfVars confVar : ConfVars.values()) {
vars.put(confVar.varname, confVar);
}
Set<String> llapDaemonConfVarsSetLocal = new LinkedHashSet<>();
populateLlapDaemonVarsSet(llapDaemonConfVarsSetLocal);
llapDaemonVarsSet = Collections.unmodifiableSet(llapDaemonConfVarsSetLocal);
}
private static URL findConfigFile(ClassLoader classLoader, String name, boolean doLog) {
URL result = classLoader.getResource(name);
if (result == null) {
String confPath = System.getenv("HIVE_CONF_DIR");
result = checkConfigFile(new File(confPath, name));
if (result == null) {
String homePath = System.getenv("HIVE_HOME");
String nameInConf = "conf" + File.separator + name;
result = checkConfigFile(new File(homePath, nameInConf));
if (result == null) {
try {
// Handle both file:// and jar:<url>!{entry} in the case of shaded hive libs
URL sourceUrl = HiveConf.class.getProtectionDomain().getCodeSource().getLocation();
URI jarUri = sourceUrl.getProtocol().equalsIgnoreCase("jar") ? new URI(sourceUrl.getPath()) : sourceUrl.toURI();
// From the jar file, the parent is /lib folder
File parent = new File(jarUri).getParentFile();
if (parent != null) {
result = checkConfigFile(new File(parent.getParentFile(), nameInConf));
}
} catch (Throwable e) {
LOG.info("Cannot get jar URI", e);
System.err.println("Cannot get jar URI: " + e.getMessage());
}
}
}
}
if (doLog) {
LOG.info("Found configuration file {}", result);
}
return result;
}
private static URL checkConfigFile(File f) {
try {
return (f.exists() && f.isFile()) ? f.toURI().toURL() : null;
} catch (Throwable e) {
LOG.info("Error looking for config {}", f, e);
System.err.println("Error looking for config " + f + ": " + e.getMessage());
return null;
}
}
@InterfaceAudience.Private
public static final String PREFIX_LLAP = "llap.";
@InterfaceAudience.Private
public static final String PREFIX_HIVE_LLAP = "hive.llap.";
/**
* Metastore related options that the db is initialized against. When a conf
* var in this is list is changed, the metastore instance for the CLI will
* be recreated so that the change will take effect.
*/
public static final HiveConf.ConfVars[] metaVars = {
HiveConf.ConfVars.METASTOREWAREHOUSE,
HiveConf.ConfVars.REPLDIR,
HiveConf.ConfVars.METASTOREURIS,
HiveConf.ConfVars.METASTORESELECTION,
HiveConf.ConfVars.METASTORE_SERVER_PORT,
HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES,
HiveConf.ConfVars.METASTORETHRIFTFAILURERETRIES,
HiveConf.ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY,
HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT,
HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_LIFETIME,
HiveConf.ConfVars.METASTOREPWD,
HiveConf.ConfVars.METASTORECONNECTURLHOOK,
HiveConf.ConfVars.METASTORECONNECTURLKEY,
HiveConf.ConfVars.METASTORESERVERMINTHREADS,
HiveConf.ConfVars.METASTORESERVERMAXTHREADS,
HiveConf.ConfVars.METASTORE_TCP_KEEP_ALIVE,
HiveConf.ConfVars.METASTORE_INT_ORIGINAL,
HiveConf.ConfVars.METASTORE_INT_ARCHIVED,
HiveConf.ConfVars.METASTORE_INT_EXTRACTED,
HiveConf.ConfVars.METASTORE_KERBEROS_KEYTAB_FILE,
HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL,
HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL,
HiveConf.ConfVars.METASTORE_TOKEN_SIGNATURE,
HiveConf.ConfVars.METASTORE_CACHE_PINOBJTYPES,
HiveConf.ConfVars.METASTORE_CONNECTION_POOLING_TYPE,
HiveConf.ConfVars.METASTORE_VALIDATE_TABLES,
HiveConf.ConfVars.METASTORE_DATANUCLEUS_INIT_COL_INFO,
HiveConf.ConfVars.METASTORE_VALIDATE_COLUMNS,
HiveConf.ConfVars.METASTORE_VALIDATE_CONSTRAINTS,
HiveConf.ConfVars.METASTORE_STORE_MANAGER_TYPE,
HiveConf.ConfVars.METASTORE_AUTO_CREATE_ALL,
HiveConf.ConfVars.METASTORE_TRANSACTION_ISOLATION,
HiveConf.ConfVars.METASTORE_CACHE_LEVEL2,
HiveConf.ConfVars.METASTORE_CACHE_LEVEL2_TYPE,
HiveConf.ConfVars.METASTORE_IDENTIFIER_FACTORY,
HiveConf.ConfVars.METASTORE_PLUGIN_REGISTRY_BUNDLE_CHECK,
HiveConf.ConfVars.METASTORE_AUTHORIZATION_STORAGE_AUTH_CHECKS,
HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_MAX,
HiveConf.ConfVars.METASTORE_EVENT_LISTENERS,
HiveConf.ConfVars.METASTORE_TRANSACTIONAL_EVENT_LISTENERS,
HiveConf.ConfVars.METASTORE_EVENT_CLEAN_FREQ,
HiveConf.ConfVars.METASTORE_EVENT_EXPIRY_DURATION,
HiveConf.ConfVars.METASTORE_EVENT_MESSAGE_FACTORY,
HiveConf.ConfVars.METASTORE_FILTER_HOOK,
HiveConf.ConfVars.METASTORE_RAW_STORE_IMPL,
HiveConf.ConfVars.METASTORE_END_FUNCTION_LISTENERS,
HiveConf.ConfVars.METASTORE_PART_INHERIT_TBL_PROPS,
HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_OBJECTS_MAX,
HiveConf.ConfVars.METASTORE_INIT_HOOKS,
HiveConf.ConfVars.METASTORE_PRE_EVENT_LISTENERS,
HiveConf.ConfVars.HMSHANDLERATTEMPTS,
HiveConf.ConfVars.HMSHANDLERINTERVAL,
HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF,
HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN,
HiveConf.ConfVars.METASTORE_ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS,
HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES,
HiveConf.ConfVars.USERS_IN_ADMIN_ROLE,
HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER,
HiveConf.ConfVars.HIVE_TXN_MANAGER,
HiveConf.ConfVars.HIVE_TXN_TIMEOUT,
HiveConf.ConfVars.HIVE_TXN_OPERATIONAL_PROPERTIES,
HiveConf.ConfVars.HIVE_TXN_HEARTBEAT_THREADPOOL_SIZE,
HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH,
HiveConf.ConfVars.HIVE_TXN_RETRYABLE_SQLEX_REGEX,
HiveConf.ConfVars.HIVE_METASTORE_STATS_NDV_TUNER,
HiveConf.ConfVars.HIVE_METASTORE_STATS_NDV_DENSITY_FUNCTION,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_ENABLED,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_SIZE,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_PARTITIONS,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_FPP,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_VARIANCE,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_TTL,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_READER_WAIT,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_FULL,
HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_CLEAN_UNTIL,
HiveConf.ConfVars.METASTORE_FASTPATH,
HiveConf.ConfVars.METASTORE_HBASE_FILE_METADATA_THREADS,
HiveConf.ConfVars.METASTORE_WM_DEFAULT_POOL_SIZE
};
/**
* User configurable Metastore vars
*/
static final HiveConf.ConfVars[] metaConfVars = {
HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL,
HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL_DDL,
HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT,
HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN,
HiveConf.ConfVars.METASTORE_CAPABILITY_CHECK,
HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES
};
static {
for (ConfVars confVar : metaConfVars) {
metaConfs.put(confVar.varname, confVar);
}
}
public static final String HIVE_LLAP_DAEMON_SERVICE_PRINCIPAL_NAME = "hive.llap.daemon.service.principal";
public static final String HIVE_SERVER2_AUTHENTICATION_LDAP_USERMEMBERSHIPKEY_NAME =
"hive.server2.authentication.ldap.userMembershipKey";
public static final String HIVE_SPARK_SUBMIT_CLIENT = "spark-submit";
public static final String HIVE_SPARK_LAUNCHER_CLIENT = "spark-launcher";
/**
* dbVars are the parameters can be set per database. If these
* parameters are set as a database property, when switching to that
* database, the HiveConf variable will be changed. The change of these
* parameters will effectively change the DFS and MapReduce clusters
* for different databases.
*/
public static final HiveConf.ConfVars[] dbVars = {
HiveConf.ConfVars.HADOOPBIN,
HiveConf.ConfVars.METASTOREWAREHOUSE,
HiveConf.ConfVars.SCRATCHDIR
};
/**
* encoded parameter values are ;-) encoded. Use decoder to get ;-) decoded string
*/
static final HiveConf.ConfVars[] ENCODED_CONF = {
ConfVars.HIVEQUERYSTRING
};
/**
* Variables used by LLAP daemons.
* TODO: Eventually auto-populate this based on prefixes. The conf variables
* will need to be renamed for this.
*/
private static final Set<String> llapDaemonVarsSet;
private static void populateLlapDaemonVarsSet(Set<String> llapDaemonVarsSetLocal) {
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_ENABLED.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_MEMORY_MODE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_MIN_ALLOC.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_MAX_ALLOC.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_ARENA_COUNT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_MEMORY_MAX_SIZE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_DIRECT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_USE_LRFU.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_LRFU_LAMBDA.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_LRFU_BP_WRAPPER_SIZE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_CACHE_ALLOW_SYNTHETIC_FILEID.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_USE_FILEID_PATH.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_DECODING_METRICS_PERCENTILE_INTERVALS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ORC_ENABLE_TIME_COUNTERS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_THREADPOOL_SIZE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_KERBEROS_PRINCIPAL.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_KERBEROS_KEYTAB_FILE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ZKSM_ZK_CONNECTION_STRING.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_SECURITY_ACL.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_ACL.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_SECURITY_ACL_DENY.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_ACL_DENY.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DELEGATION_TOKEN_LIFETIME.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_RPC_PORT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_WEB_AUTO_AUTH.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_RPC_NUM_HANDLERS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WORK_DIRS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_YARN_SHUFFLE_PORT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_YARN_CONTAINER_MB.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SHUFFLE_DIR_WATCHER_ENABLED.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_HEARTBEAT_INTERVAL_MS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_CONNECTION_TIMEOUT_MS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_CONNECTION_SLEEP_BETWEEN_RETRIES_MS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_NUM_EXECUTORS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_RPC_PORT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_MEMORY_PER_INSTANCE_MB.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_XMX_HEADROOM.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_VCPUS_PER_INSTANCE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_NUM_FILE_CLEANER_THREADS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_FILE_CLEANUP_DELAY_SECONDS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SERVICE_REFRESH_INTERVAL.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOW_PERMANENT_FNS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_DOWNLOAD_PERMANENT_FNS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_SCHEDULER_WAIT_QUEUE_SIZE.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WAIT_QUEUE_COMPARATOR_CLASS_NAME.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_SCHEDULER_ENABLE_PREEMPTION.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_PREEMPTION_METRICS_INTERVALS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WEB_PORT.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WEB_SSL.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_CONTAINER_ID.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_VALIDATE_ACLS.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_LOGGER.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_USE_FQDN.varname);
llapDaemonVarsSetLocal.add(ConfVars.LLAP_OUTPUT_FORMAT_ARROW.varname);
}
/**
* Get a set containing configuration parameter names used by LLAP Server isntances
* @return an unmodifiable set containing llap ConfVars
*/
public static final Set<String> getLlapDaemonConfVars() {
return llapDaemonVarsSet;
}
/**
* ConfVars.
*
* These are the default configuration properties for Hive. Each HiveConf
* object is initialized as follows:
*
* 1) Hadoop configuration properties are applied.
* 2) ConfVar properties with non-null values are overlayed.
* 3) hive-site.xml properties are overlayed.
* 4) System Properties and Manual Overrides are overlayed.
*
* WARNING: think twice before adding any Hadoop configuration properties
* with non-null values to this list as they will override any values defined
* in the underlying Hadoop configuration.
*/
public static enum ConfVars {
MSC_CACHE_ENABLED("hive.metastore.client.cache.v2.enabled", true,
"This property enables a Caffeine Cache for Metastore client"),
MSC_CACHE_MAX_SIZE("hive.metastore.client.cache.v2.maxSize", "1Gb", new SizeValidator(),
"Set the maximum size (number of bytes) of the metastore client cache (DEFAULT: 1GB). " +
"Only in effect when the cache is enabled"),
MSC_CACHE_RECORD_STATS("hive.metastore.client.cache.v2.recordStats", false,
"This property enables recording metastore client cache stats in DEBUG logs"),
// QL execution stuff
SCRIPTWRAPPER("hive.exec.script.wrapper", null, ""),
PLAN("hive.exec.plan", "", ""),
STAGINGDIR("hive.exec.stagingdir", ".hive-staging",
"Directory name that will be created inside table locations in order to support HDFS encryption. " +
"This is replaces ${hive.exec.scratchdir} for query results with the exception of read-only tables. " +
"In all cases ${hive.exec.scratchdir} is still used for other temporary files, such as job plans."),
SCRATCHDIR("hive.exec.scratchdir", "/tmp/hive",
"HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. " +
"For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/<username> is created, " +
"with ${hive.scratch.dir.permission}."),
REPLDIR("hive.repl.rootdir","/user/${system:user.name}/repl/",
"HDFS root dir for all replication dumps."),
REPLCMENABLED("hive.repl.cm.enabled", false,
"Turn on ChangeManager, so delete files will go to cmrootdir."),
REPLCMDIR("hive.repl.cmrootdir","/user/${system:user.name}/cmroot/",
"Root dir for ChangeManager, used for deleted files."),
REPLCMRETIAN("hive.repl.cm.retain","10d",
new TimeValidator(TimeUnit.DAYS),
"Time to retain removed files in cmrootdir."),
REPLCMENCRYPTEDDIR("hive.repl.cm.encryptionzone.rootdir", ".cmroot",
"Root dir for ChangeManager if encryption zones are enabled, used for deleted files."),
REPLCMFALLBACKNONENCRYPTEDDIR("hive.repl.cm.nonencryptionzone.rootdir",
"",
"Root dir for ChangeManager for non encrypted paths if hive.repl.cmrootdir is encrypted."),
REPLCMINTERVAL("hive.repl.cm.interval","3600s",
new TimeValidator(TimeUnit.SECONDS),
"Inteval for cmroot cleanup thread."),
REPL_HA_DATAPATH_REPLACE_REMOTE_NAMESERVICE("hive.repl.ha.datapath.replace.remote.nameservice", false,
"When HDFS is HA enabled and both source and target clusters are configured with same nameservice name," +
"enable this flag and provide a new unique logical name for representing the remote cluster " +
"nameservice using config " + "'hive.repl.ha.datapath.replace.remote.nameservice.name'."),
REPL_HA_DATAPATH_REPLACE_REMOTE_NAMESERVICE_NAME("hive.repl.ha.datapath.replace.remote.nameservice.name", null,
"When HDFS is HA enabled and both source and target clusters are configured with same nameservice name, " +
"use this config to provide a unique logical name for nameservice on the remote cluster (should " +
"be different from nameservice name on the local cluster)"),
REPL_FUNCTIONS_ROOT_DIR("hive.repl.replica.functions.root.dir","/user/${system:user.name}/repl/functions/",
"Root directory on the replica warehouse where the repl sub-system will store jars from the primary warehouse"),
REPL_APPROX_MAX_LOAD_TASKS("hive.repl.approx.max.load.tasks", 10000,
"Provide an approximation of the maximum number of tasks that should be executed before \n"
+ "dynamically generating the next set of tasks. The number is approximate as Hive \n"
+ "will stop at a slightly higher number, the reason being some events might lead to a \n"
+ "task increment that would cross the specified limit."),
REPL_PARTITIONS_DUMP_PARALLELISM("hive.repl.partitions.dump.parallelism",100,
"Number of threads that will be used to dump partition data information during repl dump."),
REPL_RUN_DATA_COPY_TASKS_ON_TARGET("hive.repl.run.data.copy.tasks.on.target", true,
"Indicates whether replication should run data copy tasks during repl load operation."),
REPL_FILE_LIST_CACHE_SIZE("hive.repl.file.list.cache.size", 10000,
"This config indicates threshold for the maximum number of data copy locations to be kept in memory. \n"
+ "When the config 'hive.repl.run.data.copy.tasks.on.target' is set to true, this config " +
"is not considered."),
REPL_DUMP_METADATA_ONLY("hive.repl.dump.metadata.only", false,
"Indicates whether replication dump only metadata information or data + metadata. \n"
+ "This config makes hive.repl.include.external.tables config ineffective."),
REPL_RETAIN_PREV_DUMP_DIR("hive.repl.retain.prev.dump.dir", false,
"If this is set to false, then all previously used dump-directories will be deleted after repl-dump. " +
"If true, a number of latest dump-directories specified by hive.repl.retain.prev.dump.dir.count will be retained"),
REPL_RETAIN_PREV_DUMP_DIR_COUNT("hive.repl.retain.prev.dump.dir.count", 3,
"Indicates maximium number of latest previously used dump-directories which would be retained when " +
"hive.repl.retain.prev.dump.dir is set to true"),
REPL_INCLUDE_MATERIALIZED_VIEWS("hive.repl.include.materialized.views", false,
"Indicates whether replication of materialized views is enabled."),
REPL_DUMP_SKIP_IMMUTABLE_DATA_COPY("hive.repl.dump.skip.immutable.data.copy", false,
"Indicates whether replication dump can skip copyTask and refer to \n"
+ " original path instead. This would retain all table and partition meta"),
REPL_DUMP_METADATA_ONLY_FOR_EXTERNAL_TABLE("hive.repl.dump.metadata.only.for.external.table",
true,
"Indicates whether external table replication dump only metadata information or data + metadata"),
REPL_BOOTSTRAP_ACID_TABLES("hive.repl.bootstrap.acid.tables", false,
"Indicates if repl dump should bootstrap the information about ACID tables along with \n"
+ "incremental dump for replication. It is recommended to keep this config parameter \n"
+ "as false always and should be set to true only via WITH clause of REPL DUMP \n"
+ "command. It should be set to true only once for incremental repl dump on \n"
+ "each of the existing replication policies after enabling acid tables replication."),
REPL_BOOTSTRAP_DUMP_OPEN_TXN_TIMEOUT("hive.repl.bootstrap.dump.open.txn.timeout", "1h",
new TimeValidator(TimeUnit.HOURS),
"Indicates the timeout for all transactions which are opened before triggering bootstrap REPL DUMP. "
+ "If these open transactions are not closed within the timeout value, then REPL DUMP will "
+ "forcefully abort those transactions and continue with bootstrap dump."),
REPL_BOOTSTRAP_DUMP_ABORT_WRITE_TXN_AFTER_TIMEOUT("hive.repl.bootstrap.dump.abort.write.txn.after.timeout",
true,
"Indicates whether to abort write transactions belonging to the db under replication while doing a" +
" bootstrap dump after the timeout configured by hive.repl.bootstrap.dump.open.txn.timeout. If set to false," +
" bootstrap dump will fail."),
//https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/TransparentEncryption.html#Running_as_the_superuser
REPL_ADD_RAW_RESERVED_NAMESPACE("hive.repl.add.raw.reserved.namespace", false,
"For TDE with same encryption keys on source and target, allow Distcp super user to access \n"
+ "the raw bytes from filesystem without decrypting on source and then encrypting on target."),
REPL_INCLUDE_EXTERNAL_TABLES("hive.repl.include.external.tables", true,
"Indicates if repl dump should include information about external tables. It should be \n"
+ "used in conjunction with 'hive.repl.dump.metadata.only' set to false. if 'hive.repl.dump.metadata.only' \n"
+ " is set to true then this config parameter has no effect as external table meta data is flushed \n"
+ " always by default. If this config parameter is enabled on an on-going replication policy which is in\n"
+ " incremental phase, then need to set 'hive.repl.bootstrap.external.tables' to true for the first \n"
+ " repl dump to bootstrap all external tables."),
REPL_BOOTSTRAP_EXTERNAL_TABLES("hive.repl.bootstrap.external.tables", false,
"Indicates if repl dump should bootstrap the information about external tables along with incremental \n"
+ "dump for replication. It is recommended to keep this config parameter as false always and should be \n"
+ "set to true only via WITH clause of REPL DUMP command. It should be used in conjunction with \n"
+ "'hive.repl.include.external.tables' when sets to true. If 'hive.repl.include.external.tables' is \n"
+ "set to false, then this config parameter has no effect. It should be set to true only once for \n"
+ "incremental repl dump on each existing replication policy after enabling external tables replication."),
REPL_EXTERNAL_TABLE_BASE_DIR("hive.repl.replica.external.table.base.dir", null,
"This is the fully qualified base directory on the target/replica warehouse under which data for "
+ "external tables is stored. This is relative base path and hence prefixed to the source "
+ "external table path on target cluster."),
REPL_INCLUDE_AUTHORIZATION_METADATA("hive.repl.include.authorization.metadata", false,
"This configuration will enable security and authorization related metadata along "
+ "with the hive data and metadata replication. "),
REPL_AUTHORIZATION_PROVIDER_SERVICE("hive.repl.authorization.provider.service", "ranger",
"This configuration will define which service will provide the security and authorization "
+ "related metadata that needs to be replicated along "
+ "with the hive data and metadata replication. Set the configuration "
+ "hive.repl.include.authorization.metadata to false to disable "
+ "security policies being replicated "),
REPL_RANGER_ADD_DENY_POLICY_TARGET("hive.repl.ranger.target.deny.policy",
true,
"This configuration will add a deny policy on the target database for all users except hive"
+ " to avoid any update to the target database"),
REPL_RANGER_CLIENT_READ_TIMEOUT("hive.repl.ranger.client.read.timeout", "300s",
new TimeValidator(TimeUnit.SECONDS), "Ranger client read timeout for Ranger REST API calls."),
REPL_INCLUDE_ATLAS_METADATA("hive.repl.include.atlas.metadata", false,
"Indicates if Atlas metadata should be replicated along with Hive data and metadata or not."),
REPL_ATLAS_ENDPOINT("hive.repl.atlas.endpoint", null,
"Atlas endpoint of the current cluster hive database is getting replicated from/to."),
REPL_ATLAS_REPLICATED_TO_DB("hive.repl.atlas.replicatedto", null,
"Target hive database name Atlas metadata of source hive database is being replicated to."),
REPL_ATLAS_CLIENT_READ_TIMEOUT("hive.repl.atlas.client.read.timeout", "7200s",
new TimeValidator(TimeUnit.SECONDS), "Atlas client read timeout for Atlas REST API calls."),
REPL_EXTERNAL_CLIENT_CONNECT_TIMEOUT("hive.repl.external.client.connect.timeout", "10s",
new TimeValidator(TimeUnit.SECONDS), "Client connect timeout for REST API calls to external service."),
REPL_SOURCE_CLUSTER_NAME("hive.repl.source.cluster.name", null,
"Name of the source cluster for the replication."),
REPL_TARGET_CLUSTER_NAME("hive.repl.target.cluster.name", null,
"Name of the target cluster for the replication."),
REPL_RETRY_INTIAL_DELAY("hive.repl.retry.initial.delay", "60s",
new TimeValidator(TimeUnit.SECONDS),
"Initial Delay before retry starts."),
REPL_RETRY_BACKOFF_COEFFICIENT("hive.repl.retry.backoff.coefficient", 1.2f,
"The backoff coefficient for exponential retry delay between retries. " +
"Previous Delay * Backoff Coefficient will determine the next retry interval"),
REPL_RETRY_JITTER("hive.repl.retry.jitter", "30s", new TimeValidator(TimeUnit.SECONDS),
"A random jitter to be applied to avoid all retries happening at the same time."),
REPL_RETRY_MAX_DELAY_BETWEEN_RETRIES("hive.repl.retry.max.delay.between.retries", "60m",
new TimeValidator(TimeUnit.MINUTES),
"Maximum allowed retry delay in minutes after including exponential backoff. " +
"If this limit is reached, retry will continue with this retry duration."),
REPL_RETRY_TOTAL_DURATION("hive.repl.retry.total.duration", "24h",
new TimeValidator(TimeUnit.HOURS),
"Total allowed retry duration in hours inclusive of all retries. Once this is exhausted, " +
"the policy instance will be marked as failed and will need manual intervention to restart."),
REPL_LOAD_PARTITIONS_BATCH_SIZE("hive.repl.load.partitions.batch.size", 10000,
"Provide the maximum number of partitions of a table that will be batched together during \n"
+ "repl load. All the partitions in a batch will make a single metastore call to update the metadata. \n"
+ "The data for these partitions will be copied before copying the metadata batch. "),
REPL_LOAD_PARTITIONS_WITH_DATA_COPY_BATCH_SIZE("hive.repl.load.partitions.with.data.copy.batch.size",1000,
"Provide the maximum number of partitions of a table that will be batched together during \n"
+ "repl load. All the partitions in a batch will make a single metastore call to update the metadata. \n"
+ "The data for these partitions will be copied before copying the metadata batch. "),
REPL_PARALLEL_COPY_TASKS("hive.repl.parallel.copy.tasks",100,
"Provide the maximum number of parallel copy operation(distcp or regular copy) launched for a table \n"
+ "or partition. This will create at max 100 threads which will run copy in parallel for the data files at \n"
+ " table or partition level. If hive.exec.parallel \n"
+ "is set to true then max worker threads created for copy can be hive.exec.parallel.thread.number(determines \n"
+ "number of copy tasks in parallel) * hive.repl.parallel.copy.tasks "),
LOCALSCRATCHDIR("hive.exec.local.scratchdir",
"${system:java.io.tmpdir}" + File.separator + "${system:user.name}",
"Local scratch space for Hive jobs"),
DOWNLOADED_RESOURCES_DIR("hive.downloaded.resources.dir",
"${system:java.io.tmpdir}" + File.separator + "${hive.session.id}_resources",
"Temporary local directory for added resources in the remote file system."),
SCRATCHDIRPERMISSION("hive.scratch.dir.permission", "700",
"The permission for the user specific scratch directories that get created."),
SUBMITVIACHILD("hive.exec.submitviachild", false, ""),
SUBMITLOCALTASKVIACHILD("hive.exec.submit.local.task.via.child", true,
"Determines whether local tasks (typically mapjoin hashtable generation phase) runs in \n" +
"separate JVM (true recommended) or not. \n" +
"Avoids the overhead of spawning new JVM, but can lead to out-of-memory issues."),
SCRIPTERRORLIMIT("hive.exec.script.maxerrsize", 100000,
"Maximum number of bytes a script is allowed to emit to standard error (per map-reduce task). \n" +
"This prevents runaway scripts from filling logs partitions to capacity"),
ALLOWPARTIALCONSUMP("hive.exec.script.allow.partial.consumption", false,
"When enabled, this option allows a user script to exit successfully without consuming \n" +
"all the data from the standard input."),
STREAMREPORTERPERFIX("stream.stderr.reporter.prefix", "reporter:",
"Streaming jobs that log to standard error with this prefix can log counter or status information."),
STREAMREPORTERENABLED("stream.stderr.reporter.enabled", true,
"Enable consumption of status and counter messages for streaming jobs."),
COMPRESSRESULT("hive.exec.compress.output", false,
"This controls whether the final outputs of a query (to a local/HDFS file or a Hive table) is compressed. \n" +
"The compression codec and other options are determined from Hadoop config variables mapred.output.compress*"),
COMPRESSINTERMEDIATE("hive.exec.compress.intermediate", false,
"This controls whether intermediate files produced by Hive between multiple map-reduce jobs are compressed. \n" +
"The compression codec and other options are determined from Hadoop config variables mapred.output.compress*"),
COMPRESSINTERMEDIATECODEC("hive.intermediate.compression.codec", "", ""),
COMPRESSINTERMEDIATETYPE("hive.intermediate.compression.type", "", ""),
BYTESPERREDUCER("hive.exec.reducers.bytes.per.reducer", (long) (256 * 1000 * 1000),
"size per reducer.The default is 256Mb, i.e if the input size is 1G, it will use 4 reducers."),
MAXREDUCERS("hive.exec.reducers.max", 1009,
"max number of reducers will be used. If the one specified in the configuration parameter mapred.reduce.tasks is\n" +
"negative, Hive will use this one as the max number of reducers when automatically determine number of reducers."),
PREEXECHOOKS("hive.exec.pre.hooks", "",
"Comma-separated list of pre-execution hooks to be invoked for each statement. \n" +
"A pre-execution hook is specified as the name of a Java class which implements the \n" +
"org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."),
POSTEXECHOOKS("hive.exec.post.hooks", "",
"Comma-separated list of post-execution hooks to be invoked for each statement. \n" +
"A post-execution hook is specified as the name of a Java class which implements the \n" +
"org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."),
ONFAILUREHOOKS("hive.exec.failure.hooks", "",
"Comma-separated list of on-failure hooks to be invoked for each statement. \n" +
"An on-failure hook is specified as the name of Java class which implements the \n" +
"org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."),
QUERYREDACTORHOOKS("hive.exec.query.redactor.hooks", "",
"Comma-separated list of hooks to be invoked for each query which can \n" +
"tranform the query before it's placed in the job.xml file. Must be a Java class which \n" +
"extends from the org.apache.hadoop.hive.ql.hooks.Redactor abstract class."),
CLIENTSTATSPUBLISHERS("hive.client.stats.publishers", "",
"Comma-separated list of statistics publishers to be invoked on counters on each job. \n" +
"A client stats publisher is specified as the name of a Java class which implements the \n" +
"org.apache.hadoop.hive.ql.stats.ClientStatsPublisher interface."),
EXECPARALLEL("hive.exec.parallel", false, "Whether to execute jobs in parallel"),
EXECPARALLETHREADNUMBER("hive.exec.parallel.thread.number", 8,
"How many jobs at most can be executed in parallel"),
@Deprecated
HIVESPECULATIVEEXECREDUCERS("hive.mapred.reduce.tasks.speculative.execution", false,
"(Deprecated) Whether speculative execution for reducers should be turned on. "),
HIVECOUNTERSPULLINTERVAL("hive.exec.counters.pull.interval", 1000L,
"The interval with which to poll the JobTracker for the counters the running job. \n" +
"The smaller it is the more load there will be on the jobtracker, the higher it is the less granular the caught will be."),
DYNAMICPARTITIONING("hive.exec.dynamic.partition", true,
"Whether or not to allow dynamic partitions in DML/DDL."),
DYNAMICPARTITIONINGMODE("hive.exec.dynamic.partition.mode", "nonstrict",
new StringSet("strict", "nonstrict"),
"In strict mode, the user must specify at least one static partition\n" +
"in case the user accidentally overwrites all partitions.\n" +
"In nonstrict mode all partitions are allowed to be dynamic."),
DYNAMICPARTITIONMAXPARTS("hive.exec.max.dynamic.partitions", 1000,
"Maximum number of dynamic partitions allowed to be created in total."),
DYNAMICPARTITIONMAXPARTSPERNODE("hive.exec.max.dynamic.partitions.pernode", 100,
"Maximum number of dynamic partitions allowed to be created in each mapper/reducer node."),
DYNAMICPARTITIONCONVERT("hive.exec.dynamic.partition.type.conversion", true,
"Whether to check and cast a dynamic partition column before creating the partition " +
"directory. For example, if partition p is type int and we insert string '001', then if " +
"this value is true, directory p=1 will be created; if false, p=001"),
MAXCREATEDFILES("hive.exec.max.created.files", 100000L,
"Maximum number of HDFS files created by all mappers/reducers in a MapReduce job."),
DEFAULTPARTITIONNAME("hive.exec.default.partition.name", "__HIVE_DEFAULT_PARTITION__",
"The default partition name in case the dynamic partition column value is null/empty string or any other values that cannot be escaped. \n" +
"This value must not contain any special character used in HDFS URI (e.g., ':', '%', '/' etc). \n" +
"The user has to be aware that the dynamic partition value should not contain this value to avoid confusions."),
DEFAULT_ZOOKEEPER_PARTITION_NAME("hive.lockmgr.zookeeper.default.partition.name", "__HIVE_DEFAULT_ZOOKEEPER_PARTITION__", ""),
// Whether to show a link to the most failed task + debugging tips
SHOW_JOB_FAIL_DEBUG_INFO("hive.exec.show.job.failure.debug.info", true,
"If a job fails, whether to provide a link in the CLI to the task with the\n" +
"most failures, along with debugging hints if applicable."),
JOB_DEBUG_CAPTURE_STACKTRACES("hive.exec.job.debug.capture.stacktraces", true,
"Whether or not stack traces parsed from the task logs of a sampled failed task \n" +
"for each failed job should be stored in the SessionState"),
JOB_DEBUG_TIMEOUT("hive.exec.job.debug.timeout", 30000, ""),
TASKLOG_DEBUG_TIMEOUT("hive.exec.tasklog.debug.timeout", 20000, ""),
OUTPUT_FILE_EXTENSION("hive.output.file.extension", null,
"String used as a file extension for output files. \n" +
"If not set, defaults to the codec extension for text files (e.g. \".gz\"), or no extension otherwise."),
HIVE_IN_TEST("hive.in.test", false, "internal usage only, true in test mode", true),
HIVE_IN_TEST_SSL("hive.in.ssl.test", false, "internal usage only, true in SSL test mode", true),
// TODO: this needs to be removed; see TestReplicationScenarios* comments.
HIVE_IN_TEST_REPL("hive.in.repl.test", false, "internal usage only, true in replication test mode", true),
HIVE_IN_TEST_IDE("hive.in.ide.test", false, "internal usage only, true if test running in ide",
true),
HIVE_TESTING_SHORT_LOGS("hive.testing.short.logs", false,
"internal usage only, used only in test mode. If set true, when requesting the " +
"operation logs the short version (generated by LogDivertAppenderForTest) will be " +
"returned"),
HIVE_TESTING_REMOVE_LOGS("hive.testing.remove.logs", true,
"internal usage only, used only in test mode. If set false, the operation logs, and the " +
"operation log directory will not be removed, so they can be found after the test runs."),
HIVE_TEST_LOAD_HOSTNAMES("hive.test.load.hostnames", "",
"Specify host names for load testing. (e.g., \"host1,host2,host3\"). Leave it empty if no " +
"load generation is needed (eg. for production)."),
HIVE_TEST_LOAD_INTERVAL("hive.test.load.interval", "10ms", new TimeValidator(TimeUnit.MILLISECONDS),
"The interval length used for load and idle periods in milliseconds."),
HIVE_TEST_LOAD_UTILIZATION("hive.test.load.utilization", 0.2f,
"Specify processor load utilization between 0.0 (not loaded on all threads) and 1.0 " +
"(fully loaded on all threads). Comparing this with a random value the load generator creates " +
"hive.test.load.interval length active loops or idle periods"),
HIVE_IN_TEZ_TEST("hive.in.tez.test", false, "internal use only, true when in testing tez",
true),
HIVE_MAPJOIN_TESTING_NO_HASH_TABLE_LOAD("hive.mapjoin.testing.no.hash.table.load", false, "internal use only, true when in testing map join",
true),
HIVE_ADDITIONAL_PARTIAL_MASKS_PATTERN("hive.qtest.additional.partial.mask.pattern", "",
"internal use only, used in only qtests. Provide additional partial masks pattern" +
"for qtests as a ',' separated list"),
HIVE_ADDITIONAL_PARTIAL_MASKS_REPLACEMENT_TEXT("hive.qtest.additional.partial.mask.replacement.text", "",
"internal use only, used in only qtests. Provide additional partial masks replacement" +
"text for qtests as a ',' separated list"),
HIVE_IN_REPL_TEST_FILES_SORTED("hive.in.repl.test.files.sorted", false,
"internal usage only, set to true if the file listing is required in sorted order during bootstrap load", true),
LOCALMODEAUTO("hive.exec.mode.local.auto", false,
"Let Hive determine whether to run in local mode automatically"),
LOCALMODEMAXBYTES("hive.exec.mode.local.auto.inputbytes.max", 134217728L,
"When hive.exec.mode.local.auto is true, input bytes should less than this for local mode."),
LOCALMODEMAXINPUTFILES("hive.exec.mode.local.auto.input.files.max", 4,
"When hive.exec.mode.local.auto is true, the number of tasks should less than this for local mode."),
DROP_IGNORES_NON_EXISTENT("hive.exec.drop.ignorenonexistent", true,
"Do not report an error if DROP TABLE/VIEW/Index/Function specifies a non-existent table/view/function"),
HIVEIGNOREMAPJOINHINT("hive.ignore.mapjoin.hint", true, "Ignore the mapjoin hint"),
HIVE_FILE_MAX_FOOTER("hive.file.max.footer", 100,
"maximum number of lines for footer user can define for a table file"),
HIVE_RESULTSET_USE_UNIQUE_COLUMN_NAMES("hive.resultset.use.unique.column.names", true,
"Make column names unique in the result set by qualifying column names with table alias if needed.\n" +
"Table alias will be added to column names for queries of type \"select *\" or \n" +
"if query explicitly uses table alias \"select r1.x..\"."),
HIVE_PROTO_EVENTS_QUEUE_CAPACITY("hive.hook.proto.queue.capacity", 64,
"Queue capacity for the proto events logging threads."),
HIVE_PROTO_EVENTS_BASE_PATH("hive.hook.proto.base-directory", "",
"Base directory into which the proto event messages are written by HiveProtoLoggingHook."),
HIVE_PROTO_EVENTS_ROLLOVER_CHECK_INTERVAL("hive.hook.proto.rollover-interval", "600s",
new TimeValidator(TimeUnit.SECONDS, 0L, true, 3600 * 24L, true),
"Frequency at which the file rollover check is triggered."),
HIVE_PROTO_EVENTS_CLEAN_FREQ("hive.hook.proto.events.clean.freq", "1d",
new TimeValidator(TimeUnit.DAYS),
"Frequency at which timer task runs to purge expired proto event files."),
HIVE_PROTO_EVENTS_TTL("hive.hook.proto.events.ttl", "7d",
new TimeValidator(TimeUnit.DAYS),
"Time-To-Live (TTL) of proto event files before cleanup."),
HIVE_PROTO_FILE_PER_EVENT("hive.hook.proto.file.per.event", false,
"Whether each proto event has to be written to separate file. " +
"(Use this for FS that does not hflush immediately like S3A)"),
// Hadoop Configuration Properties
// Properties with null values are ignored and exist only for the purpose of giving us
// a symbolic name to reference in the Hive source code. Properties with non-null
// values will override any values set in the underlying Hadoop configuration.
HADOOPBIN("hadoop.bin.path", findHadoopBinary(), "", true),
YARNBIN("yarn.bin.path", findYarnBinary(), "", true),
MAPREDBIN("mapred.bin.path", findMapRedBinary(), "", true),
HIVE_FS_HAR_IMPL("fs.har.impl", "org.apache.hadoop.hive.shims.HiveHarFileSystem",
"The implementation for accessing Hadoop Archives. Note that this won't be applicable to Hadoop versions less than 0.20"),
MAPREDMAXSPLITSIZE(FileInputFormat.SPLIT_MAXSIZE, 256000000L, "", true),
MAPREDMINSPLITSIZE(FileInputFormat.SPLIT_MINSIZE, 1L, "", true),
MAPREDMINSPLITSIZEPERNODE(CombineFileInputFormat.SPLIT_MINSIZE_PERNODE, 1L, "", true),
MAPREDMINSPLITSIZEPERRACK(CombineFileInputFormat.SPLIT_MINSIZE_PERRACK, 1L, "", true),
// The number of reduce tasks per job. Hadoop sets this value to 1 by default
// By setting this property to -1, Hive will automatically determine the correct
// number of reducers.
HADOOPNUMREDUCERS("mapreduce.job.reduces", -1, "", true),
// Metastore stuff. Be sure to update HiveConf.metaVars when you add something here!
METASTOREDBTYPE("hive.metastore.db.type", "DERBY", new StringSet("DERBY", "ORACLE", "MYSQL", "MSSQL", "POSTGRES"),
"Type of database used by the metastore. Information schema & JDBCStorageHandler depend on it."),
/**
* @deprecated Use MetastoreConf.WAREHOUSE
*/
@Deprecated
METASTOREWAREHOUSE("hive.metastore.warehouse.dir", "/user/hive/warehouse",
"location of default database for the warehouse"),
HIVE_METASTORE_WAREHOUSE_EXTERNAL("hive.metastore.warehouse.external.dir", null,
"Default location for external tables created in the warehouse. " +
"If not set or null, then the normal warehouse location will be used as the default location."),
/**
* @deprecated Use MetastoreConf.THRIFT_URIS
*/
@Deprecated
METASTOREURIS("hive.metastore.uris", "",
"Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore."),
/**
* @deprecated Use MetastoreConf.THRIFT_URI_SELECTION
*/
@Deprecated
METASTORESELECTION("hive.metastore.uri.selection", "RANDOM",
new StringSet("SEQUENTIAL", "RANDOM"),
"Determines the selection mechanism used by metastore client to connect to remote " +
"metastore. SEQUENTIAL implies that the first valid metastore from the URIs specified " +
"as part of hive.metastore.uris will be picked. RANDOM implies that the metastore " +
"will be picked randomly"),
/**
* @deprecated Use MetastoreConf.CAPABILITY_CHECK
*/
@Deprecated
METASTORE_CAPABILITY_CHECK("hive.metastore.client.capability.check", true,
"Whether to check client capabilities for potentially breaking API usage."),
METASTORE_CLIENT_CAPABILITIES("hive.metastore.client.capabilities", "", "Capabilities possessed by HiveServer"),
METASTORE_CLIENT_CACHE_ENABLED("hive.metastore.client.cache.enabled", false,
"Whether to enable metastore client cache"),
METASTORE_CLIENT_CACHE_EXPIRY_TIME("hive.metastore.client.cache.expiry.time", "120s",
new TimeValidator(TimeUnit.SECONDS), "Expiry time for metastore client cache"),
METASTORE_CLIENT_CACHE_INITIAL_CAPACITY("hive.metastore.client.cache.initial.capacity", 50,
"Initial capacity for metastore client cache"),
METASTORE_CLIENT_CACHE_MAX_CAPACITY("hive.metastore.client.cache.max.capacity", 50,
"Max capacity for metastore client cache"),
METASTORE_CLIENT_CACHE_STATS_ENABLED("hive.metastore.client.cache.stats.enabled", false,
"Whether to enable metastore client cache stats"),
METASTORE_FASTPATH("hive.metastore.fastpath", false,
"Used to avoid all of the proxies and object copies in the metastore. Note, if this is " +
"set, you MUST use a local metastore (hive.metastore.uris must be empty) otherwise " +
"undefined and most likely undesired behavior will result"),
/**
* @deprecated Use MetastoreConf.FS_HANDLER_THREADS_COUNT
*/
@Deprecated
METASTORE_FS_HANDLER_THREADS_COUNT("hive.metastore.fshandler.threads", 15,
"Number of threads to be allocated for metastore handler for fs operations."),
/**
* @deprecated Use MetastoreConf.FILE_METADATA_THREADS
*/
@Deprecated
METASTORE_HBASE_FILE_METADATA_THREADS("hive.metastore.hbase.file.metadata.threads", 1,
"Number of threads to use to read file metadata in background to cache it."),
/**
* @deprecated Use MetastoreConf.URI_RESOLVER
*/
@Deprecated
METASTORE_URI_RESOLVER("hive.metastore.uri.resolver", "",
"If set, fully qualified class name of resolver for hive metastore uri's"),
/**
* @deprecated Use MetastoreConf.THRIFT_CONNECTION_RETRIES
*/
@Deprecated
METASTORETHRIFTCONNECTIONRETRIES("hive.metastore.connect.retries", 3,
"Number of retries while opening a connection to metastore"),
/**
* @deprecated Use MetastoreConf.THRIFT_FAILURE_RETRIES
*/
@Deprecated
METASTORETHRIFTFAILURERETRIES("hive.metastore.failure.retries", 1,
"Number of retries upon failure of Thrift metastore calls"),
/**
* @deprecated Use MetastoreConf.SERVER_PORT
*/
@Deprecated
METASTORE_SERVER_PORT("hive.metastore.port", 9083, "Hive metastore listener port"),
/**
* @deprecated Use MetastoreConf.CLIENT_CONNECT_RETRY_DELAY
*/
@Deprecated
METASTORE_CLIENT_CONNECT_RETRY_DELAY("hive.metastore.client.connect.retry.delay", "1s",
new TimeValidator(TimeUnit.SECONDS),
"Number of seconds for the client to wait between consecutive connection attempts"),
/**
* @deprecated Use MetastoreConf.CLIENT_SOCKET_TIMEOUT
*/
@Deprecated
METASTORE_CLIENT_SOCKET_TIMEOUT("hive.metastore.client.socket.timeout", "600s",
new TimeValidator(TimeUnit.SECONDS),
"MetaStore Client socket timeout in seconds"),
/**
* @deprecated Use MetastoreConf.CLIENT_SOCKET_LIFETIME
*/
@Deprecated
METASTORE_CLIENT_SOCKET_LIFETIME("hive.metastore.client.socket.lifetime", "0s",
new TimeValidator(TimeUnit.SECONDS),
"MetaStore Client socket lifetime in seconds. After this time is exceeded, client\n" +
"reconnects on the next MetaStore operation. A value of 0s means the connection\n" +
"has an infinite lifetime."),
/**
* @deprecated Use MetastoreConf.PWD
*/
@Deprecated
METASTOREPWD("javax.jdo.option.ConnectionPassword", "mine",
"password to use against metastore database"),
/**
* @deprecated Use MetastoreConf.CONNECT_URL_HOOK
*/
@Deprecated
METASTORECONNECTURLHOOK("hive.metastore.ds.connection.url.hook", "",
"Name of the hook to use for retrieving the JDO connection URL. If empty, the value in javax.jdo.option.ConnectionURL is used"),
/**
* @deprecated Use MetastoreConf.MULTITHREADED
*/
@Deprecated
METASTOREMULTITHREADED("javax.jdo.option.Multithreaded", true,
"Set this to true if multiple threads access metastore through JDO concurrently."),
/**
* @deprecated Use MetastoreConf.CONNECT_URL_KEY
*/
@Deprecated
METASTORECONNECTURLKEY("javax.jdo.option.ConnectionURL",
"jdbc:derby:;databaseName=metastore_db;create=true",
"JDBC connect string for a JDBC metastore.\n" +
"To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.\n" +
"For example, jdbc:postgresql://myhost/db?ssl=true for postgres database."),
/**
* @deprecated Use MetastoreConf.DBACCESS_SSL_PROPS
*/
@Deprecated
METASTORE_DBACCESS_SSL_PROPS("hive.metastore.dbaccess.ssl.properties", "",
"Comma-separated SSL properties for metastore to access database when JDO connection URL\n" +
"enables SSL access. e.g. javax.net.ssl.trustStore=/tmp/truststore,javax.net.ssl.trustStorePassword=pwd."),
/**
* @deprecated Use MetastoreConf.HMS_HANDLER_ATTEMPTS
*/
@Deprecated
HMSHANDLERATTEMPTS("hive.hmshandler.retry.attempts", 10,
"The number of times to retry a HMSHandler call if there were a connection error."),
/**
* @deprecated Use MetastoreConf.HMS_HANDLER_INTERVAL
*/
@Deprecated
HMSHANDLERINTERVAL("hive.hmshandler.retry.interval", "2000ms",
new TimeValidator(TimeUnit.MILLISECONDS), "The time between HMSHandler retry attempts on failure."),
/**
* @deprecated Use MetastoreConf.HMS_HANDLER_FORCE_RELOAD_CONF
*/
@Deprecated
HMSHANDLERFORCERELOADCONF("hive.hmshandler.force.reload.conf", false,
"Whether to force reloading of the HMSHandler configuration (including\n" +
"the connection URL, before the next metastore query that accesses the\n" +
"datastore. Once reloaded, this value is reset to false. Used for\n" +
"testing only."),
/**
* @deprecated Use MetastoreConf.SERVER_MAX_MESSAGE_SIZE
*/
@Deprecated
METASTORESERVERMAXMESSAGESIZE("hive.metastore.server.max.message.size", 100*1024*1024L,
"Maximum message size in bytes a HMS will accept."),
/**
* @deprecated Use MetastoreConf.SERVER_MIN_THREADS
*/
@Deprecated
METASTORESERVERMINTHREADS("hive.metastore.server.min.threads", 200,
"Minimum number of worker threads in the Thrift server's pool."),
/**
* @deprecated Use MetastoreConf.SERVER_MAX_THREADS
*/
@Deprecated
METASTORESERVERMAXTHREADS("hive.metastore.server.max.threads", 1000,
"Maximum number of worker threads in the Thrift server's pool."),
/**
* @deprecated Use MetastoreConf.TCP_KEEP_ALIVE
*/
@Deprecated
METASTORE_TCP_KEEP_ALIVE("hive.metastore.server.tcp.keepalive", true,
"Whether to enable TCP keepalive for the metastore server. Keepalive will prevent accumulation of half-open connections."),
/**
* @deprecated Use MetastoreConf.WM_DEFAULT_POOL_SIZE
*/
@Deprecated
METASTORE_WM_DEFAULT_POOL_SIZE("hive.metastore.wm.default.pool.size", 4,
"The size of a default pool to create when creating an empty resource plan;\n" +
"If not positive, no default pool will be created."),
METASTORE_INT_ORIGINAL("hive.metastore.archive.intermediate.original",
"_INTERMEDIATE_ORIGINAL",
"Intermediate dir suffixes used for archiving. Not important what they\n" +
"are, as long as collisions are avoided"),
METASTORE_INT_ARCHIVED("hive.metastore.archive.intermediate.archived",
"_INTERMEDIATE_ARCHIVED", ""),
METASTORE_INT_EXTRACTED("hive.metastore.archive.intermediate.extracted",
"_INTERMEDIATE_EXTRACTED", ""),
/**
* @deprecated Use MetastoreConf.KERBEROS_KEYTAB_FILE
*/
@Deprecated
METASTORE_KERBEROS_KEYTAB_FILE("hive.metastore.kerberos.keytab.file", "",
"The path to the Kerberos Keytab file containing the metastore Thrift server's service principal."),
/**
* @deprecated Use MetastoreConf.KERBEROS_PRINCIPAL
*/
@Deprecated
METASTORE_KERBEROS_PRINCIPAL("hive.metastore.kerberos.principal",
"hive-metastore/[email protected]",
"The service principal for the metastore Thrift server. \n" +
"The special string _HOST will be replaced automatically with the correct host name."),
/**
* @deprecated Use MetastoreConf.CLIENT_KERBEROS_PRINCIPAL
*/
@Deprecated
METASTORE_CLIENT_KERBEROS_PRINCIPAL("hive.metastore.client.kerberos.principal",
"", // E.g. "hive-metastore/[email protected]".
"The Kerberos principal associated with the HA cluster of hcat_servers."),
/**
* @deprecated Use MetastoreConf.USE_THRIFT_SASL
*/
@Deprecated
METASTORE_USE_THRIFT_SASL("hive.metastore.sasl.enabled", false,
"If true, the metastore Thrift interface will be secured with SASL. Clients must authenticate with Kerberos."),
/**
* @deprecated Use MetastoreConf.USE_THRIFT_FRAMED_TRANSPORT
*/
@Deprecated
METASTORE_USE_THRIFT_FRAMED_TRANSPORT("hive.metastore.thrift.framed.transport.enabled", false,
"If true, the metastore Thrift interface will use TFramedTransport. When false (default) a standard TTransport is used."),
/**
* @deprecated Use MetastoreConf.USE_THRIFT_COMPACT_PROTOCOL
*/
@Deprecated
METASTORE_USE_THRIFT_COMPACT_PROTOCOL("hive.metastore.thrift.compact.protocol.enabled", false,
"If true, the metastore Thrift interface will use TCompactProtocol. When false (default) TBinaryProtocol will be used.\n" +
"Setting it to true will break compatibility with older clients running TBinaryProtocol."),
/**
* @deprecated Use MetastoreConf.TOKEN_SIGNATURE
*/
@Deprecated
METASTORE_TOKEN_SIGNATURE("hive.metastore.token.signature", "",
"The delegation token service name to match when selecting a token from the current user's tokens."),
/**
* @deprecated Use MetastoreConf.DELEGATION_TOKEN_STORE_CLS
*/
@Deprecated
METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_CLS("hive.cluster.delegation.token.store.class",
"org.apache.hadoop.hive.thrift.MemoryTokenStore",
"The delegation token store implementation. Set to org.apache.hadoop.hive.thrift.ZooKeeperTokenStore for load-balanced cluster."),
METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_CONNECTSTR(
"hive.cluster.delegation.token.store.zookeeper.connectString", "",
"The ZooKeeper token store connect string. You can re-use the configuration value\n" +
"set in hive.zookeeper.quorum, by leaving this parameter unset."),
METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_ZNODE(
"hive.cluster.delegation.token.store.zookeeper.znode", "/hivedelegation",
"The root path for token store data. Note that this is used by both HiveServer2 and\n" +
"MetaStore to store delegation Token. One directory gets created for each of them.\n" +
"The final directory names would have the servername appended to it (HIVESERVER2,\n" +
"METASTORE)."),
METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_ACL(
"hive.cluster.delegation.token.store.zookeeper.acl", "",
"ACL for token store entries. Comma separated list of ACL entries. For example:\n" +
"sasl:hive/[email protected]:cdrwa,sasl:hive/[email protected]:cdrwa\n" +
"Defaults to all permissions for the hiveserver2/metastore process user."),
/**
* @deprecated Use MetastoreConf.CACHE_PINOBJTYPES
*/
@Deprecated
METASTORE_CACHE_PINOBJTYPES("hive.metastore.cache.pinobjtypes", "Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order",
"List of comma separated metastore object types that should be pinned in the cache"),
/**
* @deprecated Use MetastoreConf.CONNECTION_POOLING_TYPE
*/
@Deprecated
METASTORE_CONNECTION_POOLING_TYPE("datanucleus.connectionPoolingType", "HikariCP", new StringSet("DBCP",
"HikariCP", "NONE"),
"Specify connection pool library for datanucleus"),
/**
* @deprecated Use MetastoreConf.CONNECTION_POOLING_MAX_CONNECTIONS
*/
@Deprecated
METASTORE_CONNECTION_POOLING_MAX_CONNECTIONS("datanucleus.connectionPool.maxPoolSize", 10,
"Specify the maximum number of connections in the connection pool. Note: The configured size will be used by\n" +
"2 connection pools (TxnHandler and ObjectStore). When configuring the max connection pool size, it is\n" +
"recommended to take into account the number of metastore instances and the number of HiveServer2 instances\n" +
"configured with embedded metastore. To get optimal performance, set config to meet the following condition\n"+
"(2 * pool_size * metastore_instances + 2 * pool_size * HS2_instances_with_embedded_metastore) = \n" +
"(2 * physical_core_count + hard_disk_count)."),
// Workaround for DN bug on Postgres:
// http://www.datanucleus.org/servlet/forum/viewthread_thread,7985_offset
/**
* @deprecated Use MetastoreConf.DATANUCLEUS_INIT_COL_INFO
*/
@Deprecated
METASTORE_DATANUCLEUS_INIT_COL_INFO("datanucleus.rdbms.initializeColumnInfo", "NONE",
"initializeColumnInfo setting for DataNucleus; set to NONE at least on Postgres."),
/**
* @deprecated Use MetastoreConf.VALIDATE_TABLES
*/
@Deprecated
METASTORE_VALIDATE_TABLES("datanucleus.schema.validateTables", false,
"validates existing schema against code. turn this on if you want to verify existing schema"),
/**
* @deprecated Use MetastoreConf.VALIDATE_COLUMNS
*/
@Deprecated
METASTORE_VALIDATE_COLUMNS("datanucleus.schema.validateColumns", false,
"validates existing schema against code. turn this on if you want to verify existing schema"),
/**
* @deprecated Use MetastoreConf.VALIDATE_CONSTRAINTS
*/
@Deprecated
METASTORE_VALIDATE_CONSTRAINTS("datanucleus.schema.validateConstraints", false,
"validates existing schema against code. turn this on if you want to verify existing schema"),
/**
* @deprecated Use MetastoreConf.STORE_MANAGER_TYPE
*/
@Deprecated
METASTORE_STORE_MANAGER_TYPE("datanucleus.storeManagerType", "rdbms", "metadata store type"),
/**
* @deprecated Use MetastoreConf.AUTO_CREATE_ALL
*/
@Deprecated
METASTORE_AUTO_CREATE_ALL("datanucleus.schema.autoCreateAll", false,
"Auto creates necessary schema on a startup if one doesn't exist. Set this to false, after creating it once."
+ "To enable auto create also set hive.metastore.schema.verification=false. Auto creation is not "
+ "recommended for production use cases, run schematool command instead." ),
/**
* @deprecated Use MetastoreConf.SCHEMA_VERIFICATION
*/
@Deprecated
METASTORE_SCHEMA_VERIFICATION("hive.metastore.schema.verification", true,
"Enforce metastore schema version consistency.\n" +
"True: Verify that version information stored in is compatible with one from Hive jars. Also disable automatic\n" +
" schema migration attempt. Users are required to manually migrate schema after Hive upgrade which ensures\n" +
" proper metastore schema migration. (Default)\n" +
"False: Warn if the version information stored in metastore doesn't match with one from in Hive jars."),
/**
* @deprecated Use MetastoreConf.SCHEMA_VERIFICATION_RECORD_VERSION
*/
@Deprecated
METASTORE_SCHEMA_VERIFICATION_RECORD_VERSION("hive.metastore.schema.verification.record.version", false,
"When true the current MS version is recorded in the VERSION table. If this is disabled and verification is\n" +
" enabled the MS will be unusable."),
/**
* @deprecated Use MetastoreConf.SCHEMA_INFO_CLASS
*/
@Deprecated
METASTORE_SCHEMA_INFO_CLASS("hive.metastore.schema.info.class",
"org.apache.hadoop.hive.metastore.MetaStoreSchemaInfo",
"Fully qualified class name for the metastore schema information class \n"
+ "which is used by schematool to fetch the schema information.\n"
+ " This class should implement the IMetaStoreSchemaInfo interface"),
/**
* @deprecated Use MetastoreConf.DATANUCLEUS_TRANSACTION_ISOLATION
*/
@Deprecated
METASTORE_TRANSACTION_ISOLATION("datanucleus.transactionIsolation", "read-committed",
"Default transaction isolation level for identity generation."),
/**
* @deprecated Use MetastoreConf.DATANUCLEUS_CACHE_LEVEL2
*/
@Deprecated
METASTORE_CACHE_LEVEL2("datanucleus.cache.level2", false,
"Use a level 2 cache. Turn this off if metadata is changed independently of Hive metastore server"),
METASTORE_CACHE_LEVEL2_TYPE("datanucleus.cache.level2.type", "none", ""),
/**
* @deprecated Use MetastoreConf.IDENTIFIER_FACTORY
*/
@Deprecated
METASTORE_IDENTIFIER_FACTORY("datanucleus.identifierFactory", "datanucleus1",
"Name of the identifier factory to use when generating table/column names etc. \n" +
"'datanucleus1' is used for backward compatibility with DataNucleus v1"),
/**
* @deprecated Use MetastoreConf.DATANUCLEUS_USE_LEGACY_VALUE_STRATEGY
*/
@Deprecated
METASTORE_USE_LEGACY_VALUE_STRATEGY("datanucleus.rdbms.useLegacyNativeValueStrategy", true, ""),
/**
* @deprecated Use MetastoreConf.DATANUCLEUS_PLUGIN_REGISTRY_BUNDLE_CHECK
*/
@Deprecated
METASTORE_PLUGIN_REGISTRY_BUNDLE_CHECK("datanucleus.plugin.pluginRegistryBundleCheck", "LOG",
"Defines what happens when plugin bundles are found and are duplicated [EXCEPTION|LOG|NONE]"),
/**
* @deprecated Use MetastoreConf.BATCH_RETRIEVE_MAX
*/
@Deprecated
METASTORE_BATCH_RETRIEVE_MAX("hive.metastore.batch.retrieve.max", 300,
"Maximum number of objects (tables/partitions) can be retrieved from metastore in one batch. \n" +
"The higher the number, the less the number of round trips is needed to the Hive metastore server, \n" +
"but it may also cause higher memory requirement at the client side."),
/**
* @deprecated Use MetastoreConf.BATCH_RETRIEVE_OBJECTS_MAX
*/
@Deprecated
METASTORE_BATCH_RETRIEVE_OBJECTS_MAX(
"hive.metastore.batch.retrieve.table.partition.max", 1000,
"Maximum number of objects that metastore internally retrieves in one batch."),
/**
* @deprecated Use MetastoreConf.INIT_HOOKS
*/
@Deprecated
METASTORE_INIT_HOOKS("hive.metastore.init.hooks", "",
"A comma separated list of hooks to be invoked at the beginning of HMSHandler initialization. \n" +
"An init hook is specified as the name of Java class which extends org.apache.hadoop.hive.metastore.MetaStoreInitListener."),
/**
* @deprecated Use MetastoreConf.PRE_EVENT_LISTENERS
*/
@Deprecated
METASTORE_PRE_EVENT_LISTENERS("hive.metastore.pre.event.listeners", "",
"List of comma separated listeners for metastore events."),
/**
* @deprecated Use MetastoreConf.EVENT_LISTENERS
*/
@Deprecated
METASTORE_EVENT_LISTENERS("hive.metastore.event.listeners", "",
"A comma separated list of Java classes that implement the org.apache.hadoop.hive.metastore.MetaStoreEventListener" +
" interface. The metastore event and corresponding listener method will be invoked in separate JDO transactions. " +
"Alternatively, configure hive.metastore.transactional.event.listeners to ensure both are invoked in same JDO transaction."),
/**
* @deprecated Use MetastoreConf.TRANSACTIONAL_EVENT_LISTENERS
*/
@Deprecated
METASTORE_TRANSACTIONAL_EVENT_LISTENERS("hive.metastore.transactional.event.listeners", "",
"A comma separated list of Java classes that implement the org.apache.hadoop.hive.metastore.MetaStoreEventListener" +
" interface. Both the metastore event and corresponding listener method will be invoked in the same JDO transaction."),
/**
* @deprecated Use MetastoreConf.NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES
*/
@Deprecated
NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES("hive.notification.sequence.lock.max.retries", 10,
"Number of retries required to acquire a lock when getting the next notification sequential ID for entries "
+ "in the NOTIFICATION_LOG table."),
/**
* @deprecated Use MetastoreConf.NOTIFICATION_SEQUENCE_LOCK_RETRY_SLEEP_INTERVAL
*/
@Deprecated
NOTIFICATION_SEQUENCE_LOCK_RETRY_SLEEP_INTERVAL("hive.notification.sequence.lock.retry.sleep.interval", 10L,
new TimeValidator(TimeUnit.SECONDS),
"Sleep interval between retries to acquire a notification lock as described part of property "
+ NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES.name()),
/**
* @deprecated Use MetastoreConf.EVENT_DB_LISTENER_TTL
*/
@Deprecated
METASTORE_EVENT_DB_LISTENER_TTL("hive.metastore.event.db.listener.timetolive", "86400s",
new TimeValidator(TimeUnit.SECONDS),
"time after which events will be removed from the database listener queue when repl.cm.enabled \n" +
"is set to false. When repl.cm.enabled is set to true, repl.event.db.listener.timetolive is used instead"),
/**
* @deprecated Use MetastoreConf.EVENT_DB_NOTIFICATION_API_AUTH
*/
@Deprecated
METASTORE_EVENT_DB_NOTIFICATION_API_AUTH("hive.metastore.event.db.notification.api.auth", true,
"Should metastore do authorization against database notification related APIs such as get_next_notification.\n" +
"If set to true, then only the superusers in proxy settings have the permission"),
/**
* @deprecated Use MetastoreConf.AUTHORIZATION_STORAGE_AUTH_CHECKS
*/
@Deprecated
METASTORE_AUTHORIZATION_STORAGE_AUTH_CHECKS("hive.metastore.authorization.storage.checks", false,
"Should the metastore do authorization checks against the underlying storage (usually hdfs) \n" +
"for operations like drop-partition (disallow the drop-partition if the user in\n" +
"question doesn't have permissions to delete the corresponding directory\n" +
"on the storage)."),
METASTORE_AUTHORIZATION_EXTERNALTABLE_DROP_CHECK("hive.metastore.authorization.storage.check.externaltable.drop", true,
"Should StorageBasedAuthorization check permission of the storage before dropping external table.\n" +
"StorageBasedAuthorization already does this check for managed table. For external table however,\n" +
"anyone who has read permission of the directory could drop external table, which is surprising.\n" +
"The flag is set to false by default to maintain backward compatibility."),
/**
* @deprecated Use MetastoreConf.EVENT_CLEAN_FREQ
*/
@Deprecated
METASTORE_EVENT_CLEAN_FREQ("hive.metastore.event.clean.freq", "0s",
new TimeValidator(TimeUnit.SECONDS),
"Frequency at which timer task runs to purge expired events in metastore."),
/**
* @deprecated Use MetastoreConf.EVENT_EXPIRY_DURATION
*/
@Deprecated
METASTORE_EVENT_EXPIRY_DURATION("hive.metastore.event.expiry.duration", "0s",
new TimeValidator(TimeUnit.SECONDS),
"Duration after which events expire from events table"),
/**
* @deprecated Use MetastoreConf.EVENT_MESSAGE_FACTORY
*/
@Deprecated
METASTORE_EVENT_MESSAGE_FACTORY("hive.metastore.event.message.factory",
"org.apache.hadoop.hive.metastore.messaging.json.gzip.GzipJSONMessageEncoder",
"Factory class for making encoding and decoding messages in the events generated."),
/**
* @deprecated Use MetastoreConf.EXECUTE_SET_UGI
*/
@Deprecated
METASTORE_EXECUTE_SET_UGI("hive.metastore.execute.setugi", true,
"In unsecure mode, setting this property to true will cause the metastore to execute DFS operations using \n" +
"the client's reported user and group permissions. Note that this property must be set on \n" +
"both the client and server sides. Further note that its best effort. \n" +
"If client sets its to true and server sets it to false, client setting will be ignored."),
/**
* @deprecated Use MetastoreConf.PARTITION_NAME_WHITELIST_PATTERN
*/
@Deprecated
METASTORE_PARTITION_NAME_WHITELIST_PATTERN("hive.metastore.partition.name.whitelist.pattern", "",
"Partition names will be checked against this regex pattern and rejected if not matched."),
/**
* @deprecated Use MetastoreConf.INTEGER_JDO_PUSHDOWN
*/
@Deprecated
METASTORE_INTEGER_JDO_PUSHDOWN("hive.metastore.integral.jdo.pushdown", false,
"Allow JDO query pushdown for integral partition columns in metastore. Off by default. This\n" +
"improves metastore perf for integral columns, especially if there's a large number of partitions.\n" +
"However, it doesn't work correctly with integral values that are not normalized (e.g. have\n" +
"leading zeroes, like 0012). If metastore direct SQL is enabled and works, this optimization\n" +
"is also irrelevant."),
/**
* @deprecated Use MetastoreConf.TRY_DIRECT_SQL
*/
@Deprecated
METASTORE_TRY_DIRECT_SQL("hive.metastore.try.direct.sql", true,
"Whether the Hive metastore should try to use direct SQL queries instead of the\n" +
"DataNucleus for certain read paths. This can improve metastore performance when\n" +
"fetching many partitions or column statistics by orders of magnitude; however, it\n" +
"is not guaranteed to work on all RDBMS-es and all versions. In case of SQL failures,\n" +
"the metastore will fall back to the DataNucleus, so it's safe even if SQL doesn't\n" +
"work for all queries on your datastore. If all SQL queries fail (for example, your\n" +
"metastore is backed by MongoDB), you might want to disable this to save the\n" +
"try-and-fall-back cost."),
/**
* @deprecated Use MetastoreConf.DIRECT_SQL_PARTITION_BATCH_SIZE
*/
@Deprecated
METASTORE_DIRECT_SQL_PARTITION_BATCH_SIZE("hive.metastore.direct.sql.batch.size", 0,
"Batch size for partition and other object retrieval from the underlying DB in direct\n" +
"SQL. For some DBs like Oracle and MSSQL, there are hardcoded or perf-based limitations\n" +
"that necessitate this. For DBs that can handle the queries, this isn't necessary and\n" +
"may impede performance. -1 means no batching, 0 means automatic batching."),
/**
* @deprecated Use MetastoreConf.TRY_DIRECT_SQL_DDL
*/
@Deprecated
METASTORE_TRY_DIRECT_SQL_DDL("hive.metastore.try.direct.sql.ddl", true,
"Same as hive.metastore.try.direct.sql, for read statements within a transaction that\n" +
"modifies metastore data. Due to non-standard behavior in Postgres, if a direct SQL\n" +
"select query has incorrect syntax or something similar inside a transaction, the\n" +
"entire transaction will fail and fall-back to DataNucleus will not be possible. You\n" +
"should disable the usage of direct SQL inside transactions if that happens in your case."),
/**
* @deprecated Use MetastoreConf.DIRECT_SQL_MAX_QUERY_LENGTH
*/
@Deprecated
METASTORE_DIRECT_SQL_MAX_QUERY_LENGTH("hive.direct.sql.max.query.length", 100, "The maximum\n" +
" size of a query string (in KB)."),
/**
* @deprecated Use MetastoreConf.DIRECT_SQL_MAX_ELEMENTS_IN_CLAUSE
*/
@Deprecated
METASTORE_DIRECT_SQL_MAX_ELEMENTS_IN_CLAUSE("hive.direct.sql.max.elements.in.clause", 1000,
"The maximum number of values in a IN clause. Once exceeded, it will be broken into\n" +
" multiple OR separated IN clauses."),
/**
* @deprecated Use MetastoreConf.DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE
*/
@Deprecated
METASTORE_DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE("hive.direct.sql.max.elements.values.clause",
1000, "The maximum number of values in a VALUES clause for INSERT statement."),
/**
* @deprecated Use MetastoreConf.ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS
*/
@Deprecated
METASTORE_ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS("hive.metastore.orm.retrieveMapNullsAsEmptyStrings",false,
"Thrift does not support nulls in maps, so any nulls present in maps retrieved from ORM must " +
"either be pruned or converted to empty strings. Some backing dbs such as Oracle persist empty strings " +
"as nulls, so we should set this parameter if we wish to reverse that behaviour. For others, " +
"pruning is the correct behaviour"),
/**
* @deprecated Use MetastoreConf.DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES
*/
@Deprecated
METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES(
"hive.metastore.disallow.incompatible.col.type.changes", true,
"If true (default is false), ALTER TABLE operations which change the type of a\n" +
"column (say STRING) to an incompatible type (say MAP) are disallowed.\n" +
"RCFile default SerDe (ColumnarSerDe) serializes the values in such a way that the\n" +
"datatypes can be converted from string to any type. The map is also serialized as\n" +
"a string, which can be read as a string as well. However, with any binary\n" +
"serialization, this is not true. Blocking the ALTER TABLE prevents ClassCastExceptions\n" +
"when subsequently trying to access old partitions.\n" +
"\n" +
"Primitive types like INT, STRING, BIGINT, etc., are compatible with each other and are\n" +
"not blocked.\n" +
"\n" +
"See HIVE-4409 for more details."),
/**
* @deprecated Use MetastoreConf.LIMIT_PARTITION_REQUEST
*/
@Deprecated
METASTORE_LIMIT_PARTITION_REQUEST("hive.metastore.limit.partition.request", -1,
"This limits the number of partitions that can be requested from the metastore for a given table.\n" +
"The default value \"-1\" means no limit."),
NEWTABLEDEFAULTPARA("hive.table.parameters.default", "",
"Default property values for newly created tables"),
DDL_CTL_PARAMETERS_WHITELIST("hive.ddl.createtablelike.properties.whitelist", "",
"Table Properties to copy over when executing a Create Table Like."),
/**
* @deprecated Use MetastoreConf.RAW_STORE_IMPL
*/
@Deprecated
METASTORE_RAW_STORE_IMPL("hive.metastore.rawstore.impl", "org.apache.hadoop.hive.metastore.ObjectStore",
"Name of the class that implements org.apache.hadoop.hive.metastore.rawstore interface. \n" +
"This class is used to store and retrieval of raw metadata objects such as table, database"),
/**
* @deprecated Use MetastoreConf.TXN_STORE_IMPL
*/
@Deprecated
METASTORE_TXN_STORE_IMPL("hive.metastore.txn.store.impl",
"org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler",
"Name of class that implements org.apache.hadoop.hive.metastore.txn.TxnStore. This " +
"class is used to store and retrieve transactions and locks"),
/**
* @deprecated Use MetastoreConf.CONNECTION_DRIVER
*/
@Deprecated
METASTORE_CONNECTION_DRIVER("javax.jdo.option.ConnectionDriverName", "org.apache.derby.jdbc.EmbeddedDriver",
"Driver class name for a JDBC metastore"),
/**
* @deprecated Use MetastoreConf.MANAGER_FACTORY_CLASS
*/
@Deprecated
METASTORE_MANAGER_FACTORY_CLASS("javax.jdo.PersistenceManagerFactoryClass",
"org.datanucleus.api.jdo.JDOPersistenceManagerFactory",
"class implementing the jdo persistence"),
/**
* @deprecated Use MetastoreConf.EXPRESSION_PROXY_CLASS
*/
@Deprecated
METASTORE_EXPRESSION_PROXY_CLASS("hive.metastore.expression.proxy",
"org.apache.hadoop.hive.ql.optimizer.ppr.PartitionExpressionForMetastore", ""),
/**
* @deprecated Use MetastoreConf.DETACH_ALL_ON_COMMIT
*/
@Deprecated
METASTORE_DETACH_ALL_ON_COMMIT("javax.jdo.option.DetachAllOnCommit", true,
"Detaches all objects from session so that they can be used after transaction is committed"),
/**
* @deprecated Use MetastoreConf.NON_TRANSACTIONAL_READ
*/
@Deprecated
METASTORE_NON_TRANSACTIONAL_READ("javax.jdo.option.NonTransactionalRead", true,
"Reads outside of transactions"),
/**
* @deprecated Use MetastoreConf.CONNECTION_USER_NAME
*/
@Deprecated
METASTORE_CONNECTION_USER_NAME("javax.jdo.option.ConnectionUserName", "APP",
"Username to use against metastore database"),
/**
* @deprecated Use MetastoreConf.END_FUNCTION_LISTENERS
*/
@Deprecated
METASTORE_END_FUNCTION_LISTENERS("hive.metastore.end.function.listeners", "",
"List of comma separated listeners for the end of metastore functions."),
/**
* @deprecated Use MetastoreConf.PART_INHERIT_TBL_PROPS
*/
@Deprecated
METASTORE_PART_INHERIT_TBL_PROPS("hive.metastore.partition.inherit.table.properties", "",
"List of comma separated keys occurring in table properties which will get inherited to newly created partitions. \n" +
"* implies all the keys will get inherited."),
/**
* @deprecated Use MetastoreConf.FILTER_HOOK
*/
@Deprecated
METASTORE_FILTER_HOOK("hive.metastore.filter.hook", "org.apache.hadoop.hive.metastore.DefaultMetaStoreFilterHookImpl",
"Metastore hook class for filtering the metadata read results. If hive.security.authorization.manager"
+ "is set to instance of HiveAuthorizerFactory, then this value is ignored."),
FIRE_EVENTS_FOR_DML("hive.metastore.dml.events", false, "If true, the metastore will be asked" +
" to fire events for DML operations"),
METASTORE_CLIENT_DROP_PARTITIONS_WITH_EXPRESSIONS("hive.metastore.client.drop.partitions.using.expressions", true,
"Choose whether dropping partitions with HCatClient pushes the partition-predicate to the metastore, " +
"or drops partitions iteratively"),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_ENABLED
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_ENABLED("hive.metastore.aggregate.stats.cache.enabled", false,
"Whether aggregate stats caching is enabled or not."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_SIZE
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_SIZE("hive.metastore.aggregate.stats.cache.size", 10000,
"Maximum number of aggregate stats nodes that we will place in the metastore aggregate stats cache."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_PARTITIONS
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_MAX_PARTITIONS("hive.metastore.aggregate.stats.cache.max.partitions", 10000,
"Maximum number of partitions that are aggregated per cache node."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_FPP
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_FPP("hive.metastore.aggregate.stats.cache.fpp", (float) 0.01,
"Maximum false positive probability for the Bloom Filter used in each aggregate stats cache node (default 1%)."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_VARIANCE
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_MAX_VARIANCE("hive.metastore.aggregate.stats.cache.max.variance", (float) 0.01,
"Maximum tolerable variance in number of partitions between a cached node and our request (default 1%)."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_TTL
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_TTL("hive.metastore.aggregate.stats.cache.ttl", "600s", new TimeValidator(TimeUnit.SECONDS),
"Number of seconds for a cached node to be active in the cache before they become stale."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT("hive.metastore.aggregate.stats.cache.max.writer.wait", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Number of milliseconds a writer will wait to acquire the writelock before giving up."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_READER_WAIT
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_MAX_READER_WAIT("hive.metastore.aggregate.stats.cache.max.reader.wait", "1000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Number of milliseconds a reader will wait to acquire the readlock before giving up."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_FULL
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_MAX_FULL("hive.metastore.aggregate.stats.cache.max.full", (float) 0.9,
"Maximum cache full % after which the cache cleaner thread kicks in."),
/**
* @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_CLEAN_UNTIL
*/
@Deprecated
METASTORE_AGGREGATE_STATS_CACHE_CLEAN_UNTIL("hive.metastore.aggregate.stats.cache.clean.until", (float) 0.8,
"The cleaner thread cleans until cache reaches this % full size."),
/**
* @deprecated Use MetastoreConf.METRICS_ENABLED
*/
@Deprecated
METASTORE_METRICS("hive.metastore.metrics.enabled", false, "Enable metrics on the metastore."),
/**
* @deprecated Use MetastoreConf.INIT_METADATA_COUNT_ENABLED
*/
@Deprecated
METASTORE_INIT_METADATA_COUNT_ENABLED("hive.metastore.initial.metadata.count.enabled", true,
"Enable a metadata count at metastore startup for metrics."),
// Metastore SSL settings
/**
* @deprecated Use MetastoreConf.USE_SSL
*/
@Deprecated
HIVE_METASTORE_USE_SSL("hive.metastore.use.SSL", false,
"Set this to true for using SSL encryption in HMS server."),
/**
* @deprecated Use MetastoreConf.SSL_KEYSTORE_PATH
*/
@Deprecated
HIVE_METASTORE_SSL_KEYSTORE_PATH("hive.metastore.keystore.path", "",
"Metastore SSL certificate keystore location."),
/**
* @deprecated Use MetastoreConf.SSL_KEYSTORE_PASSWORD
*/
@Deprecated
HIVE_METASTORE_SSL_KEYSTORE_PASSWORD("hive.metastore.keystore.password", "",
"Metastore SSL certificate keystore password."),
/**
* @deprecated Use MetastoreConf.SSL_TRUSTSTORE_PATH
*/
@Deprecated
HIVE_METASTORE_SSL_TRUSTSTORE_PATH("hive.metastore.truststore.path", "",
"Metastore SSL certificate truststore location."),
/**
* @deprecated Use MetastoreConf.SSL_TRUSTSTORE_PASSWORD
*/
@Deprecated
HIVE_METASTORE_SSL_TRUSTSTORE_PASSWORD("hive.metastore.truststore.password", "",
"Metastore SSL certificate truststore password."),
// Parameters for exporting metadata on table drop (requires the use of the)
// org.apache.hadoop.hive.ql.parse.MetaDataExportListener preevent listener
/**
* @deprecated Use MetastoreConf.METADATA_EXPORT_LOCATION
*/
@Deprecated
METADATA_EXPORT_LOCATION("hive.metadata.export.location", "",
"When used in conjunction with the org.apache.hadoop.hive.ql.parse.MetaDataExportListener pre event listener, \n" +
"it is the location to which the metadata will be exported. The default is an empty string, which results in the \n" +
"metadata being exported to the current user's home directory on HDFS."),
/**
* @deprecated Use MetastoreConf.MOVE_EXPORTED_METADATA_TO_TRASH
*/
@Deprecated
MOVE_EXPORTED_METADATA_TO_TRASH("hive.metadata.move.exported.metadata.to.trash", true,
"When used in conjunction with the org.apache.hadoop.hive.ql.parse.MetaDataExportListener pre event listener, \n" +
"this setting determines if the metadata that is exported will subsequently be moved to the user's trash directory \n" +
"alongside the dropped table data. This ensures that the metadata will be cleaned up along with the dropped table data."),
// CLI
CLIIGNOREERRORS("hive.cli.errors.ignore", false, ""),
CLIPRINTCURRENTDB("hive.cli.print.current.db", false,
"Whether to include the current database in the Hive prompt."),
CLIPROMPT("hive.cli.prompt", "hive",
"Command line prompt configuration value. Other hiveconf can be used in this configuration value. \n" +
"Variable substitution will only be invoked at the Hive CLI startup."),
/**
* @deprecated Use MetastoreConf.FS_HANDLER_CLS
*/
@Deprecated
HIVE_METASTORE_FS_HANDLER_CLS("hive.metastore.fs.handler.class", "org.apache.hadoop.hive.metastore.HiveMetaStoreFsImpl", ""),
// Things we log in the jobconf
// session identifier
HIVESESSIONID("hive.session.id", "", ""),
// whether session is running in silent mode or not
HIVESESSIONSILENT("hive.session.silent", false, ""),
HIVE_LOCAL_TIME_ZONE("hive.local.time.zone", "LOCAL",
"Sets the time-zone for displaying and interpreting time stamps. If this property value is set to\n" +
"LOCAL, it is not specified, or it is not a correct time-zone, the system default time-zone will be\n " +
"used instead. Time-zone IDs can be specified as region-based zone IDs (based on IANA time-zone data),\n" +
"abbreviated zone IDs, or offset IDs."),
HIVE_SESSION_HISTORY_ENABLED("hive.session.history.enabled", false,
"Whether to log Hive query, query plan, runtime statistics etc."),
HIVEQUERYSTRING("hive.query.string", "",
"Query being executed (might be multiple per a session)"),
HIVEQUERYID("hive.query.id", "",
"ID for query being executed (might be multiple per a session)"),
HIVEQUERYTAG("hive.query.tag", null, "Tag for the queries in the session. User can kill the queries with the tag " +
"in another session. Currently there is no tag duplication check, user need to make sure his tag is unique. " +
"Also 'kill query' needs to be issued to all HiveServer2 instances to proper kill the queries"),
HIVESPARKJOBNAMELENGTH("hive.spark.jobname.length", 100000, "max jobname length for Hive on " +
"Spark queries"),
HIVEJOBNAMELENGTH("hive.jobname.length", 50, "max jobname length"),
// hive jar
HIVEJAR("hive.jar.path", "",
"The location of hive_cli.jar that is used when submitting jobs in a separate jvm."),
HIVEAUXJARS("hive.aux.jars.path", "",
"The location of the plugin jars that contain implementations of user defined functions and serdes."),
// reloadable jars
HIVERELOADABLEJARS("hive.reloadable.aux.jars.path", "",
"The locations of the plugin jars, which can be a comma-separated folders or jars. Jars can be renewed\n"
+ "by executing reload command. And these jars can be "
+ "used as the auxiliary classes like creating a UDF or SerDe."),
// hive added files and jars
HIVEADDEDFILES("hive.added.files.path", "", "This an internal parameter."),
HIVEADDEDJARS("hive.added.jars.path", "", "This an internal parameter."),
HIVEADDEDARCHIVES("hive.added.archives.path", "", "This an internal parameter."),
HIVEADDFILESUSEHDFSLOCATION("hive.resource.use.hdfs.location", true, "Reference HDFS based files/jars directly instead of "
+ "copy to session based HDFS scratch directory, to make distributed cache more useful."),
HIVE_CURRENT_DATABASE("hive.current.database", "", "Database name used by current session. Internal usage only.", true),
// for hive script operator
HIVES_AUTO_PROGRESS_TIMEOUT("hive.auto.progress.timeout", "0s",
new TimeValidator(TimeUnit.SECONDS),
"How long to run autoprogressor for the script/UDTF operators.\n" +
"Set to 0 for forever."),
HIVESCRIPTAUTOPROGRESS("hive.script.auto.progress", false,
"Whether Hive Transform/Map/Reduce Clause should automatically send progress information to TaskTracker \n" +
"to avoid the task getting killed because of inactivity. Hive sends progress information when the script is \n" +
"outputting to stderr. This option removes the need of periodically producing stderr messages, \n" +
"but users should be cautious because this may prevent infinite loops in the scripts to be killed by TaskTracker."),
HIVESCRIPTIDENVVAR("hive.script.operator.id.env.var", "HIVE_SCRIPT_OPERATOR_ID",
"Name of the environment variable that holds the unique script operator ID in the user's \n" +
"transform function (the custom mapper/reducer that the user has specified in the query)"),
HIVESCRIPTTRUNCATEENV("hive.script.operator.truncate.env", false,
"Truncate each environment variable for external script in scripts operator to 20KB (to fit system limits)"),
HIVESCRIPT_ENV_BLACKLIST("hive.script.operator.env.blacklist",
"hive.txn.valid.txns,hive.txn.tables.valid.writeids,hive.txn.valid.writeids,hive.script.operator.env.blacklist,hive.repl.current.table.write.id",
"Comma separated list of keys from the configuration file not to convert to environment " +
"variables when invoking the script operator"),
HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT("hive.strict.checks.orderby.no.limit", false,
"Enabling strict large query checks disallows the following:\n" +
" Orderby without limit.\n" +
"Note that this check currently does not consider data size, only the query pattern."),
HIVE_STRICT_CHECKS_NO_PARTITION_FILTER("hive.strict.checks.no.partition.filter", false,
"Enabling strict large query checks disallows the following:\n" +
" No partition being picked up for a query against partitioned table.\n" +
"Note that this check currently does not consider data size, only the query pattern."),
HIVE_STRICT_CHECKS_TYPE_SAFETY("hive.strict.checks.type.safety", true,
"Enabling strict type safety checks disallows the following:\n" +
" Comparing bigints and strings/(var)chars.\n" +
" Comparing bigints and doubles."),
HIVE_STRICT_CHECKS_CARTESIAN("hive.strict.checks.cartesian.product", false,
"Enabling strict Cartesian join checks disallows the following:\n" +
" Cartesian product (cross join)."),
HIVE_STRICT_CHECKS_BUCKETING("hive.strict.checks.bucketing", true,
"Enabling strict bucketing checks disallows the following:\n" +
" Load into bucketed tables."),
HIVE_STRICT_TIMESTAMP_CONVERSION("hive.strict.timestamp.conversion", true,
"Restricts unsafe numeric to timestamp conversions"),
HIVE_LOAD_DATA_OWNER("hive.load.data.owner", "",
"Set the owner of files loaded using load data in managed tables."),
@Deprecated
HIVEMAPREDMODE("hive.mapred.mode", null,
"Deprecated; use hive.strict.checks.* settings instead."),
HIVEALIAS("hive.alias", "", ""),
HIVEMAPSIDEAGGREGATE("hive.map.aggr", true, "Whether to use map-side aggregation in Hive Group By queries"),
HIVEGROUPBYSKEW("hive.groupby.skewindata", false, "Whether there is skew in data to optimize group by queries"),
HIVEJOINEMITINTERVAL("hive.join.emit.interval", 1000,
"How many rows in the right-most join operand Hive should buffer before emitting the join result."),
HIVEJOINCACHESIZE("hive.join.cache.size", 25000,
"How many rows in the joining tables (except the streaming table) should be cached in memory."),
HIVE_PUSH_RESIDUAL_INNER("hive.join.inner.residual", false,
"Whether to push non-equi filter predicates within inner joins. This can improve efficiency in "
+ "the evaluation of certain joins, since we will not be emitting rows which are thrown away by "
+ "a Filter operator straight away. However, currently vectorization does not support them, thus "
+ "enabling it is only recommended when vectorization is disabled."),
HIVE_PTF_RANGECACHE_SIZE("hive.ptf.rangecache.size", 10000,
"Size of the cache used on reducer side, that stores boundaries of ranges within a PTF " +
"partition. Used if a query specifies a RANGE type window including an orderby clause." +
"Set this to 0 to disable this cache."),
// CBO related
HIVE_CBO_ENABLED("hive.cbo.enable", true, "Flag to control enabling Cost Based Optimizations using Calcite framework."),
HIVE_CBO_CNF_NODES_LIMIT("hive.cbo.cnf.maxnodes", -1, "When converting to conjunctive normal form (CNF), fail if" +
"the expression exceeds this threshold; the threshold is expressed in terms of number of nodes (leaves and" +
"interior nodes). -1 to not set up a threshold."),
HIVE_CBO_RETPATH_HIVEOP("hive.cbo.returnpath.hiveop", false, "Flag to control calcite plan to hive operator conversion"),
HIVE_CBO_EXTENDED_COST_MODEL("hive.cbo.costmodel.extended", false, "Flag to control enabling the extended cost model based on"
+ "CPU, IO and cardinality. Otherwise, the cost model is based on cardinality."),
HIVE_CBO_COST_MODEL_CPU("hive.cbo.costmodel.cpu", "0.000001", "Default cost of a comparison"),
HIVE_CBO_COST_MODEL_NET("hive.cbo.costmodel.network", "150.0", "Default cost of a transferring a byte over network;"
+ " expressed as multiple of CPU cost"),
HIVE_CBO_COST_MODEL_LFS_WRITE("hive.cbo.costmodel.local.fs.write", "4.0", "Default cost of writing a byte to local FS;"
+ " expressed as multiple of NETWORK cost"),
HIVE_CBO_COST_MODEL_LFS_READ("hive.cbo.costmodel.local.fs.read", "4.0", "Default cost of reading a byte from local FS;"
+ " expressed as multiple of NETWORK cost"),
HIVE_CBO_COST_MODEL_HDFS_WRITE("hive.cbo.costmodel.hdfs.write", "10.0", "Default cost of writing a byte to HDFS;"
+ " expressed as multiple of Local FS write cost"),
HIVE_CBO_COST_MODEL_HDFS_READ("hive.cbo.costmodel.hdfs.read", "1.5", "Default cost of reading a byte from HDFS;"
+ " expressed as multiple of Local FS read cost"),
HIVE_CBO_SHOW_WARNINGS("hive.cbo.show.warnings", true,
"Toggle display of CBO warnings like missing column stats"),
HIVE_CBO_STATS_CORRELATED_MULTI_KEY_JOINS("hive.cbo.stats.correlated.multi.key.joins", true,
"When CBO estimates output rows for a join involving multiple columns, the default behavior assumes" +
"the columns are independent. Setting this flag to true will cause the estimator to assume" +
"the columns are correlated."),
HIVE_CARDINALITY_PRESERVING_JOIN_OPTIMIZATION_FACTOR("hive.cardinality.preserving.join.optimization.factor", 1.0f,
"Original plan cost multiplier for rewriting when query has tables joined multiple time on primary/unique key and " +
"projected the majority of columns from these table. This optimization trims fields at root of tree and " +
"then joins back affected tables at top of tree to get rest of columns. " +
"Set this to 0.0 to disable this optimization or increase it for more aggressive optimization."),
AGGR_JOIN_TRANSPOSE("hive.transpose.aggr.join", false, "push aggregates through join"),
AGGR_JOIN_TRANSPOSE_UNIQUE("hive.transpose.aggr.join.unique", true, "push aggregates through join(s) in "
+ "case data is regrouped on a previously unique column"),
SEMIJOIN_CONVERSION("hive.optimize.semijoin.conversion", true, "convert group by followed by inner equi join into semijoin"),
HIVE_COLUMN_ALIGNMENT("hive.order.columnalignment", true, "Flag to control whether we want to try to align" +
"columns in operators such as Aggregate or Join so that we try to reduce the number of shuffling stages"),
// materialized views
HIVE_MATERIALIZED_VIEW_ENABLE_AUTO_REWRITING("hive.materializedview.rewriting", true,
"Whether to try to rewrite queries using the materialized views enabled for rewriting"),
HIVE_MATERIALIZED_VIEW_ENABLE_AUTO_REWRITING_SQL("hive.materializedview.rewriting.sql", true,
"Whether to try to rewrite queries using the materialized views enabled for rewriting by comparing the sql " +
"query text with the materialized views query text"),
HIVE_MATERIALIZED_VIEW_REWRITING_SELECTION_STRATEGY("hive.materializedview.rewriting.strategy", "heuristic",
new StringSet("heuristic", "costbased"),
"The strategy that should be used to cost and select the materialized view rewriting. \n" +
" heuristic: Always try to select the plan using the materialized view if rewriting produced one," +
"choosing the plan with lower cost among possible plans containing a materialized view\n" +
" costbased: Fully cost-based strategy, always use plan with lower cost, independently on whether " +
"it uses a materialized view or not"),
HIVE_MATERIALIZED_VIEW_REWRITING_TIME_WINDOW("hive.materializedview.rewriting.time.window", "0min", new TimeValidator(TimeUnit.MINUTES),
"Time window, specified in seconds, after which outdated materialized views become invalid for automatic query rewriting.\n" +
"For instance, if more time than the value assigned to the property has passed since the materialized view " +
"was created or rebuilt, and one of its source tables has changed since, the materialized view will not be " +
"considered for rewriting. Default value 0 means that the materialized view cannot be " +
"outdated to be used automatically in query rewriting. Value -1 means to skip this check."),
HIVE_MATERIALIZED_VIEW_REWRITING_INCREMENTAL("hive.materializedview.rewriting.incremental", false,
"Whether to try to execute incremental rewritings based on outdated materializations and\n" +
"current content of tables. Default value of true effectively amounts to enabling incremental\n" +
"rebuild for the materializations too."),
HIVE_MATERIALIZED_VIEW_REBUILD_INCREMENTAL("hive.materializedview.rebuild.incremental", true,
"Whether to try to execute incremental rebuild for the materialized views. Incremental rebuild\n" +
"tries to modify the original materialization contents to reflect the latest changes to the\n" +
"materialized view source tables, instead of rebuilding the contents fully. Incremental rebuild\n" +
"is based on the materialized view algebraic incremental rewriting."),
HIVE_MATERIALIZED_VIEW_REBUILD_INCREMENTAL_FACTOR("hive.materializedview.rebuild.incremental.factor", 0.1f,
"The estimated cost of the resulting plan for incremental maintenance of materialization\n" +
"with aggregations will be multiplied by this value. Reducing the value can be useful to\n" +
"favour incremental rebuild over full rebuild."),
HIVE_MATERIALIZED_VIEW_FILE_FORMAT("hive.materializedview.fileformat", "ORC",
new StringSet("none", "TextFile", "SequenceFile", "RCfile", "ORC"),
"Default file format for CREATE MATERIALIZED VIEW statement"),
HIVE_MATERIALIZED_VIEW_SERDE("hive.materializedview.serde",
"org.apache.hadoop.hive.ql.io.orc.OrcSerde", "Default SerDe used for materialized views"),
HIVE_ENABLE_JDBC_PUSHDOWN("hive.jdbc.pushdown.enable", true,
"Flag to control enabling pushdown of operators into JDBC connection and subsequent SQL generation\n" +
"using Calcite"),
HIVE_ENABLE_JDBC_SAFE_PUSHDOWN("hive.jdbc.pushdown.safe.enable", false,
"Flag to control enabling pushdown of operators using Calcite that prevent splitting results\n" +
"retrieval in the JDBC storage handler"),
// hive.mapjoin.bucket.cache.size has been replaced by hive.smbjoin.cache.row,
// need to remove by hive .13. Also, do not change default (see SMB operator)
HIVEMAPJOINBUCKETCACHESIZE("hive.mapjoin.bucket.cache.size", 100, ""),
HIVEMAPJOINUSEOPTIMIZEDTABLE("hive.mapjoin.optimized.hashtable", true,
"Whether Hive should use memory-optimized hash table for MapJoin.\n" +
"Only works on Tez and Spark, because memory-optimized hashtable cannot be serialized."),
HIVEMAPJOINOPTIMIZEDTABLEPROBEPERCENT("hive.mapjoin.optimized.hashtable.probe.percent",
(float) 0.5, "Probing space percentage of the optimized hashtable"),
HIVEUSEHYBRIDGRACEHASHJOIN("hive.mapjoin.hybridgrace.hashtable", false, "Whether to use hybrid" +
"grace hash join as the join method for mapjoin. Tez only."),
HIVEHYBRIDGRACEHASHJOINMEMCHECKFREQ("hive.mapjoin.hybridgrace.memcheckfrequency", 1024, "For " +
"hybrid grace hash join, how often (how many rows apart) we check if memory is full. " +
"This number should be power of 2."),
HIVEHYBRIDGRACEHASHJOINMINWBSIZE("hive.mapjoin.hybridgrace.minwbsize", 524288, "For hybrid grace" +
"Hash join, the minimum write buffer size used by optimized hashtable. Default is 512 KB."),
HIVEHYBRIDGRACEHASHJOINMINNUMPARTITIONS("hive.mapjoin.hybridgrace.minnumpartitions", 16, "For" +
"Hybrid grace hash join, the minimum number of partitions to create."),
HIVEHASHTABLEWBSIZE("hive.mapjoin.optimized.hashtable.wbsize", 8 * 1024 * 1024,
"Optimized hashtable (see hive.mapjoin.optimized.hashtable) uses a chain of buffers to\n" +
"store data. This is one buffer size. HT may be slightly faster if this is larger, but for small\n" +
"joins unnecessary memory will be allocated and then trimmed."),
HIVEHYBRIDGRACEHASHJOINBLOOMFILTER("hive.mapjoin.hybridgrace.bloomfilter", true, "Whether to " +
"use BloomFilter in Hybrid grace hash join to minimize unnecessary spilling."),
HIVEMAPJOINFULLOUTER("hive.mapjoin.full.outer", true,
"Whether to use MapJoin for FULL OUTER JOINs."),
HIVE_TEST_MAPJOINFULLOUTER_OVERRIDE(
"hive.test.mapjoin.full.outer.override",
"none", new StringSet("none", "enable", "disable"),
"internal use only, used to override the hive.mapjoin.full.outer\n" +
"setting. Using enable will force it on and disable will force it off.\n" +
"The default none is do nothing, of course",
true),
HIVESMBJOINCACHEROWS("hive.smbjoin.cache.rows", 10000,
"How many rows with the same key value should be cached in memory per smb joined table."),
HIVEGROUPBYMAPINTERVAL("hive.groupby.mapaggr.checkinterval", 100000,
"Number of rows after which size of the grouping keys/aggregation classes is performed"),
HIVEMAPAGGRHASHMEMORY("hive.map.aggr.hash.percentmemory", (float) 0.5,
"Portion of total memory to be used by map-side group aggregation hash table"),
HIVEMAPJOINFOLLOWEDBYMAPAGGRHASHMEMORY("hive.mapjoin.followby.map.aggr.hash.percentmemory", (float) 0.3,
"Portion of total memory to be used by map-side group aggregation hash table, when this group by is followed by map join"),
HIVEMAPAGGRMEMORYTHRESHOLD("hive.map.aggr.hash.force.flush.memory.threshold", (float) 0.9,
"The max memory to be used by map-side group aggregation hash table.\n" +
"If the memory usage is higher than this number, force to flush data"),
HIVEMAPAGGRHASHMINREDUCTION("hive.map.aggr.hash.min.reduction", (float) 0.99,
"Hash aggregation will be turned off if the ratio between hash table size and input rows is bigger than this number. \n" +
"Set to 1 to make sure hash aggregation is never turned off."),
HIVEMAPAGGRHASHMINREDUCTIONLOWERBOUND("hive.map.aggr.hash.min.reduction.lower.bound", (float) 0.4,
"Lower bound of Hash aggregate reduction filter. See also: hive.map.aggr.hash.min.reduction"),
HIVEMAPAGGRHASHMINREDUCTIONSTATSADJUST("hive.map.aggr.hash.min.reduction.stats", true,
"Whether the value for hive.map.aggr.hash.min.reduction should be set statically using stats estimates. \n" +
"If this is enabled, the default value for hive.map.aggr.hash.min.reduction is only used as an upper-bound\n" +
"for the value set in the map-side group by operators."),
HIVEMULTIGROUPBYSINGLEREDUCER("hive.multigroupby.singlereducer", true,
"Whether to optimize multi group by query to generate single M/R job plan. If the multi group by query has \n" +
"common group by keys, it will be optimized to generate single M/R job."),
HIVE_MAP_GROUPBY_SORT("hive.map.groupby.sorted", true,
"If the bucketing/sorting properties of the table exactly match the grouping key, whether to perform \n" +
"the group by in the mapper by using BucketizedHiveInputFormat. The only downside to this\n" +
"is that it limits the number of mappers to the number of files."),
HIVE_DEFAULT_NULLS_LAST("hive.default.nulls.last", true,
"Whether to set NULLS LAST as the default null ordering for ASC order and " +
"NULLS FIRST for DESC order."),
HIVE_GROUPBY_POSITION_ALIAS("hive.groupby.position.alias", false,
"Whether to enable using Column Position Alias in Group By"),
HIVE_ORDERBY_POSITION_ALIAS("hive.orderby.position.alias", true,
"Whether to enable using Column Position Alias in Order By"),
@Deprecated
HIVE_GROUPBY_ORDERBY_POSITION_ALIAS("hive.groupby.orderby.position.alias", false,
"Whether to enable using Column Position Alias in Group By or Order By (deprecated).\n" +
"Use " + HIVE_ORDERBY_POSITION_ALIAS.varname + " or " + HIVE_GROUPBY_POSITION_ALIAS.varname + " instead"),
HIVE_NEW_JOB_GROUPING_SET_CARDINALITY("hive.new.job.grouping.set.cardinality", 30,
"Whether a new map-reduce job should be launched for grouping sets/rollups/cubes.\n" +
"For a query like: select a, b, c, count(1) from T group by a, b, c with rollup;\n" +
"4 rows are created per row: (a, b, c), (a, b, null), (a, null, null), (null, null, null).\n" +
"This can lead to explosion across map-reduce boundary if the cardinality of T is very high,\n" +
"and map-side aggregation does not do a very good job. \n" +
"\n" +
"This parameter decides if Hive should add an additional map-reduce job. If the grouping set\n" +
"cardinality (4 in the example above), is more than this value, a new MR job is added under the\n" +
"assumption that the original group by will reduce the data size."),
HIVE_GROUPBY_LIMIT_EXTRASTEP("hive.groupby.limit.extrastep", true, "This parameter decides if Hive should \n" +
"create new MR job for sorting final output"),
// Max file num and size used to do a single copy (after that, distcp is used)
HIVE_EXEC_COPYFILE_MAXNUMFILES("hive.exec.copyfile.maxnumfiles", 1L,
"Maximum number of files Hive uses to do sequential HDFS copies between directories." +
"Distributed copies (distcp) will be used instead for larger numbers of files so that copies can be done faster."),
HIVE_EXEC_COPYFILE_MAXSIZE("hive.exec.copyfile.maxsize", 32L * 1024 * 1024 /*32M*/,
"Maximum file size (in bytes) that Hive uses to do single HDFS copies between directories." +
"Distributed copies (distcp) will be used instead for bigger files so that copies can be done faster."),
// for hive udtf operator
HIVEUDTFAUTOPROGRESS("hive.udtf.auto.progress", false,
"Whether Hive should automatically send progress information to TaskTracker \n" +
"when using UDTF's to prevent the task getting killed because of inactivity. Users should be cautious \n" +
"because this may prevent TaskTracker from killing tasks with infinite loops."),
HIVEDEFAULTFILEFORMAT("hive.default.fileformat", "TextFile", new StringSet("TextFile", "SequenceFile", "RCfile", "ORC", "parquet"),
"Default file format for CREATE TABLE statement. Users can explicitly override it by CREATE TABLE ... STORED AS [FORMAT]"),
HIVEDEFAULTMANAGEDFILEFORMAT("hive.default.fileformat.managed", "none",
new StringSet("none", "TextFile", "SequenceFile", "RCfile", "ORC", "parquet"),
"Default file format for CREATE TABLE statement applied to managed tables only. External tables will be \n" +
"created with format specified by hive.default.fileformat. Leaving this null will result in using hive.default.fileformat \n" +
"for all tables."),
HIVE_DEFAULT_STORAGE_HANDLER("hive.default.storage.handler.class", "",
"Default storage handler class for CREATE TABLE statements. If this is set to a valid class, a 'CREATE TABLE ... STORED AS ... LOCATION ...' command will " +
"be equivalent to 'CREATE TABLE ... STORED BY [default.storage.handler.class] LOCATION ...'. Any STORED AS clauses will be ignored, given that STORED BY and STORED AS are " +
"incompatible within the same command. Users can explicitly override the default class by issuing 'CREATE TABLE ... STORED BY [overriding.storage.handler.class] ...'"),
HIVEQUERYRESULTFILEFORMAT("hive.query.result.fileformat", ResultFileFormat.SEQUENCEFILE.toString(),
new StringSet(ResultFileFormat.getValidSet()),
"Default file format for storing result of the query."),
HIVECHECKFILEFORMAT("hive.fileformat.check", true, "Whether to check file format or not when loading data files"),
// default serde for rcfile
HIVEDEFAULTRCFILESERDE("hive.default.rcfile.serde",
"org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe",
"The default SerDe Hive will use for the RCFile format"),
HIVEDEFAULTSERDE("hive.default.serde",
"org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
"The default SerDe Hive will use for storage formats that do not specify a SerDe."),
/**
* @deprecated Use MetastoreConf.SERDES_USING_METASTORE_FOR_SCHEMA
*/
@Deprecated
SERDESUSINGMETASTOREFORSCHEMA("hive.serdes.using.metastore.for.schema",
"org.apache.hadoop.hive.ql.io.orc.OrcSerde," +
"org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe," +
"org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe," +
"org.apache.hadoop.hive.serde2.MetadataTypedColumnsetSerDe," +
"org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe," +
"org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe," +
"org.apache.hadoop.hive.serde2.lazybinary.LazyBinarySerDe," +
"org.apache.hadoop.hive.serde2.OpenCSVSerde",
"SerDes retrieving schema from metastore. This is an internal parameter."),
@Deprecated
HIVE_LEGACY_SCHEMA_FOR_ALL_SERDES("hive.legacy.schema.for.all.serdes",
false,
"A backward compatibility setting for external metastore users that do not handle \n" +
SERDESUSINGMETASTOREFORSCHEMA.varname + " correctly. This may be removed at any time."),
HIVEHISTORYFILELOC("hive.querylog.location",
"${system:java.io.tmpdir}" + File.separator + "${system:user.name}",
"Location of Hive run time structured log file"),
HIVE_LOG_INCREMENTAL_PLAN_PROGRESS("hive.querylog.enable.plan.progress", true,
"Whether to log the plan's progress every time a job's progress is checked.\n" +
"These logs are written to the location specified by hive.querylog.location"),
HIVE_LOG_INCREMENTAL_PLAN_PROGRESS_INTERVAL("hive.querylog.plan.progress.interval", "60000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"The interval to wait between logging the plan's progress.\n" +
"If there is a whole number percentage change in the progress of the mappers or the reducers,\n" +
"the progress is logged regardless of this value.\n" +
"The actual interval will be the ceiling of (this value divided by the value of\n" +
"hive.exec.counters.pull.interval) multiplied by the value of hive.exec.counters.pull.interval\n" +
"I.e. if it is not divide evenly by the value of hive.exec.counters.pull.interval it will be\n" +
"logged less frequently than specified.\n" +
"This only has an effect if hive.querylog.enable.plan.progress is set to true."),
HIVESCRIPTSERDE("hive.script.serde", "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
"The default SerDe for transmitting input data to and reading output data from the user scripts. "),
HIVESCRIPTRECORDREADER("hive.script.recordreader",
"org.apache.hadoop.hive.ql.exec.TextRecordReader",
"The default record reader for reading data from the user scripts. "),
HIVESCRIPTRECORDWRITER("hive.script.recordwriter",
"org.apache.hadoop.hive.ql.exec.TextRecordWriter",
"The default record writer for writing data to the user scripts. "),
HIVESCRIPTESCAPE("hive.transform.escape.input", false,
"This adds an option to escape special chars (newlines, carriage returns and\n" +
"tabs) when they are passed to the user script. This is useful if the Hive tables\n" +
"can contain data that contains special characters."),
HIVEBINARYRECORDMAX("hive.binary.record.max.length", 1000,
"Read from a binary stream and treat each hive.binary.record.max.length bytes as a record. \n" +
"The last record before the end of stream can have less than hive.binary.record.max.length bytes"),
HIVEHADOOPMAXMEM("hive.mapred.local.mem", 0, "mapper/reducer memory in local mode"),
//small table file size
HIVESMALLTABLESFILESIZE("hive.mapjoin.smalltable.filesize", 25000000L,
"The threshold for the input file size of the small tables; if the file size is smaller \n" +
"than this threshold, it will try to convert the common join into map join"),
HIVE_SCHEMA_EVOLUTION("hive.exec.schema.evolution", true,
"Use schema evolution to convert self-describing file format's data to the schema desired by the reader."),
HIVE_ORC_FORCE_POSITIONAL_SCHEMA_EVOLUTION("orc.force.positional.evolution", true,
"Whether to use column position based schema evolution or not (as opposed to column name based evolution)"),
/** Don't use this directly - use AcidUtils! */
HIVE_TRANSACTIONAL_TABLE_SCAN("hive.transactional.table.scan", false,
"internal usage only -- do transaction (ACID or insert-only) table scan.", true),
HIVE_TRANSACTIONAL_NUM_EVENTS_IN_MEMORY("hive.transactional.events.mem", 10000000,
"Vectorized ACID readers can often load all the delete events from all the delete deltas\n"
+ "into memory to optimize for performance. To prevent out-of-memory errors, this is a rough heuristic\n"
+ "that limits the total number of delete events that can be loaded into memory at once.\n"
+ "Roughly it has been set to 10 million delete events per bucket (~160 MB).\n"),
FILTER_DELETE_EVENTS("hive.txn.filter.delete.events", true,
"If true, VectorizedOrcAcidRowBatchReader will compute min/max " +
"ROW__ID for the split and only load delete events in that range.\n"
),
HIVESAMPLERANDOMNUM("hive.sample.seednumber", 0,
"A number used to percentage sampling. By changing this number, user will change the subsets of data sampled."),
// test mode in hive mode
HIVETESTMODE("hive.test.mode", false,
"Whether Hive is running in test mode. If yes, it turns on sampling and prefixes the output tablename.",
false),
HIVEEXIMTESTMODE("hive.exim.test.mode", false,
"The subset of test mode that only enables custom path handling for ExIm.", false),
HIVETESTMODEPREFIX("hive.test.mode.prefix", "test_",
"In test mode, specifies prefixes for the output table", false),
HIVETESTMODESAMPLEFREQ("hive.test.mode.samplefreq", 32,
"In test mode, specifies sampling frequency for table, which is not bucketed,\n" +
"For example, the following query:\n" +
" INSERT OVERWRITE TABLE dest SELECT col1 from src\n" +
"would be converted to\n" +
" INSERT OVERWRITE TABLE test_dest\n" +
" SELECT col1 from src TABLESAMPLE (BUCKET 1 out of 32 on rand(1))", false),
HIVETESTMODENOSAMPLE("hive.test.mode.nosamplelist", "",
"In test mode, specifies comma separated table names which would not apply sampling", false),
HIVETESTMODEDUMMYSTATAGGR("hive.test.dummystats.aggregator", "", "internal variable for test", false),
HIVETESTMODEDUMMYSTATPUB("hive.test.dummystats.publisher", "", "internal variable for test", false),
HIVETESTCURRENTTIMESTAMP("hive.test.currenttimestamp", null, "current timestamp for test", false),
HIVETESTMODEROLLBACKTXN("hive.test.rollbacktxn", false, "For testing only. Will mark every ACID transaction aborted", false),
HIVETESTMODEFAILCOMPACTION("hive.test.fail.compaction", false, "For testing only. Will cause CompactorMR to fail.", false),
HIVETESTMODEFAILLOADDYNAMICPARTITION("hive.test.fail.load.dynamic.partition", false, "For testing only. Will cause loadDynamicPartition to fail.", false),
HIVETESTMODEFAILHEARTBEATER("hive.test.fail.heartbeater", false, "For testing only. Will cause Heartbeater to fail.", false),
TESTMODE_BUCKET_CODEC_VERSION("hive.test.bucketcodec.version", 1,
"For testing only. Will make ACID subsystem write RecordIdentifier.bucketId in specified\n" +
"format", false),
HIVETESTMODEACIDKEYIDXSKIP("hive.test.acid.key.index.skip", false, "For testing only. OrcRecordUpdater will skip "
+ "generation of the hive.acid.key.index", false),
HIVEMERGEMAPFILES("hive.merge.mapfiles", true,
"Merge small files at the end of a map-only job"),
HIVEMERGEMAPREDFILES("hive.merge.mapredfiles", false,
"Merge small files at the end of a map-reduce job"),
HIVEMERGETEZFILES("hive.merge.tezfiles", false, "Merge small files at the end of a Tez DAG"),
HIVEMERGESPARKFILES("hive.merge.sparkfiles", false, "Merge small files at the end of a Spark DAG Transformation"),
HIVEMERGEMAPFILESSIZE("hive.merge.size.per.task", (long) (256 * 1000 * 1000),
"Size of merged files at the end of the job"),
HIVEMERGEMAPFILESAVGSIZE("hive.merge.smallfiles.avgsize", (long) (16 * 1000 * 1000),
"When the average output file size of a job is less than this number, Hive will start an additional \n" +
"map-reduce job to merge the output files into bigger files. This is only done for map-only jobs \n" +
"if hive.merge.mapfiles is true, and for map-reduce jobs if hive.merge.mapredfiles is true."),
HIVEMERGERCFILEBLOCKLEVEL("hive.merge.rcfile.block.level", true, ""),
HIVEMERGEORCFILESTRIPELEVEL("hive.merge.orcfile.stripe.level", true,
"When hive.merge.mapfiles, hive.merge.mapredfiles or hive.merge.tezfiles is enabled\n" +
"while writing a table with ORC file format, enabling this config will do stripe-level\n" +
"fast merge for small ORC files. Note that enabling this config will not honor the\n" +
"padding tolerance config (hive.exec.orc.block.padding.tolerance)."),
HIVE_ORC_CODEC_POOL("hive.use.orc.codec.pool", false,
"Whether to use codec pool in ORC. Disable if there are bugs with codec reuse."),
HIVEUSEEXPLICITRCFILEHEADER("hive.exec.rcfile.use.explicit.header", true,
"If this is set the header for RCFiles will simply be RCF. If this is not\n" +
"set the header will be that borrowed from sequence files, e.g. SEQ- followed\n" +
"by the input and output RCFile formats."),
HIVEUSERCFILESYNCCACHE("hive.exec.rcfile.use.sync.cache", true, ""),
HIVE_RCFILE_RECORD_INTERVAL("hive.io.rcfile.record.interval", Integer.MAX_VALUE, ""),
HIVE_RCFILE_COLUMN_NUMBER_CONF("hive.io.rcfile.column.number.conf", 0, ""),
HIVE_RCFILE_TOLERATE_CORRUPTIONS("hive.io.rcfile.tolerate.corruptions", false, ""),
HIVE_RCFILE_RECORD_BUFFER_SIZE("hive.io.rcfile.record.buffer.size", 4194304, ""), // 4M
PARQUET_MEMORY_POOL_RATIO("parquet.memory.pool.ratio", 0.5f,
"Maximum fraction of heap that can be used by Parquet file writers in one task.\n" +
"It is for avoiding OutOfMemory error in tasks. Work with Parquet 1.6.0 and above.\n" +
"This config parameter is defined in Parquet, so that it does not start with 'hive.'."),
HIVE_PARQUET_TIMESTAMP_SKIP_CONVERSION("hive.parquet.timestamp.skip.conversion", true,
"Current Hive implementation of parquet stores timestamps to UTC, this flag allows skipping of the conversion" +
"on reading parquet files from other tools"),
HIVE_PARQUET_DATE_PROLEPTIC_GREGORIAN("hive.parquet.date.proleptic.gregorian", false,
"Should we write date using the proleptic Gregorian calendar instead of the hybrid Julian Gregorian?\n" +
"Hybrid is the default."),
HIVE_PARQUET_DATE_PROLEPTIC_GREGORIAN_DEFAULT("hive.parquet.date.proleptic.gregorian.default", false,
"This value controls whether date type in Parquet files was written using the hybrid or proleptic\n" +
"calendar. Hybrid is the default."),
HIVE_PARQUET_TIMESTAMP_LEGACY_CONVERSION_ENABLED("hive.parquet.timestamp.legacy.conversion.enabled", true,
"This value controls whether we use former Java time API to convert between timezones on files where timezone\n" +
"is not encoded in the metadata. This is for debugging."),
HIVE_AVRO_TIMESTAMP_SKIP_CONVERSION("hive.avro.timestamp.skip.conversion", false,
"Some older Hive implementations (pre-3.1) wrote Avro timestamps in a UTC-normalized" +
"manner, while from version 3.1 until now Hive wrote time zone agnostic timestamps. " +
"Setting this flag to true will treat legacy timestamps as time zone agnostic. Setting " +
"it to false will treat legacy timestamps as UTC-normalized. This flag will not affect " +
"timestamps written after this change."),
HIVE_AVRO_PROLEPTIC_GREGORIAN("hive.avro.proleptic.gregorian", false,
"Should we write date and timestamp using the proleptic Gregorian calendar instead of the hybrid Julian Gregorian?\n" +
"Hybrid is the default."),
HIVE_AVRO_PROLEPTIC_GREGORIAN_DEFAULT("hive.avro.proleptic.gregorian.default", false,
"This value controls whether date and timestamp type in Avro files was written using the hybrid or proleptic\n" +
"calendar. Hybrid is the default."),
HIVE_AVRO_TIMESTAMP_LEGACY_CONVERSION_ENABLED("hive.avro.timestamp.legacy.conversion.enabled", true,
"This value controls whether we use former Java time API to convert between timezones on files where timezone\n" +
"is not encoded in the metadata. This is for debugging."),
HIVE_INT_TIMESTAMP_CONVERSION_IN_SECONDS("hive.int.timestamp.conversion.in.seconds", false,
"Boolean/tinyint/smallint/int/bigint value is interpreted as milliseconds during the timestamp conversion.\n" +
"Set this flag to true to interpret the value as seconds to be consistent with float/double." ),
HIVE_PARQUET_WRITE_INT64_TIMESTAMP("hive.parquet.write.int64.timestamp", false,
"Write parquet timestamps as int64/LogicalTypes instead of int96/OriginalTypes. Note:" +
"Timestamps will be time zone agnostic (NEVER converted to a different time zone)."),
HIVE_PARQUET_TIMESTAMP_TIME_UNIT("hive.parquet.timestamp.time.unit", "micros",
new StringSet("nanos", "micros", "millis"),
"Store parquet int64/LogicalTypes timestamps in this time unit."),
HIVE_ORC_BASE_DELTA_RATIO("hive.exec.orc.base.delta.ratio", 8, "The ratio of base writer and\n" +
"delta writer in terms of STRIPE_SIZE and BUFFER_SIZE."),
HIVE_ORC_DELTA_STREAMING_OPTIMIZATIONS_ENABLED("hive.exec.orc.delta.streaming.optimizations.enabled", false,
"Whether to enable streaming optimizations for ORC delta files. This will disable ORC's internal indexes,\n" +
"disable compression, enable fast encoding and disable dictionary encoding."),
HIVE_ORC_SPLIT_STRATEGY("hive.exec.orc.split.strategy", "HYBRID", new StringSet("HYBRID", "BI", "ETL"),
"This is not a user level config. BI strategy is used when the requirement is to spend less time in split generation" +
" as opposed to query execution (split generation does not read or cache file footers)." +
" ETL strategy is used when spending little more time in split generation is acceptable" +
" (split generation reads and caches file footers). HYBRID chooses between the above strategies" +
" based on heuristics."),
HIVE_ORC_BLOB_STORAGE_SPLIT_SIZE("hive.exec.orc.blob.storage.split.size", 128L * 1024 * 1024,
"When blob storage is used, BI split strategy does not have block locations for splitting orc files.\n" +
"In such cases, split generation will use this config to split orc file"),
HIVE_ORC_WRITER_LLAP_MEMORY_MANAGER_ENABLED("hive.exec.orc.writer.llap.memory.manager.enabled", true,
"Whether orc writers should use llap-aware memory manager. LLAP aware memory manager will use memory\n" +
"per executor instead of entire heap memory when concurrent orc writers are involved. This will let\n" +
"task fragments to use memory within its limit (memory per executor) when performing ETL in LLAP."),
// hive streaming ingest settings
HIVE_STREAMING_AUTO_FLUSH_ENABLED("hive.streaming.auto.flush.enabled", true, "Whether to enable memory \n" +
"monitoring and automatic flushing of open record updaters during streaming ingest. This is an expert level \n" +
"setting and disabling this may have severe performance impact under memory pressure."),
HIVE_HEAP_MEMORY_MONITOR_USAGE_THRESHOLD("hive.heap.memory.monitor.usage.threshold", 0.7f,
"Hive streaming does automatic memory management across all open record writers. This threshold will let the \n" +
"memory monitor take an action (flush open files) when heap memory usage exceeded this threshold."),
HIVE_STREAMING_AUTO_FLUSH_CHECK_INTERVAL_SIZE("hive.streaming.auto.flush.check.interval.size", "100Mb",
new SizeValidator(),
"Hive streaming ingest has auto flush mechanism to flush all open record updaters under memory pressure.\n" +
"When memory usage exceed hive.heap.memory.monitor.default.usage.threshold, the auto-flush mechanism will \n" +
"wait until this size (default 100Mb) of records are ingested before triggering flush."),
HIVE_CLASSLOADER_SHADE_PREFIX("hive.classloader.shade.prefix", "", "During reflective instantiation of a class\n" +
"(input, output formats, serde etc.), when classloader throws ClassNotFoundException, as a fallback this\n" +
"shade prefix will be used before class reference and retried."),
HIVE_ORC_MS_FOOTER_CACHE_ENABLED("hive.orc.splits.ms.footer.cache.enabled", false,
"Whether to enable using file metadata cache in metastore for ORC file footers."),
HIVE_ORC_MS_FOOTER_CACHE_PPD("hive.orc.splits.ms.footer.cache.ppd.enabled", true,
"Whether to enable file footer cache PPD (hive.orc.splits.ms.footer.cache.enabled\n" +
"must also be set to true for this to work)."),
HIVE_ORC_INCLUDE_FILE_FOOTER_IN_SPLITS("hive.orc.splits.include.file.footer", false,
"If turned on splits generated by orc will include metadata about the stripes in the file. This\n" +
"data is read remotely (from the client or HS2 machine) and sent to all the tasks."),
HIVE_ORC_SPLIT_DIRECTORY_BATCH_MS("hive.orc.splits.directory.batch.ms", 0,
"How long, in ms, to wait to batch input directories for processing during ORC split\n" +
"generation. 0 means process directories individually. This can increase the number of\n" +
"metastore calls if metastore metadata cache is used."),
HIVE_ORC_INCLUDE_FILE_ID_IN_SPLITS("hive.orc.splits.include.fileid", true,
"Include file ID in splits on file systems that support it."),
HIVE_ORC_ALLOW_SYNTHETIC_FILE_ID_IN_SPLITS("hive.orc.splits.allow.synthetic.fileid", true,
"Allow synthetic file ID in splits on file systems that don't have a native one."),
HIVE_ORC_CACHE_STRIPE_DETAILS_MEMORY_SIZE("hive.orc.cache.stripe.details.mem.size", "256Mb",
new SizeValidator(), "Maximum size of orc splits cached in the client."),
/**
* @deprecated Use HiveConf.HIVE_COMPUTE_SPLITS_NUM_THREADS
*/
@Deprecated
HIVE_ORC_COMPUTE_SPLITS_NUM_THREADS("hive.orc.compute.splits.num.threads", 10,
"How many threads orc should use to create splits in parallel."),
HIVE_ORC_CACHE_USE_SOFT_REFERENCES("hive.orc.cache.use.soft.references", false,
"By default, the cache that ORC input format uses to store orc file footer use hard\n" +
"references for the cached object. Setting this to true can help avoid out of memory\n" +
"issues under memory pressure (in some cases) at the cost of slight unpredictability in\n" +
"overall query performance."),
HIVE_IO_SARG_CACHE_MAX_WEIGHT_MB("hive.io.sarg.cache.max.weight.mb", 10,
"The max weight allowed for the SearchArgument Cache. By default, the cache allows a max-weight of 10MB, " +
"after which entries will be evicted."),
HIVE_LAZYSIMPLE_EXTENDED_BOOLEAN_LITERAL("hive.lazysimple.extended_boolean_literal", false,
"LazySimpleSerde uses this property to determine if it treats 'T', 't', 'F', 'f',\n" +
"'1', and '0' as extended, legal boolean literal, in addition to 'TRUE' and 'FALSE'.\n" +
"The default is false, which means only 'TRUE' and 'FALSE' are treated as legal\n" +
"boolean literal."),
HIVESKEWJOIN("hive.optimize.skewjoin", false,
"Whether to enable skew join optimization. \n" +
"The algorithm is as follows: At runtime, detect the keys with a large skew. Instead of\n" +
"processing those keys, store them temporarily in an HDFS directory. In a follow-up map-reduce\n" +
"job, process those skewed keys. The same key need not be skewed for all the tables, and so,\n" +
"the follow-up map-reduce job (for the skewed keys) would be much faster, since it would be a\n" +
"map-join."),
HIVEDYNAMICPARTITIONHASHJOIN("hive.optimize.dynamic.partition.hashjoin", false,
"Whether to enable dynamically partitioned hash join optimization. \n" +
"This setting is also dependent on enabling hive.auto.convert.join"),
HIVECONVERTJOIN("hive.auto.convert.join", true,
"Whether Hive enables the optimization about converting common join into mapjoin based on the input file size"),
HIVECONVERTJOINNOCONDITIONALTASK("hive.auto.convert.join.noconditionaltask", true,
"Whether Hive enables the optimization about converting common join into mapjoin based on the input file size. \n" +
"If this parameter is on, and the sum of size for n-1 of the tables/partitions for a n-way join is smaller than the\n" +
"specified size, the join is directly converted to a mapjoin (there is no conditional task)."),
HIVE_CONVERT_ANTI_JOIN("hive.auto.convert.anti.join", true,
"Whether Hive enables the optimization about converting join with null filter to anti join"),
HIVECONVERTJOINNOCONDITIONALTASKTHRESHOLD("hive.auto.convert.join.noconditionaltask.size",
10000000L,
"If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" +
"However, if it is on, and the sum of size for n-1 of the tables/partitions for a n-way join is smaller than this size, \n" +
"the join is directly converted to a mapjoin(there is no conditional task). The default is 10MB"),
HIVECONVERTJOINUSENONSTAGED("hive.auto.convert.join.use.nonstaged", false,
"For conditional joins, if input stream from a small alias can be directly applied to join operator without \n" +
"filtering or projection, the alias need not to be pre-staged in distributed cache via mapred local task.\n" +
"Currently, this is not working with vectorization or tez execution engine."),
HIVESKEWJOINKEY("hive.skewjoin.key", 100000,
"Determine if we get a skew key in join. If we see more than the specified number of rows with the same key in join operator,\n" +
"we think the key as a skew join key. "),
HIVESKEWJOINMAPJOINNUMMAPTASK("hive.skewjoin.mapjoin.map.tasks", 10000,
"Determine the number of map task used in the follow up map join job for a skew join.\n" +
"It should be used together with hive.skewjoin.mapjoin.min.split to perform a fine grained control."),
HIVESKEWJOINMAPJOINMINSPLIT("hive.skewjoin.mapjoin.min.split", 33554432L,
"Determine the number of map task at most used in the follow up map join job for a skew join by specifying \n" +
"the minimum split size. It should be used together with hive.skewjoin.mapjoin.map.tasks to perform a fine grained control."),
HIVESENDHEARTBEAT("hive.heartbeat.interval", 1000,
"Send a heartbeat after this interval - used by mapjoin and filter operators"),
HIVELIMITMAXROWSIZE("hive.limit.row.max.size", 100000L,
"When trying a smaller subset of data for simple LIMIT, how much size we need to guarantee each row to have at least."),
HIVELIMITOPTLIMITFILE("hive.limit.optimize.limit.file", 10,
"When trying a smaller subset of data for simple LIMIT, maximum number of files we can sample."),
HIVELIMITOPTENABLE("hive.limit.optimize.enable", false,
"Whether to enable to optimization to trying a smaller subset of data for simple LIMIT first."),
HIVELIMITOPTMAXFETCH("hive.limit.optimize.fetch.max", 50000,
"Maximum number of rows allowed for a smaller subset of data for simple LIMIT, if it is a fetch query. \n" +
"Insert queries are not restricted by this limit."),
HIVELIMITPUSHDOWNMEMORYUSAGE("hive.limit.pushdown.memory.usage", 0.1f, new RatioValidator(),
"The fraction of available memory to be used for buffering rows in Reducesink operator for limit pushdown optimization."),
HIVECONVERTJOINMAXENTRIESHASHTABLE("hive.auto.convert.join.hashtable.max.entries", 21000000L,
"If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" +
"However, if it is on, and the predicted number of entries in hashtable for a given join \n" +
"input is larger than this number, the join will not be converted to a mapjoin. \n" +
"The value \"-1\" means no limit."),
XPRODSMALLTABLEROWSTHRESHOLD("hive.xprod.mapjoin.small.table.rows", 1,"Maximum number of rows on build side"
+ " of map join before it switches over to cross product edge"),
HIVECONVERTJOINMAXSHUFFLESIZE("hive.auto.convert.join.shuffle.max.size", 10000000000L,
"If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" +
"However, if it is on, and the predicted size of the larger input for a given join is greater \n" +
"than this number, the join will not be converted to a dynamically partitioned hash join. \n" +
"The value \"-1\" means no limit."),
HIVEHASHTABLEKEYCOUNTADJUSTMENT("hive.hashtable.key.count.adjustment", 0.99f,
"Adjustment to mapjoin hashtable size derived from table and column statistics; the estimate" +
" of the number of keys is divided by this value. If the value is 0, statistics are not used" +
"and hive.hashtable.initialCapacity is used instead."),
HIVEHASHTABLETHRESHOLD("hive.hashtable.initialCapacity", 100000, "Initial capacity of " +
"mapjoin hashtable if statistics are absent, or if hive.hashtable.key.count.adjustment is set to 0"),
HIVEHASHTABLELOADFACTOR("hive.hashtable.loadfactor", (float) 0.75, ""),
HIVEHASHTABLEFOLLOWBYGBYMAXMEMORYUSAGE("hive.mapjoin.followby.gby.localtask.max.memory.usage", (float) 0.55,
"This number means how much memory the local task can take to hold the key/value into an in-memory hash table \n" +
"when this map join is followed by a group by. If the local task's memory usage is more than this number, \n" +
"the local task will abort by itself. It means the data of the small table is too large " +
"to be held in memory. Does not apply to Hive-on-Spark (replaced by " +
"hive.mapjoin.max.gc.time.percentage)"),
HIVEHASHTABLEMAXMEMORYUSAGE("hive.mapjoin.localtask.max.memory.usage", (float) 0.90,
"This number means how much memory the local task can take to hold the key/value into an in-memory hash table. \n" +
"If the local task's memory usage is more than this number, the local task will abort by itself. \n" +
"It means the data of the small table is too large to be held in memory. Does not apply to " +
"Hive-on-Spark (replaced by hive.mapjoin.max.gc.time.percentage)"),
HIVEHASHTABLESCALE("hive.mapjoin.check.memory.rows", (long)100000,
"The number means after how many rows processed it needs to check the memory usage"),
HIVEHASHTABLEMAXGCTIMEPERCENTAGE("hive.mapjoin.max.gc.time.percentage", (float) 0.60,
new RangeValidator(0.0f, 1.0f), "This number means how much time (what percentage, " +
"0..1, of wallclock time) the JVM is allowed to spend in garbage collection when running " +
"the local task. If GC time percentage exceeds this number, the local task will abort by " +
"itself. Applies to Hive-on-Spark only"),
HIVEINPUTFORMAT("hive.input.format", "org.apache.hadoop.hive.ql.io.CombineHiveInputFormat",
"The default input format. Set this to HiveInputFormat if you encounter problems with CombineHiveInputFormat."),
HIVETEZINPUTFORMAT("hive.tez.input.format", "org.apache.hadoop.hive.ql.io.HiveInputFormat",
"The default input format for tez. Tez groups splits in the AM."),
HIVETEZCONTAINERSIZE("hive.tez.container.size", -1,
"By default Tez will spawn containers of the size of a mapper. This can be used to overwrite."),
HIVETEZCPUVCORES("hive.tez.cpu.vcores", -1,
"By default Tez will ask for however many cpus map-reduce is configured to use per container.\n" +
"This can be used to overwrite."),
HIVETEZJAVAOPTS("hive.tez.java.opts", null,
"By default Tez will use the Java options from map tasks. This can be used to overwrite."),
HIVETEZLOGLEVEL("hive.tez.log.level", "INFO",
"The log level to use for tasks executing as part of the DAG.\n" +
"Used only if hive.tez.java.opts is used to configure Java options."),
HIVETEZHS2USERACCESS("hive.tez.hs2.user.access", true,
"Whether to grant access to the hs2/hive user for queries"),
HIVEQUERYNAME ("hive.query.name", null,
"This named is used by Tez to set the dag name. This name in turn will appear on \n" +
"the Tez UI representing the work that was done. Used by Spark to set the query name, will show up in the\n" +
"Spark UI."),
HIVETEZJOBNAME("tez.job.name", "HIVE-%s",
"This named is used by Tez to set the job name. This name in turn will appear on \n" +
"the Yarn UI representing the Yarn Application Name. And The job name may be a \n" +
"Java String.format() string, to which the session ID will be supplied as the single parameter."),
SYSLOG_INPUT_FORMAT_FILE_PRUNING("hive.syslog.input.format.file.pruning", true,
"Whether syslog input format should prune files based on timestamp (ts) column in sys.logs table."),
SYSLOG_INPUT_FORMAT_FILE_TIME_SLICE("hive.syslog.input.format.file.time.slice", "300s",
new TimeValidator(TimeUnit.SECONDS, 0L, false, Long.MAX_VALUE, false),
"Files stored in sys.logs typically are chunked with time interval. For example: depending on the\n" +
"logging library used this represents the flush interval/time slice. \n" +
"If time slice/flust interval is set to 5 minutes, then the expectation is that the filename \n" +
"2019-01-02-10-00_0.log represent time range from 10:00 to 10:05.\n" +
"This time slice should align with the flush interval of the logging library else file pruning may\n" +
"incorrectly prune files leading to incorrect results from sys.logs table."),
HIVEOPTIMIZEBUCKETINGSORTING("hive.optimize.bucketingsorting", true,
"Don't create a reducer for enforcing \n" +
"bucketing/sorting for queries of the form: \n" +
"insert overwrite table T2 select * from T1;\n" +
"where T1 and T2 are bucketed/sorted by the same keys into the same number of buckets."),
HIVEPARTITIONER("hive.mapred.partitioner", "org.apache.hadoop.hive.ql.io.DefaultHivePartitioner", ""),
HIVEENFORCESORTMERGEBUCKETMAPJOIN("hive.enforce.sortmergebucketmapjoin", false,
"If the user asked for sort-merge bucketed map-side join, and it cannot be performed, should the query fail or not ?"),
HIVEENFORCEBUCKETMAPJOIN("hive.enforce.bucketmapjoin", false,
"If the user asked for bucketed map-side join, and it cannot be performed, \n" +
"should the query fail or not ? For example, if the buckets in the tables being joined are\n" +
"not a multiple of each other, bucketed map-side join cannot be performed, and the\n" +
"query will fail if hive.enforce.bucketmapjoin is set to true."),
HIVE_SORT_WHEN_BUCKETING("hive.optimize.clustered.sort", true,
"When this option is true, when a Hive table was created with a clustered by clause, we will also\n" +
"sort by same value (if sort columns were not specified)"),
HIVE_ENFORCE_NOT_NULL_CONSTRAINT("hive.constraint.notnull.enforce", true,
"Should \"IS NOT NULL \" constraint be enforced?"),
HIVE_AUTO_SORTMERGE_JOIN("hive.auto.convert.sortmerge.join", true,
"Will the join be automatically converted to a sort-merge join, if the joined tables pass the criteria for sort-merge join."),
HIVE_AUTO_SORTMERGE_JOIN_REDUCE("hive.auto.convert.sortmerge.join.reduce.side", true,
"Whether hive.auto.convert.sortmerge.join (if enabled) should be applied to reduce side."),
HIVE_AUTO_SORTMERGE_JOIN_BIGTABLE_SELECTOR(
"hive.auto.convert.sortmerge.join.bigtable.selection.policy",
"org.apache.hadoop.hive.ql.optimizer.AvgPartitionSizeBasedBigTableSelectorForAutoSMJ",
"The policy to choose the big table for automatic conversion to sort-merge join. \n" +
"By default, the table with the largest partitions is assigned the big table. All policies are:\n" +
". based on position of the table - the leftmost table is selected\n" +
"org.apache.hadoop.hive.ql.optimizer.LeftmostBigTableSMJ.\n" +
". based on total size (all the partitions selected in the query) of the table \n" +
"org.apache.hadoop.hive.ql.optimizer.TableSizeBasedBigTableSelectorForAutoSMJ.\n" +
". based on average size (all the partitions selected in the query) of the table \n" +
"org.apache.hadoop.hive.ql.optimizer.AvgPartitionSizeBasedBigTableSelectorForAutoSMJ.\n" +
"New policies can be added in future."),
HIVE_AUTO_SORTMERGE_JOIN_TOMAPJOIN(
"hive.auto.convert.sortmerge.join.to.mapjoin", false,
"If hive.auto.convert.sortmerge.join is set to true, and a join was converted to a sort-merge join, \n" +
"this parameter decides whether each table should be tried as a big table, and effectively a map-join should be\n" +
"tried. That would create a conditional task with n+1 children for a n-way join (1 child for each table as the\n" +
"big table), and the backup task will be the sort-merge join. In some cases, a map-join would be faster than a\n" +
"sort-merge join, if there is no advantage of having the output bucketed and sorted. For example, if a very big sorted\n" +
"and bucketed table with few files (say 10 files) are being joined with a very small sorter and bucketed table\n" +
"with few files (10 files), the sort-merge join will only use 10 mappers, and a simple map-only join might be faster\n" +
"if the complete small table can fit in memory, and a map-join can be performed."),
HIVESCRIPTOPERATORTRUST("hive.exec.script.trust", false, ""),
HIVEROWOFFSET("hive.exec.rowoffset", false,
"Whether to provide the row offset virtual column"),
// Optimizer
HIVEOPTINDEXFILTER("hive.optimize.index.filter", true, "Whether to enable automatic use of indexes"),
HIVEOPTPPD("hive.optimize.ppd", true,
"Whether to enable predicate pushdown"),
HIVEOPTPPD_WINDOWING("hive.optimize.ppd.windowing", true,
"Whether to enable predicate pushdown through windowing"),
HIVEPPDRECOGNIZETRANSITIVITY("hive.ppd.recognizetransivity", true,
"Whether to transitively replicate predicate filters over equijoin conditions."),
HIVEPPDREMOVEDUPLICATEFILTERS("hive.ppd.remove.duplicatefilters", true,
"During query optimization, filters may be pushed down in the operator tree. \n" +
"If this config is true only pushed down filters remain in the operator tree, \n" +
"and the original filter is removed. If this config is false, the original filter \n" +
"is also left in the operator tree at the original place."),
HIVEPOINTLOOKUPOPTIMIZER("hive.optimize.point.lookup", true,
"Whether to transform OR clauses in Filter operators into IN clauses"),
HIVEPOINTLOOKUPOPTIMIZERMIN("hive.optimize.point.lookup.min", 2,
"Minimum number of OR clauses needed to transform into IN clauses"),
HIVEOPT_TRANSFORM_IN_MAXNODES("hive.optimize.transform.in.maxnodes", 16,
"Maximum number of IN expressions beyond which IN will not be transformed into OR clause"),
HIVECOUNTDISTINCTOPTIMIZER("hive.optimize.countdistinct", true,
"Whether to transform count distinct into two stages"),
HIVEPARTITIONCOLUMNSEPARATOR("hive.optimize.partition.columns.separate", true,
"Extract partition columns from IN clauses"),
// Constant propagation optimizer
HIVEOPTCONSTANTPROPAGATION("hive.optimize.constant.propagation", true, "Whether to enable constant propagation optimizer"),
HIVEIDENTITYPROJECTREMOVER("hive.optimize.remove.identity.project", true, "Removes identity project from operator tree"),
HIVEMETADATAONLYQUERIES("hive.optimize.metadataonly", false,
"Whether to eliminate scans of the tables from which no columns are selected. Note\n" +
"that, when selecting from empty tables with data files, this can produce incorrect\n" +
"results, so it's disabled by default. It works correctly for normal tables."),
HIVENULLSCANOPTIMIZE("hive.optimize.null.scan", true, "Dont scan relations which are guaranteed to not generate any rows"),
HIVEOPTPPD_STORAGE("hive.optimize.ppd.storage", true,
"Whether to push predicates down to storage handlers"),
HIVEOPTGROUPBY("hive.optimize.groupby", true,
"Whether to enable the bucketed group by from bucketed partitions/tables."),
HIVEOPTBUCKETMAPJOIN("hive.optimize.bucketmapjoin", false,
"Whether to try bucket mapjoin"),
HIVEOPTSORTMERGEBUCKETMAPJOIN("hive.optimize.bucketmapjoin.sortedmerge", false,
"Whether to try sorted bucket merge map join"),
HIVEOPTREDUCEDEDUPLICATION("hive.optimize.reducededuplication", true,
"Remove extra map-reduce jobs if the data is already clustered by the same key which needs to be used again. \n" +
"This should always be set to true. Since it is a new feature, it has been made configurable."),
HIVEOPTREDUCEDEDUPLICATIONMINREDUCER("hive.optimize.reducededuplication.min.reducer", 4,
"Reduce deduplication merges two RSs by moving key/parts/reducer-num of the child RS to parent RS. \n" +
"That means if reducer-num of the child RS is fixed (order by or forced bucketing) and small, it can make very slow, single MR.\n" +
"The optimization will be automatically disabled if number of reducers would be less than specified value."),
HIVEOPTJOINREDUCEDEDUPLICATION("hive.optimize.joinreducededuplication", true,
"Remove extra shuffle/sorting operations after join algorithm selection has been executed. \n" +
"Currently it only works with Apache Tez. This should always be set to true. \n" +
"Since it is a new feature, it has been made configurable."),
@Deprecated
HIVEOPTSORTDYNAMICPARTITION("hive.optimize.sort.dynamic.partition", false,
"Deprecated. Use hive.optimize.sort.dynamic.partition.threshold instead."),
HIVEOPTSORTDYNAMICPARTITIONTHRESHOLD("hive.optimize.sort.dynamic.partition.threshold", 0,
"When enabled dynamic partitioning column will be globally sorted.\n" +
"This way we can keep only one record writer open for each partition value\n" +
"in the reducer thereby reducing the memory pressure on reducers.\n" +
"This config has following possible values: \n" +
"\t-1 - This completely disables the optimization. \n" +
"\t1 - This always enable the optimization. \n" +
"\t0 - This makes the optimization a cost based decision. \n" +
"Setting it to any other positive integer will make Hive use this as threshold for number of writers."),
HIVESAMPLINGFORORDERBY("hive.optimize.sampling.orderby", false, "Uses sampling on order-by clause for parallel execution."),
HIVESAMPLINGNUMBERFORORDERBY("hive.optimize.sampling.orderby.number", 1000, "Total number of samples to be obtained."),
HIVESAMPLINGPERCENTFORORDERBY("hive.optimize.sampling.orderby.percent", 0.1f, new RatioValidator(),
"Probability with which a row will be chosen."),
HIVE_REMOVE_ORDERBY_IN_SUBQUERY("hive.remove.orderby.in.subquery", true,
"If set to true, order/sort by without limit in sub queries will be removed."),
HIVEOPTIMIZEDISTINCTREWRITE("hive.optimize.distinct.rewrite", true, "When applicable this "
+ "optimization rewrites distinct aggregates from a single stage to multi-stage "
+ "aggregation. This may not be optimal in all cases. Ideally, whether to trigger it or "
+ "not should be cost based decision. Until Hive formalizes cost model for this, this is config driven."),
// whether to optimize union followed by select followed by filesink
// It creates sub-directories in the final output, so should not be turned on in systems
// where MAPREDUCE-1501 is not present
HIVE_OPTIMIZE_UNION_REMOVE("hive.optimize.union.remove", false,
"Whether to remove the union and push the operators between union and the filesink above union. \n" +
"This avoids an extra scan of the output by union. This is independently useful for union\n" +
"queries, and specially useful when hive.optimize.skewjoin.compiletime is set to true, since an\n" +
"extra union is inserted.\n" +
"\n" +
"The merge is triggered if either of hive.merge.mapfiles or hive.merge.mapredfiles is set to true.\n" +
"If the user has set hive.merge.mapfiles to true and hive.merge.mapredfiles to false, the idea was the\n" +
"number of reducers are few, so the number of files anyway are small. However, with this optimization,\n" +
"we are increasing the number of files possibly by a big margin. So, we merge aggressively."),
HIVEOPTCORRELATION("hive.optimize.correlation", false, "exploit intra-query correlations."),
HIVE_OPTIMIZE_LIMIT_TRANSPOSE("hive.optimize.limittranspose", false,
"Whether to push a limit through left/right outer join or union. If the value is true and the size of the outer\n" +
"input is reduced enough (as specified in hive.optimize.limittranspose.reduction), the limit is pushed\n" +
"to the outer input or union; to remain semantically correct, the limit is kept on top of the join or the union too."),
HIVE_OPTIMIZE_LIMIT_TRANSPOSE_REDUCTION_PERCENTAGE("hive.optimize.limittranspose.reductionpercentage", 1.0f,
"When hive.optimize.limittranspose is true, this variable specifies the minimal reduction of the\n" +
"size of the outer input of the join or input of the union that we should get in order to apply the rule."),
HIVE_OPTIMIZE_LIMIT_TRANSPOSE_REDUCTION_TUPLES("hive.optimize.limittranspose.reductiontuples", (long) 0,
"When hive.optimize.limittranspose is true, this variable specifies the minimal reduction in the\n" +
"number of tuples of the outer input of the join or the input of the union that you should get in order to apply the rule."),
HIVE_OPTIMIZE_CONSTRAINTS_JOIN("hive.optimize.constraints.join", true, "Whether to use referential constraints\n" +
"to optimize (remove or transform) join operators"),
HIVE_OPTIMIZE_SORT_PREDS_WITH_STATS("hive.optimize.filter.preds.sort", true, "Whether to sort conditions in filters\n" +
"based on estimated selectivity and compute cost"),
HIVE_OPTIMIZE_REDUCE_WITH_STATS("hive.optimize.filter.stats.reduction", false, "Whether to simplify comparison\n" +
"expressions in filter operators using column stats"),
HIVE_OPTIMIZE_SKEWJOIN_COMPILETIME("hive.optimize.skewjoin.compiletime", false,
"Whether to create a separate plan for skewed keys for the tables in the join.\n" +
"This is based on the skewed keys stored in the metadata. At compile time, the plan is broken\n" +
"into different joins: one for the skewed keys, and the other for the remaining keys. And then,\n" +
"a union is performed for the 2 joins generated above. So unless the same skewed key is present\n" +
"in both the joined tables, the join for the skewed key will be performed as a map-side join.\n" +
"\n" +
"The main difference between this parameter and hive.optimize.skewjoin is that this parameter\n" +
"uses the skew information stored in the metastore to optimize the plan at compile time itself.\n" +
"If there is no skew information in the metadata, this parameter will not have any affect.\n" +
"Both hive.optimize.skewjoin.compiletime and hive.optimize.skewjoin should be set to true.\n" +
"Ideally, hive.optimize.skewjoin should be renamed as hive.optimize.skewjoin.runtime, but not doing\n" +
"so for backward compatibility.\n" +
"\n" +
"If the skew information is correctly stored in the metadata, hive.optimize.skewjoin.compiletime\n" +
"would change the query plan to take care of it, and hive.optimize.skewjoin will be a no-op."),
HIVE_OPTIMIZE_LIMIT("hive.optimize.limit", true,
"Optimize limit by pushing through Left Outer Joins and Selects"),
HIVE_OPTIMIZE_TOPNKEY("hive.optimize.topnkey", true, "Whether to enable top n key optimizer."),
HIVE_MAX_TOPN_ALLOWED("hive.optimize.topnkey.max", 128, "Maximum topN value allowed by top n key optimizer.\n" +
"If the LIMIT is greater than this value then top n key optimization won't be used."),
HIVE_TOPN_EFFICIENCY_THRESHOLD("hive.optimize.topnkey.efficiency.threshold", 0.8f, "Disable topN key filter if the ratio between forwarded and total rows reaches this limit."),
HIVE_TOPN_EFFICIENCY_CHECK_BATCHES("hive.optimize.topnkey.efficiency.check.nbatches", 10000, "Check topN key filter efficiency after a specific number of batches."),
HIVE_TOPN_MAX_NUMBER_OF_PARTITIONS("hive.optimize.topnkey.partitions.max", 64, "Limit the maximum number of partitions used by the top N key operator."),
HIVE_SHARED_WORK_OPTIMIZATION("hive.optimize.shared.work", true,
"Whether to enable shared work optimizer. The optimizer finds scan operator over the same table\n" +
"and follow-up operators in the query plan and merges them if they meet some preconditions. Tez only."),
HIVE_SHARED_WORK_EXTENDED_OPTIMIZATION("hive.optimize.shared.work.extended", true,
"Whether to enable shared work extended optimizer. The optimizer tries to merge equal operators\n" +
"after a work boundary after shared work optimizer has been executed. Requires hive.optimize.shared.work\n" +
"to be set to true. Tez only."),
HIVE_SHARED_WORK_SEMIJOIN_OPTIMIZATION("hive.optimize.shared.work.semijoin", true,
"Whether to enable shared work extended optimizer for semijoins. The optimizer tries to merge\n" +
"scan operators if one of them reads the full table, even if the other one is the target for\n" +
"one or more semijoin edges. Tez only."),
HIVE_SHARED_WORK_MERGE_TS_SCHEMA("hive.optimize.shared.work.merge.ts.schema", true,
"Whether to enable merging scan operators over the same table but with different schema." +
"The optimizer tries to merge the scan operators by taking the union of needed columns from " +
"all scan operators. Requires hive.optimize.shared.work to be set to true. Tez only."),
HIVE_SHARED_WORK_REUSE_MAPJOIN_CACHE("hive.optimize.shared.work.mapjoin.cache.reuse", true,
"When shared work optimizer is enabled, whether we should reuse the cache for the broadcast side\n" +
"of mapjoin operators that share same broadcast input. Requires hive.optimize.shared.work\n" +
"to be set to true. Tez only."),
HIVE_SHARED_WORK_DPPUNION_OPTIMIZATION("hive.optimize.shared.work.dppunion", true,
"Enables dppops unioning. This optimization will enable to merge multiple tablescans with different "
+ "dynamic filters into a single one (with a more complex filter)"),
HIVE_SHARED_WORK_DPPUNION_MERGE_EVENTOPS("hive.optimize.shared.work.dppunion.merge.eventops", true,
"Enables DPPUnion to merge EventOperators (right now this is used during DynamicPartitionPruning)"),
HIVE_SHARED_WORK_DOWNSTREAM_MERGE("hive.optimize.shared.work.downstream.merge", true,
"Analyzes and merges equiv downstream operators after a successful shared work optimization step."),
HIVE_COMBINE_EQUIVALENT_WORK_OPTIMIZATION("hive.combine.equivalent.work.optimization", true, "Whether to " +
"combine equivalent work objects during physical optimization.\n This optimization looks for equivalent " +
"work objects and combines them if they meet certain preconditions. Spark only."),
HIVE_REMOVE_SQ_COUNT_CHECK("hive.optimize.remove.sq_count_check", true,
"Whether to remove an extra join with sq_count_check for scalar subqueries "
+ "with constant group by keys."),
HIVE_OPTIMIZE_TABLE_PROPERTIES_FROM_SERDE("hive.optimize.update.table.properties.from.serde", false,
"Whether to update table-properties by initializing tables' SerDe instances during logical-optimization. \n" +
"By doing so, certain SerDe classes (like AvroSerDe) can pre-calculate table-specific information, and \n" +
"store it in table-properties, to be used later in the SerDe, while running the job."),
HIVE_OPTIMIZE_TABLE_PROPERTIES_FROM_SERDE_LIST("hive.optimize.update.table.properties.from.serde.list",
"org.apache.hadoop.hive.serde2.avro.AvroSerDe",
"The comma-separated list of SerDe classes that are considered when enhancing table-properties \n" +
"during logical optimization."),
HIVE_OPTIMIZE_SCAN_PROBEDECODE("hive.optimize.scan.probedecode", true,
"Whether to find suitable table scan operators that could reduce the number of decoded rows at runtime by probing extra available information. \n"
+ "The probe side for the row-level filtering is generated either statically in the case of expressions or dynamically for joins"
+ "e.g., use the cached MapJoin hashtable created on the small table side to filter out row columns that are not going "
+ "to be used when reading the large table data. This will result less CPU cycles spent for decoding unused data."),
HIVE_OPTIMIZE_HMS_QUERY_CACHE_ENABLED("hive.optimize.metadata.query.cache.enabled", true,
"This property enables caching metadata for repetitive requests on a per-query basis"),
// CTE
HIVE_CTE_MATERIALIZE_THRESHOLD("hive.optimize.cte.materialize.threshold", 3,
"If the number of references to a CTE clause exceeds this threshold, Hive will materialize it\n" +
"before executing the main query block. -1 will disable this feature."),
HIVE_CTE_MATERIALIZE_FULL_AGGREGATE_ONLY("hive.optimize.cte.materialize.full.aggregate.only", true,
"If enabled only CTEs with aggregate output will be pre-materialized. All CTEs otherwise." +
"Also the number of references to a CTE clause must exceeds the value of " +
"hive.optimize.cte.materialize.threshold"),
HIVE_OPTIMIZE_BI_ENABLED("hive.optimize.bi.enabled", false,
"Enables query rewrites based on approximate functions(sketches)."),
HIVE_OPTIMIZE_BI_REWRITE_COUNTDISTINCT_ENABLED("hive.optimize.bi.rewrite.countdistinct.enabled",
true,
"Enables to rewrite COUNT(DISTINCT(X)) queries to be rewritten to use sketch functions."),
HIVE_OPTIMIZE_BI_REWRITE_COUNT_DISTINCT_SKETCH("hive.optimize.bi.rewrite.countdistinct.sketch", "hll",
new StringSet("hll"),
"Defines which sketch type to use when rewriting COUNT(DISTINCT(X)) expressions. "
+ "Distinct counting can be done with: hll"),
HIVE_OPTIMIZE_BI_REWRITE_PERCENTILE_DISC_ENABLED("hive.optimize.bi.rewrite.percentile_disc.enabled",
true,
"Enables to rewrite PERCENTILE_DISC(X) queries to be rewritten to use sketch functions."),
HIVE_OPTIMIZE_BI_REWRITE_PERCENTILE_DISC_SKETCH("hive.optimize.bi.rewrite.percentile_disc.sketch", "kll",
new StringSet("kll"),
"Defines which sketch type to use when rewriting PERCENTILE_DISC expressions. Options: kll"),
HIVE_OPTIMIZE_BI_REWRITE_CUME_DIST_ENABLED("hive.optimize.bi.rewrite.cume_dist.enabled",
true,
"Enables to rewrite CUME_DIST(X) queries to be rewritten to use sketch functions."),
HIVE_OPTIMIZE_BI_REWRITE_CUME_DIST_SKETCH("hive.optimize.bi.rewrite.cume_dist.sketch", "kll",
new StringSet("kll"),
"Defines which sketch type to use when rewriting CUME_DIST expressions. Options: kll"),
HIVE_OPTIMIZE_BI_REWRITE_NTILE_ENABLED("hive.optimize.bi.rewrite.ntile.enabled",
true,
"Enables to rewrite NTILE(X) queries to be rewritten as sketch functions."),
HIVE_OPTIMIZE_BI_REWRITE_NTILE_SKETCH("hive.optimize.bi.rewrite.ntile.sketch", "kll",
new StringSet("kll"),
"Defines which sketch type to use when rewriting NTILE expressions. Options: kll"),
HIVE_OPTIMIZE_BI_REWRITE_RANK_ENABLED("hive.optimize.bi.rewrite.rank.enabled",
true,
"Enables to rewrite RANK() queries to be rewritten to use sketch functions."),
HIVE_OPTIMIZE_BI_REWRITE_RANK_SKETCH("hive.optimize.bi.rewrite.rank.sketch", "kll",
new StringSet("kll"),
"Defines which sketch type to use when rewriting RANK expressions. Options: kll"),
// Statistics
HIVE_STATS_ESTIMATE_STATS("hive.stats.estimate", true,
"Estimate statistics in absence of statistics."),
HIVE_STATS_NDV_ESTIMATE_PERC("hive.stats.ndv.estimate.percent", (float)20,
"This many percentage of rows will be estimated as count distinct in absence of statistics."),
HIVE_STATS_NUM_NULLS_ESTIMATE_PERC("hive.stats.num.nulls.estimate.percent", (float)5,
"This many percentage of rows will be estimated as number of nulls in absence of statistics."),
HIVESTATSAUTOGATHER("hive.stats.autogather", true,
"A flag to gather statistics (only basic) automatically during the INSERT OVERWRITE command."),
HIVESTATSCOLAUTOGATHER("hive.stats.column.autogather", true,
"A flag to gather column statistics automatically."),
HIVESTATSDBCLASS("hive.stats.dbclass", "fs", new PatternSet("custom", "fs"),
"The storage that stores temporary Hive statistics. In filesystem based statistics collection ('fs'), \n" +
"each task writes statistics it has collected in a file on the filesystem, which will be aggregated \n" +
"after the job has finished. Supported values are fs (filesystem) and custom as defined in StatsSetupConst.java."), // StatsSetupConst.StatDB
/**
* @deprecated Use MetastoreConf.STATS_DEFAULT_PUBLISHER
*/
@Deprecated
HIVE_STATS_DEFAULT_PUBLISHER("hive.stats.default.publisher", "",
"The Java class (implementing the StatsPublisher interface) that is used by default if hive.stats.dbclass is custom type."),
/**
* @deprecated Use MetastoreConf.STATS_DEFAULT_AGGRETATOR
*/
@Deprecated
HIVE_STATS_DEFAULT_AGGREGATOR("hive.stats.default.aggregator", "",
"The Java class (implementing the StatsAggregator interface) that is used by default if hive.stats.dbclass is custom type."),
CLIENT_STATS_COUNTERS("hive.client.stats.counters", "",
"Subset of counters that should be of interest for hive.client.stats.publishers (when one wants to limit their publishing). \n" +
"Non-display names should be used"),
//Subset of counters that should be of interest for hive.client.stats.publishers (when one wants to limit their publishing). Non-display names should be used".
HIVE_STATS_RELIABLE("hive.stats.reliable", false,
"Whether queries will fail because stats cannot be collected completely accurately. \n" +
"If this is set to true, reading/writing from/into a partition may fail because the stats\n" +
"could not be computed accurately."),
HIVE_STATS_COLLECT_PART_LEVEL_STATS("hive.analyze.stmt.collect.partlevel.stats", true,
"analyze table T compute statistics for columns. Queries like these should compute partition"
+ "level stats for partitioned table even when no part spec is specified."),
HIVE_STATS_GATHER_NUM_THREADS("hive.stats.gather.num.threads", 10,
"Number of threads used by noscan analyze command for partitioned tables.\n" +
"This is applicable only for file formats that implement StatsProvidingRecordReader (like ORC)."),
// Collect table access keys information for operators that can benefit from bucketing
HIVE_STATS_COLLECT_TABLEKEYS("hive.stats.collect.tablekeys", false,
"Whether join and group by keys on tables are derived and maintained in the QueryPlan.\n" +
"This is useful to identify how tables are accessed and to determine if they should be bucketed."),
// Collect column access information
HIVE_STATS_COLLECT_SCANCOLS("hive.stats.collect.scancols", false,
"Whether column accesses are tracked in the QueryPlan.\n" +
"This is useful to identify how tables are accessed and to determine if there are wasted columns that can be trimmed."),
HIVE_STATS_NDV_ALGO("hive.stats.ndv.algo", "hll", new PatternSet("hll", "fm"),
"hll and fm stand for HyperLogLog and FM-sketch, respectively for computing ndv."),
/**
* @deprecated Use MetastoreConf.STATS_FETCH_BITVECTOR
*/
@Deprecated
HIVE_STATS_FETCH_BITVECTOR("hive.stats.fetch.bitvector", false,
"Whether we fetch bitvector when we compute ndv. Users can turn it off if they want to use old schema"),
// standard error allowed for ndv estimates for FM-sketch. A lower value indicates higher accuracy and a
// higher compute cost.
HIVE_STATS_NDV_ERROR("hive.stats.ndv.error", (float)20.0,
"The standard error allowed for NDV estimates, expressed in percentage. This provides a tradeoff \n" +
"between accuracy and compute cost. A lower value for the error indicates higher accuracy and a \n" +
"higher compute cost. (NDV means the number of distinct values.). It only affects the FM-Sketch \n" +
"(not the HLL algorithm which is the default), where it computes the number of necessary\n" +
" bitvectors to achieve the accuracy."),
HIVE_STATS_ESTIMATORS_ENABLE("hive.stats.estimators.enable", true,
"Estimators are able to provide more accurate column statistic infos for UDF results."),
/**
* @deprecated Use MetastoreConf.STATS_NDV_TUNER
*/
@Deprecated
HIVE_METASTORE_STATS_NDV_TUNER("hive.metastore.stats.ndv.tuner", (float)0.0,
"Provides a tunable parameter between the lower bound and the higher bound of ndv for aggregate ndv across all the partitions. \n" +
"The lower bound is equal to the maximum of ndv of all the partitions. The higher bound is equal to the sum of ndv of all the partitions.\n" +
"Its value should be between 0.0 (i.e., choose lower bound) and 1.0 (i.e., choose higher bound)"),
/**
* @deprecated Use MetastoreConf.STATS_NDV_DENSITY_FUNCTION
*/
@Deprecated
HIVE_METASTORE_STATS_NDV_DENSITY_FUNCTION("hive.metastore.stats.ndv.densityfunction", false,
"Whether to use density function to estimate the NDV for the whole table based on the NDV of partitions"),
HIVE_STATS_KEY_PREFIX("hive.stats.key.prefix", "", "", true), // internal usage only
// if length of variable length data type cannot be determined this length will be used.
HIVE_STATS_MAX_VARIABLE_LENGTH("hive.stats.max.variable.length", 100,
"To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" +
"average row size is multiplied with the total number of rows coming out of each operator.\n" +
"Average row size is computed from average column size of all columns in the row. In the absence\n" +
"of column statistics, for variable length columns (like string, bytes etc.), this value will be\n" +
"used. For fixed length columns their corresponding Java equivalent sizes are used\n" +
"(float - 4 bytes, double - 8 bytes etc.)."),
// if number of elements in list cannot be determined, this value will be used
HIVE_STATS_LIST_NUM_ENTRIES("hive.stats.list.num.entries", 10,
"To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" +
"average row size is multiplied with the total number of rows coming out of each operator.\n" +
"Average row size is computed from average column size of all columns in the row. In the absence\n" +
"of column statistics and for variable length complex columns like list, the average number of\n" +
"entries/values can be specified using this config."),
// if number of elements in map cannot be determined, this value will be used
HIVE_STATS_MAP_NUM_ENTRIES("hive.stats.map.num.entries", 10,
"To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" +
"average row size is multiplied with the total number of rows coming out of each operator.\n" +
"Average row size is computed from average column size of all columns in the row. In the absence\n" +
"of column statistics and for variable length complex columns like map, the average number of\n" +
"entries/values can be specified using this config."),
// statistics annotation fetches column statistics for all required columns which can
// be very expensive sometimes
HIVE_STATS_FETCH_COLUMN_STATS("hive.stats.fetch.column.stats", true,
"Annotation of operator tree with statistics information requires column statistics.\n" +
"Column statistics are fetched from metastore. Fetching column statistics for each needed column\n" +
"can be expensive when the number of columns is high. This flag can be used to disable fetching\n" +
"of column statistics from metastore."),
// in the absence of column statistics, the estimated number of rows/data size that will
// be emitted from join operator will depend on this factor
HIVE_STATS_JOIN_FACTOR("hive.stats.join.factor", (float) 1.1,
"Hive/Tez optimizer estimates the data size flowing through each of the operators. JOIN operator\n" +
"uses column statistics to estimate the number of rows flowing out of it and hence the data size.\n" +
"In the absence of column statistics, this factor determines the amount of rows that flows out\n" +
"of JOIN operator."),
HIVE_STATS_CORRELATED_MULTI_KEY_JOINS("hive.stats.correlated.multi.key.joins", true,
"When estimating output rows for a join involving multiple columns, the default behavior assumes" +
"the columns are independent. Setting this flag to true will cause the estimator to assume" +
"the columns are correlated."),
HIVE_STATS_RANGE_SELECTIVITY_UNIFORM_DISTRIBUTION("hive.stats.filter.range.uniform", true,
"When estimating output rows from a condition, if a range predicate is applied over a column and the\n" +
"minimum and maximum values for that column are available, assume uniform distribution of values\n" +
"across that range and scales number of rows proportionally. If this is set to false, default\n" +
"selectivity value is used."),
// in the absence of uncompressed/raw data size, total file size will be used for statistics
// annotation. But the file may be compressed, encoded and serialized which may be lesser in size
// than the actual uncompressed/raw data size. This factor will be multiplied to file size to estimate
// the raw data size.
HIVE_STATS_DESERIALIZATION_FACTOR("hive.stats.deserialization.factor", (float) 10.0,
"Hive/Tez optimizer estimates the data size flowing through each of the operators. In the absence\n" +
"of basic statistics like number of rows and data size, file size is used to estimate the number\n" +
"of rows and data size. Since files in tables/partitions are serialized (and optionally\n" +
"compressed) the estimates of number of rows and data size cannot be reliably determined.\n" +
"This factor is multiplied with the file size to account for serialization and compression."),
HIVE_STATS_IN_CLAUSE_FACTOR("hive.stats.filter.in.factor", (float) 1.0,
"Currently column distribution is assumed to be uniform. This can lead to overestimation/underestimation\n" +
"in the number of rows filtered by a certain operator, which in turn might lead to overprovision or\n" +
"underprovision of resources. This factor is applied to the cardinality estimation of IN clauses in\n" +
"filter operators."),
HIVE_STATS_IN_MIN_RATIO("hive.stats.filter.in.min.ratio", 0.0f,
"Output estimation of an IN filter can't be lower than this ratio"),
HIVE_STATS_UDTF_FACTOR("hive.stats.udtf.factor", (float) 1.0,
"UDTFs change the number of rows of the output. A common UDTF is the explode() method that creates\n" +
"multiple rows for each element in the input array. This factor is applied to the number of\n" +
"output rows and output size."),
// Concurrency
HIVE_SUPPORT_CONCURRENCY("hive.support.concurrency", false,
"Whether Hive supports concurrency control or not. \n" +
"A ZooKeeper instance must be up and running when using zookeeper Hive lock manager "),
HIVE_LOCK_MANAGER("hive.lock.manager", "org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager", ""),
HIVE_LOCK_NUMRETRIES("hive.lock.numretries", 100,
"The number of times you want to try to get all the locks"),
HIVE_UNLOCK_NUMRETRIES("hive.unlock.numretries", 10,
"The number of times you want to retry to do one unlock"),
HIVE_LOCK_SLEEP_BETWEEN_RETRIES("hive.lock.sleep.between.retries", "60s",
new TimeValidator(TimeUnit.SECONDS, 0L, false, Long.MAX_VALUE, false),
"The maximum sleep time between various retries"),
HIVE_LOCK_MAPRED_ONLY("hive.lock.mapred.only.operation", false,
"This param is to control whether or not only do lock on queries\n" +
"that need to execute at least one mapred job."),
HIVE_LOCK_QUERY_STRING_MAX_LENGTH("hive.lock.query.string.max.length", 1000000,
"The maximum length of the query string to store in the lock.\n" +
"The default value is 1000000, since the data limit of a znode is 1MB"),
HIVE_MM_ALLOW_ORIGINALS("hive.mm.allow.originals", false,
"Whether to allow original files in MM tables. Conversion to MM may be expensive if\n" +
"this is set to false, however unless MAPREDUCE-7086 fix is present (hadoop 3.1.1+),\n" +
"queries that read non-orc MM tables with original files will fail. The default in\n" +
"Hive 3.0 is false."),
// Zookeeper related configs
HIVE_ZOOKEEPER_USE_KERBEROS("hive.zookeeper.kerberos.enabled", true,
"If ZooKeeper is configured for Kerberos authentication. This could be useful when cluster\n" +
"is kerberized, but Zookeeper is not."),
HIVE_ZOOKEEPER_QUORUM("hive.zookeeper.quorum", "",
"List of ZooKeeper servers to talk to. This is needed for: \n" +
"1. Read/write locks - when hive.lock.manager is set to \n" +
"org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager, \n" +
"2. When HiveServer2 supports service discovery via Zookeeper.\n" +
"3. For delegation token storage if zookeeper store is used, if\n" +
"hive.cluster.delegation.token.store.zookeeper.connectString is not set\n" +
"4. LLAP daemon registry service\n" +
"5. Leader selection for privilege synchronizer"),
HIVE_ZOOKEEPER_CLIENT_PORT("hive.zookeeper.client.port", "2181",
"The port of ZooKeeper servers to talk to.\n" +
"If the list of Zookeeper servers specified in hive.zookeeper.quorum\n" +
"does not contain port numbers, this value is used."),
HIVE_ZOOKEEPER_SESSION_TIMEOUT("hive.zookeeper.session.timeout", "120000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"ZooKeeper client's session timeout (in milliseconds). The client is disconnected, and as a result, all locks released, \n" +
"if a heartbeat is not sent in the timeout."),
HIVE_ZOOKEEPER_CONNECTION_TIMEOUT("hive.zookeeper.connection.timeout", "15s",
new TimeValidator(TimeUnit.SECONDS),
"ZooKeeper client's connection timeout in seconds. Connection timeout * hive.zookeeper.connection.max.retries\n" +
"with exponential backoff is when curator client deems connection is lost to zookeeper."),
HIVE_ZOOKEEPER_NAMESPACE("hive.zookeeper.namespace", "hive_zookeeper_namespace",
"The parent node under which all ZooKeeper nodes are created."),
HIVE_ZOOKEEPER_CLEAN_EXTRA_NODES("hive.zookeeper.clean.extra.nodes", false,
"Clean extra nodes at the end of the session."),
HIVE_ZOOKEEPER_CONNECTION_MAX_RETRIES("hive.zookeeper.connection.max.retries", 3,
"Max number of times to retry when connecting to the ZooKeeper server."),
HIVE_ZOOKEEPER_CONNECTION_BASESLEEPTIME("hive.zookeeper.connection.basesleeptime", "1000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Initial amount of time (in milliseconds) to wait between retries\n" +
"when connecting to the ZooKeeper server when using ExponentialBackoffRetry policy."),
HIVE_ZOOKEEPER_SSL_ENABLE("hive.zookeeper.ssl.client.enable", false,
"Set client to use TLS when connecting to ZooKeeper. An explicit value overrides any value set via the " +
"zookeeper.client.secure system property (note the different name). Defaults to false if neither is set."),
HIVE_ZOOKEEPER_SSL_KEYSTORE_LOCATION("hive.zookeeper.ssl.keystore.location", "",
"Keystore location when using a client-side certificate with TLS connectivity to ZooKeeper. " +
"Overrides any explicit value set via the zookeeper.ssl.keyStore.location " +
"system property (note the camelCase)."),
HIVE_ZOOKEEPER_SSL_KEYSTORE_PASSWORD("hive.zookeeper.ssl.keystore.password", "",
"Keystore password when using a client-side certificate with TLS connectivity to ZooKeeper." +
"Overrides any explicit value set via the zookeeper.ssl.keyStore.password " +
"system property (note the camelCase)."),
HIVE_ZOOKEEPER_SSL_TRUSTSTORE_LOCATION("hive.zookeeper.ssl.truststore.location", "",
"Truststore location when using a client-side certificate with TLS connectivity to ZooKeeper. " +
"Overrides any explicit value set via the zookeeper.ssl.trustStore.location" +
"system property (note the camelCase)."),
HIVE_ZOOKEEPER_SSL_TRUSTSTORE_PASSWORD("hive.zookeeper.ssl.truststore.password", "",
"Truststore password when using a client-side certificate with TLS connectivity to ZooKeeper." +
"Overrides any explicit value set via the zookeeper.ssl.trustStore.password " +
"system property (note the camelCase)."),
HIVE_ZOOKEEPER_KILLQUERY_ENABLE("hive.zookeeper.killquery.enable", true,
"Whether enabled kill query coordination with zookeeper, " +
"when hive.server2.support.dynamic.service.discovery is enabled."),
HIVE_ZOOKEEPER_KILLQUERY_NAMESPACE("hive.zookeeper.killquery.namespace", "killQueries",
"When kill query coordination is enabled, uses this namespace for registering queries to kill with zookeeper"),
// Transactions
HIVE_TXN_MANAGER("hive.txn.manager",
"org.apache.hadoop.hive.ql.lockmgr.DummyTxnManager",
"Set to org.apache.hadoop.hive.ql.lockmgr.DbTxnManager as part of turning on Hive\n" +
"transactions, which also requires appropriate settings for hive.compactor.initiator.on,\n" +
"hive.compactor.worker.threads, hive.support.concurrency (true),\n" +
"and hive.exec.dynamic.partition.mode (nonstrict).\n" +
"The default DummyTxnManager replicates pre-Hive-0.13 behavior and provides\n" +
"no transactions."),
HIVE_TXN_STRICT_LOCKING_MODE("hive.txn.strict.locking.mode", true, "In strict mode non-ACID\n" +
"resources use standard R/W lock semantics, e.g. INSERT will acquire exclusive lock.\n" +
"In nonstrict mode, for non-ACID resources, INSERT will only acquire shared lock, which\n" +
"allows two concurrent writes to the same partition but still lets lock manager prevent\n" +
"DROP TABLE etc. when the table is being written to"),
HIVE_TXN_NONACID_READ_LOCKS("hive.txn.nonacid.read.locks", true,
"Flag to turn off the read locks for non-ACID tables, when set to false.\n" +
"Could be exercised to improve the performance of non-ACID tables in clusters where read locking " +
"is enabled globally to support ACID. Can cause issues with concurrent DDL operations, or slow S3 writes."),
HIVE_TXN_READ_LOCKS("hive.txn.read.locks", true,
"Flag to turn off the read locks, when set to false. Although its not recommended, \n" +
"but in performance critical scenarios this option may be exercised."),
HIVE_LOCKS_PARTITION_THRESHOLD("hive.locks.max.partitions", -1,
"Locks the entire table if number of partition locks exceeds user-defined threshold. Disabled by default."),
TXN_OVERWRITE_X_LOCK("hive.txn.xlock.iow", true,
"Ensures commands with OVERWRITE (such as INSERT OVERWRITE) acquire Exclusive locks for\n" +
"transactional tables. This ensures that inserts (w/o overwrite) running concurrently\n" +
"are not hidden by the INSERT OVERWRITE."),
TXN_MERGE_INSERT_X_LOCK("hive.txn.xlock.mergeinsert", false,
"Ensures MERGE INSERT operations acquire EXCLUSIVE / EXCL_WRITE lock for transactional tables.\n" +
"If enabled, prevents duplicates when MERGE statements are executed in parallel transactions."),
TXN_WRITE_X_LOCK("hive.txn.xlock.write", true,
"Manages concurrency levels for ACID resources. Provides better level of query parallelism by enabling " +
"shared writes and write-write conflict resolution at the commit step." +
"- If true - exclusive writes are used:\n" +
" - INSERT OVERWRITE acquires EXCLUSIVE locks\n" +
" - UPDATE/DELETE acquire EXCL_WRITE locks\n" +
" - INSERT acquires SHARED_READ locks\n" +
"- If false - shared writes, transaction is aborted in case of conflicting changes:\n" +
" - INSERT OVERWRITE acquires EXCL_WRITE locks\n" +
" - INSERT/UPDATE/DELETE acquire SHARED_READ locks"),
HIVE_TXN_STATS_ENABLED("hive.txn.stats.enabled", true,
"Whether Hive supports transactional stats (accurate stats for transactional tables)"),
HIVE_TXN_ACID_DIR_CACHE_DURATION("hive.txn.acid.dir.cache.duration",
120, "Enable dir cache for ACID tables specified in minutes."
+ "0 indicates cache is used as read-only and no additional info would be "
+ "populated. -1 means cache is disabled"),
HIVE_WRITE_ACID_VERSION_FILE("hive.txn.write.acid.version.file", true,
"Creates an _orc_acid_version file along with acid files, to store the version data"),
HIVE_TXN_READONLY_ENABLED("hive.txn.readonly.enabled", false,
"Enables read-only transaction classification and related optimizations"),
/**
* @deprecated Use MetastoreConf.TXN_TIMEOUT
*/
@Deprecated
HIVE_TXN_TIMEOUT("hive.txn.timeout", "300s", new TimeValidator(TimeUnit.SECONDS),
"time after which transactions are declared aborted if the client has not sent a heartbeat."),
/**
* @deprecated Use MetastoreConf.TXN_HEARTBEAT_THREADPOOL_SIZE
*/
@Deprecated
HIVE_TXN_HEARTBEAT_THREADPOOL_SIZE("hive.txn.heartbeat.threadpool.size", 5, "The number of " +
"threads to use for heartbeating. For Hive CLI, 1 is enough. For HiveServer2, we need a few"),
TXN_MGR_DUMP_LOCK_STATE_ON_ACQUIRE_TIMEOUT("hive.txn.manager.dump.lock.state.on.acquire.timeout", false,
"Set this to true so that when attempt to acquire a lock on resource times out, the current state" +
" of the lock manager is dumped to log file. This is for debugging. See also " +
"hive.lock.numretries and hive.lock.sleep.between.retries."),
HIVE_TXN_OPERATIONAL_PROPERTIES("hive.txn.operational.properties", 1,
"1: Enable split-update feature found in the newer version of Hive ACID subsystem\n" +
"4: Make the table 'quarter-acid' as it only supports insert. But it doesn't require ORC or bucketing.\n" +
"This is intended to be used as an internal property for future versions of ACID. (See\n" +
"HIVE-14035 for details. User sets it tblproperites via transactional_properties.)", true),
/**
* @deprecated Use MetastoreConf.MAX_OPEN_TXNS
*/
@Deprecated
HIVE_MAX_OPEN_TXNS("hive.max.open.txns", 100000, "Maximum number of open transactions. If \n" +
"current open transactions reach this limit, future open transaction requests will be \n" +
"rejected, until this number goes below the limit."),
/**
* @deprecated Use MetastoreConf.COUNT_OPEN_TXNS_INTERVAL
*/
@Deprecated
HIVE_COUNT_OPEN_TXNS_INTERVAL("hive.count.open.txns.interval", "1s",
new TimeValidator(TimeUnit.SECONDS), "Time in seconds between checks to count open transactions."),
/**
* @deprecated Use MetastoreConf.TXN_MAX_OPEN_BATCH
*/
@Deprecated
HIVE_TXN_MAX_OPEN_BATCH("hive.txn.max.open.batch", 1000,
"Maximum number of transactions that can be fetched in one call to open_txns().\n" +
"This controls how many transactions streaming agents such as Flume or Storm open\n" +
"simultaneously. The streaming agent then writes that number of entries into a single\n" +
"file (per Flume agent or Storm bolt). Thus increasing this value decreases the number\n" +
"of delta files created by streaming agents. But it also increases the number of open\n" +
"transactions that Hive has to track at any given time, which may negatively affect\n" +
"read performance."),
/**
* @deprecated Use MetastoreConf.TXN_RETRYABLE_SQLEX_REGEX
*/
@Deprecated
HIVE_TXN_RETRYABLE_SQLEX_REGEX("hive.txn.retryable.sqlex.regex", "", "Comma separated list\n" +
"of regular expression patterns for SQL state, error code, and error message of\n" +
"retryable SQLExceptions, that's suitable for the metastore DB.\n" +
"For example: Can't serialize.*,40001$,^Deadlock,.*ORA-08176.*\n" +
"The string that the regex will be matched against is of the following form, where ex is a SQLException:\n" +
"ex.getMessage() + \" (SQLState=\" + ex.getSQLState() + \", ErrorCode=\" + ex.getErrorCode() + \")\""),
/**
* @deprecated Use MetastoreConf.COMPACTOR_INITIATOR_ON
*/
@Deprecated
HIVE_COMPACTOR_INITIATOR_ON("hive.compactor.initiator.on", false,
"Whether to run the initiator and cleaner threads on this metastore instance or not.\n" +
"Set this to true on one instance of the Thrift metastore service as part of turning\n" +
"on Hive transactions. For a complete list of parameters required for turning on\n" +
"transactions, see hive.txn.manager."),
/**
* @deprecated Use MetastoreConf.COMPACTOR_WORKER_THREADS
*/
@Deprecated
HIVE_COMPACTOR_WORKER_THREADS("hive.compactor.worker.threads", 0,
"How many compactor worker threads to run on this metastore instance. Set this to a\n" +
"positive number on one or more instances of the Thrift metastore service as part of\n" +
"turning on Hive transactions. For a complete list of parameters required for turning\n" +
"on transactions, see hive.txn.manager.\n" +
"Worker threads spawn MapReduce jobs to do compactions. They do not do the compactions\n" +
"themselves. Increasing the number of worker threads will decrease the time it takes\n" +
"tables or partitions to be compacted once they are determined to need compaction.\n" +
"It will also increase the background load on the Hadoop cluster as more MapReduce jobs\n" +
"will be running in the background."),
HIVE_COMPACTOR_WORKER_TIMEOUT("hive.compactor.worker.timeout", "86400s",
new TimeValidator(TimeUnit.SECONDS),
"Time in seconds after which a compaction job will be declared failed and the\n" +
"compaction re-queued."),
HIVE_COMPACTOR_CHECK_INTERVAL("hive.compactor.check.interval", "300s",
new TimeValidator(TimeUnit.SECONDS),
"Time in seconds between checks to see if any tables or partitions need to be\n" +
"compacted. This should be kept high because each check for compaction requires\n" +
"many calls against the NameNode.\n" +
"Decreasing this value will reduce the time it takes for compaction to be started\n" +
"for a table or partition that requires compaction. However, checking if compaction\n" +
"is needed requires several calls to the NameNode for each table or partition that\n" +
"has had a transaction done on it since the last major compaction. So decreasing this\n" +
"value will increase the load on the NameNode."),
HIVE_COMPACTOR_REQUEST_QUEUE("hive.compactor.request.queue", 1,
"Enables parallelization of the checkForCompaction operation, that includes many file metadata checks\n" +
"and may be expensive"),
HIVE_COMPACTOR_DELTA_NUM_THRESHOLD("hive.compactor.delta.num.threshold", 10,
"Number of delta directories in a table or partition that will trigger a minor\n" +
"compaction."),
HIVE_COMPACTOR_DELTA_PCT_THRESHOLD("hive.compactor.delta.pct.threshold", 0.1f,
"Percentage (fractional) size of the delta files relative to the base that will trigger\n" +
"a major compaction. (1.0 = 100%, so the default 0.1 = 10%.)"),
COMPACTOR_MAX_NUM_DELTA("hive.compactor.max.num.delta", 500, "Maximum number of delta files that " +
"the compactor will attempt to handle in a single job."),
HIVE_COMPACTOR_ABORTEDTXN_THRESHOLD("hive.compactor.abortedtxn.threshold", 1000,
"Number of aborted transactions involving a given table or partition that will trigger\n" +
"a major compaction."),
HIVE_COMPACTOR_ABORTEDTXN_TIME_THRESHOLD("hive.compactor.aborted.txn.time.threshold", "12h",
new TimeValidator(TimeUnit.HOURS),
"Age of table/partition's oldest aborted transaction when compaction will be triggered. " +
"Default time unit is: hours. Set to a negative number to disable."),
HIVE_COMPACTOR_WAIT_TIMEOUT("hive.compactor.wait.timeout", 300000L, "Time out in "
+ "milliseconds for blocking compaction. It's value has to be higher than 2000 milliseconds. "),
HIVE_MR_COMPACTOR_GATHER_STATS("hive.mr.compactor.gather.stats", true, "If set to true MAJOR compaction " +
"will gather stats if there are stats already associated with the table/partition.\n" +
"Turn this off to save some resources and the stats are not used anyway.\n" +
"Works only for MR based compaction, CRUD based compaction uses hive.stats.autogather."),
/**
* @deprecated Use MetastoreConf.COMPACTOR_INITIATOR_FAILED_THRESHOLD
*/
@Deprecated
COMPACTOR_INITIATOR_FAILED_THRESHOLD("hive.compactor.initiator.failed.compacts.threshold", 2,
new RangeValidator(1, 20), "Number of consecutive compaction failures (per table/partition) " +
"after which automatic compactions will not be scheduled any more. Note that this must be less " +
"than hive.compactor.history.retention.failed."),
HIVE_COMPACTOR_CLEANER_RUN_INTERVAL("hive.compactor.cleaner.run.interval", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS), "Time between runs of the cleaner thread"),
HIVE_COMPACTOR_DELAYED_CLEANUP_ENABLED("hive.compactor.delayed.cleanup.enabled", false,
"When enabled, cleanup of obsolete files/dirs after compaction can be delayed. This delay \n" +
" can be configured by hive configuration hive.compactor.cleaner.retention.time.seconds"),
HIVE_COMPACTOR_CLEANER_RETENTION_TIME("hive.compactor.cleaner.retention.time.seconds", "300s",
new TimeValidator(TimeUnit.SECONDS), "Time to wait before cleanup of obsolete files/dirs after compaction. \n"
+ "This is the minimum amount of time the system will wait, since it will not clean before all open transactions are committed, that were opened before the compaction"),
HIVE_COMPACTOR_CLEANER_THREADS_NUM("hive.compactor.cleaner.threads.num", 1,
"Enables parallelization of the cleaning directories after compaction, that includes many file \n" +
"related checks and may be expensive"),
COMPACTOR_JOB_QUEUE("hive.compactor.job.queue", "", "Used to specify name of Hadoop queue to which\n" +
"Compaction jobs will be submitted. Set to empty string to let Hadoop choose the queue."),
TRANSACTIONAL_CONCATENATE_NOBLOCK("hive.transactional.concatenate.noblock", false,
"Will cause 'alter table T concatenate' to be non-blocking"),
HIVE_COMPACTOR_COMPACT_MM("hive.compactor.compact.insert.only", true,
"Whether the compactor should compact insert-only tables. A safety switch."),
COMPACTOR_CRUD_QUERY_BASED("hive.compactor.crud.query.based", false,
"Means compaction on full CRUD tables is done via queries. "
+ "Compactions on insert-only tables will always run via queries regardless of the value of this configuration."),
SPLIT_GROUPING_MODE("hive.split.grouping.mode", "query", new StringSet("query", "compactor"),
"This is set to compactor from within the query based compactor. This enables the Tez SplitGrouper "
+ "to group splits based on their bucket number, so that all rows from different bucket files "
+ " for the same bucket number can end up in the same bucket file after the compaction."),
/**
* @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_SUCCEEDED
*/
@Deprecated
COMPACTOR_HISTORY_RETENTION_SUCCEEDED("hive.compactor.history.retention.succeeded", 3,
new RangeValidator(0, 100), "Determines how many successful compaction records will be " +
"retained in compaction history for a given table/partition."),
/**
* @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_FAILED
*/
@Deprecated
COMPACTOR_HISTORY_RETENTION_FAILED("hive.compactor.history.retention.failed", 3,
new RangeValidator(0, 100), "Determines how many failed compaction records will be " +
"retained in compaction history for a given table/partition."),
/**
* @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_ATTEMPTED
*/
@Deprecated
COMPACTOR_HISTORY_RETENTION_ATTEMPTED("hive.compactor.history.retention.attempted", 2,
new RangeValidator(0, 100), "Determines how many attempted compaction records will be " +
"retained in compaction history for a given table/partition."),
/**
* @deprecated Use MetastoreConf.ACID_HOUSEKEEPER_SERVICE_INTERVAL
*/
@Deprecated
COMPACTOR_HISTORY_REAPER_INTERVAL("hive.compactor.history.reaper.interval", "2m",
new TimeValidator(TimeUnit.MILLISECONDS), "Determines how often compaction history reaper runs"),
/**
* @deprecated Use MetastoreConf.ACID_HOUSEKEEPER_SERVICE_START
*/
@Deprecated
HIVE_TIMEDOUT_TXN_REAPER_START("hive.timedout.txn.reaper.start", "100s",
new TimeValidator(TimeUnit.MILLISECONDS), "Time delay of 1st reaper run after metastore start"),
/**
* @deprecated Use MetastoreConf.ACID_HOUSEKEEPER_SERVICE_INTERVAL
*/
@Deprecated
HIVE_TIMEDOUT_TXN_REAPER_INTERVAL("hive.timedout.txn.reaper.interval", "180s",
new TimeValidator(TimeUnit.MILLISECONDS), "Time interval describing how often the reaper runs"),
/**
* @deprecated Use MetastoreConf.ACID_HOUSEKEEPER_SERVICE_INTERVAL
*/
@Deprecated
WRITE_SET_REAPER_INTERVAL("hive.writeset.reaper.interval", "60s",
new TimeValidator(TimeUnit.MILLISECONDS), "Frequency of WriteSet reaper runs"),
MERGE_CARDINALITY_VIOLATION_CHECK("hive.merge.cardinality.check", true,
"Set to true to ensure that each SQL Merge statement ensures that for each row in the target\n" +
"table there is at most 1 matching row in the source table per SQL Specification."),
MERGE_SPLIT_UPDATE("hive.merge.split.update", false,
"If true, SQL Merge statement will handle WHEN MATCHED UPDATE by splitting it into 2\n" +
"branches of a multi-insert, representing delete of existing row and an insert of\n" +
"the new version of the row. Updating bucketing and partitioning columns should\n" +
"only be permitted if this is true."),
OPTIMIZE_ACID_META_COLUMNS("hive.optimize.acid.meta.columns", true,
"If true, don't decode Acid metadata columns from storage unless" +
" they are needed."),
// For Arrow SerDe
HIVE_ARROW_ROOT_ALLOCATOR_LIMIT("hive.arrow.root.allocator.limit", Long.MAX_VALUE,
"Arrow root allocator memory size limitation in bytes."),
HIVE_ARROW_BATCH_ALLOCATOR_LIMIT("hive.arrow.batch.allocator.limit", 10_000_000_000L,
"Max bytes per arrow batch. This is a threshold, the memory is not pre-allocated."),
HIVE_ARROW_BATCH_SIZE("hive.arrow.batch.size", 1000, "The number of rows sent in one Arrow batch."),
// For Druid storage handler
HIVE_DRUID_INDEXING_GRANULARITY("hive.druid.indexer.segments.granularity", "DAY",
new PatternSet("YEAR", "MONTH", "WEEK", "DAY", "HOUR", "MINUTE", "SECOND"),
"Granularity for the segments created by the Druid storage handler"
),
HIVE_DRUID_MAX_PARTITION_SIZE("hive.druid.indexer.partition.size.max", 5000000,
"Maximum number of records per segment partition"
),
HIVE_DRUID_MAX_ROW_IN_MEMORY("hive.druid.indexer.memory.rownum.max", 75000,
"Maximum number of records in memory while storing data in Druid"
),
HIVE_DRUID_BROKER_DEFAULT_ADDRESS("hive.druid.broker.address.default", "localhost:8082",
"Address of the Druid broker. If we are querying Druid from Hive, this address needs to be\n"
+
"declared"
),
HIVE_DRUID_COORDINATOR_DEFAULT_ADDRESS("hive.druid.coordinator.address.default", "localhost:8081",
"Address of the Druid coordinator. It is used to check the load status of newly created segments"
),
HIVE_DRUID_OVERLORD_DEFAULT_ADDRESS("hive.druid.overlord.address.default", "localhost:8090",
"Address of the Druid overlord. It is used to submit indexing tasks to druid."
),
HIVE_DRUID_SELECT_THRESHOLD("hive.druid.select.threshold", 10000,
"Takes only effect when hive.druid.select.distribute is set to false. \n" +
"When we can split a Select query, this is the maximum number of rows that we try to retrieve\n" +
"per query. In order to do that, we obtain the estimated size for the complete result. If the\n" +
"number of records of the query results is larger than this threshold, we split the query in\n" +
"total number of rows/threshold parts across the time dimension. Note that we assume the\n" +
"records to be split uniformly across the time dimension."),
HIVE_DRUID_NUM_HTTP_CONNECTION("hive.druid.http.numConnection", 20, "Number of connections used by\n" +
"the HTTP client."),
HIVE_DRUID_HTTP_READ_TIMEOUT("hive.druid.http.read.timeout", "PT1M", "Read timeout period for the HTTP\n" +
"client in ISO8601 format (for example P2W, P3M, PT1H30M, PT0.750S), default is period of 1 minute."),
HIVE_DRUID_SLEEP_TIME("hive.druid.sleep.time", "PT10S",
"Sleep time between retries in ISO8601 format (for example P2W, P3M, PT1H30M, PT0.750S), default is period of 10 seconds."
),
HIVE_DRUID_BASE_PERSIST_DIRECTORY("hive.druid.basePersistDirectory", "",
"Local temporary directory used to persist intermediate indexing state, will default to JVM system property java.io.tmpdir."
),
HIVE_DRUID_ROLLUP("hive.druid.rollup", true, "Whether to rollup druid rows or not."),
DRUID_SEGMENT_DIRECTORY("hive.druid.storage.storageDirectory", "/druid/segments"
, "druid deep storage location."),
DRUID_METADATA_BASE("hive.druid.metadata.base", "druid", "Default prefix for metadata tables"),
DRUID_METADATA_DB_TYPE("hive.druid.metadata.db.type", "mysql",
new PatternSet("mysql", "postgresql", "derby"), "Type of the metadata database."
),
DRUID_METADATA_DB_USERNAME("hive.druid.metadata.username", "",
"Username to connect to Type of the metadata DB."
),
DRUID_METADATA_DB_PASSWORD("hive.druid.metadata.password", "",
"Password to connect to Type of the metadata DB."
),
DRUID_METADATA_DB_URI("hive.druid.metadata.uri", "",
"URI to connect to the database (for example jdbc:mysql://hostname:port/DBName)."
),
DRUID_WORKING_DIR("hive.druid.working.directory", "/tmp/workingDirectory",
"Default hdfs working directory used to store some intermediate metadata"
),
HIVE_DRUID_MAX_TRIES("hive.druid.maxTries", 5, "Maximum number of retries before giving up"),
HIVE_DRUID_PASSIVE_WAIT_TIME("hive.druid.passiveWaitTimeMs", 30000L,
"Wait time in ms default to 30 seconds."
),
HIVE_DRUID_BITMAP_FACTORY_TYPE("hive.druid.bitmap.type", "roaring", new PatternSet("roaring", "concise"), "Coding algorithm use to encode the bitmaps"),
HIVE_DRUID_KERBEROS_ENABLE("hive.druid.kerberos.enable", true,
"Enable/Disable Kerberos authentication explicitly while connecting to a druid cluster."),
// For HBase storage handler
HIVE_HBASE_WAL_ENABLED("hive.hbase.wal.enabled", true,
"Whether writes to HBase should be forced to the write-ahead log. \n" +
"Disabling this improves HBase write performance at the risk of lost writes in case of a crash."),
HIVE_HBASE_GENERATE_HFILES("hive.hbase.generatehfiles", false,
"True when HBaseStorageHandler should generate hfiles instead of operate against the online table."),
HIVE_HBASE_SNAPSHOT_NAME("hive.hbase.snapshot.name", null, "The HBase table snapshot name to use."),
HIVE_HBASE_SNAPSHOT_RESTORE_DIR("hive.hbase.snapshot.restoredir", "/tmp", "The directory in which to " +
"restore the HBase table snapshot."),
// For Kudu storage handler
HIVE_KUDU_MASTER_ADDRESSES_DEFAULT("hive.kudu.master.addresses.default", "localhost:7050",
"Comma-separated list of all of the Kudu master addresses.\n" +
"This value is only used for a given table if the kudu.master_addresses table property is not set."),
// For har files
HIVEARCHIVEENABLED("hive.archive.enabled", false, "Whether archiving operations are permitted"),
HIVEFETCHTASKCONVERSION("hive.fetch.task.conversion", "more", new StringSet("none", "minimal", "more"),
"Some select queries can be converted to single FETCH task minimizing latency.\n" +
"Currently the query should be single sourced not having any subquery and should not have\n" +
"any aggregations or distincts (which incurs RS), lateral views and joins.\n" +
"0. none : disable hive.fetch.task.conversion\n" +
"1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only\n" +
"2. more : SELECT, FILTER, LIMIT only (support TABLESAMPLE and virtual columns)"
),
HIVEFETCHTASKCONVERSIONTHRESHOLD("hive.fetch.task.conversion.threshold", 1073741824L,
"Input threshold for applying hive.fetch.task.conversion. If target table is native, input length\n" +
"is calculated by summation of file lengths. If it's not native, storage handler for the table\n" +
"can optionally implement org.apache.hadoop.hive.ql.metadata.InputEstimator interface."),
HIVEFETCHTASKAGGR("hive.fetch.task.aggr", false,
"Aggregation queries with no group-by clause (for example, select count(*) from src) execute\n" +
"final aggregations in single reduce task. If this is set true, Hive delegates final aggregation\n" +
"stage to fetch task, possibly decreasing the query time."),
HIVEOPTIMIZEMETADATAQUERIES("hive.compute.query.using.stats", true,
"When set to true Hive will answer a few queries like count(1) purely using stats\n" +
"stored in metastore. For basic stats collection turn on the config hive.stats.autogather to true.\n" +
"For more advanced stats collection need to run analyze table queries."),
// Serde for FetchTask
HIVEFETCHOUTPUTSERDE("hive.fetch.output.serde", "org.apache.hadoop.hive.serde2.DelimitedJSONSerDe",
"The SerDe used by FetchTask to serialize the fetch output."),
HIVEEXPREVALUATIONCACHE("hive.cache.expr.evaluation", true,
"If true, the evaluation result of a deterministic expression referenced twice or more\n" +
"will be cached.\n" +
"For example, in a filter condition like '.. where key + 10 = 100 or key + 10 = 0'\n" +
"the expression 'key + 10' will be evaluated/cached once and reused for the following\n" +
"expression ('key + 10 = 0'). Currently, this is applied only to expressions in select\n" +
"or filter operators."),
// Hive Variables
HIVEVARIABLESUBSTITUTE("hive.variable.substitute", true,
"This enables substitution using syntax like ${var} ${system:var} and ${env:var}."),
HIVEVARIABLESUBSTITUTEDEPTH("hive.variable.substitute.depth", 40,
"The maximum replacements the substitution engine will do."),
HIVECONFVALIDATION("hive.conf.validation", true,
"Enables type checking for registered Hive configurations"),
SEMANTIC_ANALYZER_HOOK("hive.semantic.analyzer.hook", "", ""),
HIVE_TEST_AUTHORIZATION_SQLSTD_HS2_MODE(
"hive.test.authz.sstd.hs2.mode", false, "test hs2 mode from .q tests", true),
HIVE_AUTHORIZATION_ENABLED("hive.security.authorization.enabled", false,
"enable or disable the Hive client authorization"),
HIVE_AUTHORIZATION_KERBEROS_USE_SHORTNAME("hive.security.authorization.kerberos.use.shortname", true,
"use short name in Kerberos cluster"),
HIVE_AUTHORIZATION_MANAGER("hive.security.authorization.manager",
"org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactory",
"The Hive client authorization manager class name. The user defined authorization class should implement \n" +
"interface org.apache.hadoop.hive.ql.security.authorization.HiveAuthorizationProvider."),
HIVE_AUTHENTICATOR_MANAGER("hive.security.authenticator.manager",
"org.apache.hadoop.hive.ql.security.HadoopDefaultAuthenticator",
"hive client authenticator manager class name. The user defined authenticator should implement \n" +
"interface org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider."),
HIVE_METASTORE_AUTHORIZATION_MANAGER("hive.security.metastore.authorization.manager",
"org.apache.hadoop.hive.ql.security.authorization.DefaultHiveMetastoreAuthorizationProvider",
"Names of authorization manager classes (comma separated) to be used in the metastore\n" +
"for authorization. The user defined authorization class should implement interface\n" +
"org.apache.hadoop.hive.ql.security.authorization.HiveMetastoreAuthorizationProvider.\n" +
"All authorization manager classes have to successfully authorize the metastore API\n" +
"call for the command execution to be allowed."),
HIVE_METASTORE_AUTHORIZATION_AUTH_READS("hive.security.metastore.authorization.auth.reads", true,
"If this is true, metastore authorizer authorizes read actions on database, table"),
HIVE_METASTORE_AUTHENTICATOR_MANAGER("hive.security.metastore.authenticator.manager",
"org.apache.hadoop.hive.ql.security.HadoopDefaultMetastoreAuthenticator",
"authenticator manager class name to be used in the metastore for authentication. \n" +
"The user defined authenticator should implement interface org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider."),
HIVE_AUTHORIZATION_TABLE_USER_GRANTS("hive.security.authorization.createtable.user.grants", "",
"the privileges automatically granted to some users whenever a table gets created.\n" +
"An example like \"userX,userY:select;userZ:create\" will grant select privilege to userX and userY,\n" +
"and grant create privilege to userZ whenever a new table created."),
HIVE_AUTHORIZATION_TABLE_GROUP_GRANTS("hive.security.authorization.createtable.group.grants",
"",
"the privileges automatically granted to some groups whenever a table gets created.\n" +
"An example like \"groupX,groupY:select;groupZ:create\" will grant select privilege to groupX and groupY,\n" +
"and grant create privilege to groupZ whenever a new table created."),
HIVE_AUTHORIZATION_TABLE_ROLE_GRANTS("hive.security.authorization.createtable.role.grants", "",
"the privileges automatically granted to some roles whenever a table gets created.\n" +
"An example like \"roleX,roleY:select;roleZ:create\" will grant select privilege to roleX and roleY,\n" +
"and grant create privilege to roleZ whenever a new table created."),
HIVE_AUTHORIZATION_TABLE_OWNER_GRANTS("hive.security.authorization.createtable.owner.grants",
"",
"The privileges automatically granted to the owner whenever a table gets created.\n" +
"An example like \"select,drop\" will grant select and drop privilege to the owner\n" +
"of the table. Note that the default gives the creator of a table no access to the\n" +
"table (but see HIVE-8067)."),
HIVE_AUTHORIZATION_TASK_FACTORY("hive.security.authorization.task.factory",
"org.apache.hadoop.hive.ql.parse.authorization.HiveAuthorizationTaskFactoryImpl",
"Authorization DDL task factory implementation"),
// if this is not set default value is set during config initialization
// Default value can't be set in this constructor as it would refer names in other ConfVars
// whose constructor would not have been called
HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST(
"hive.security.authorization.sqlstd.confwhitelist", "",
"A Java regex. Configurations parameters that match this\n" +
"regex can be modified by user when SQL standard authorization is enabled.\n" +
"To get the default value, use the 'set <param>' command.\n" +
"Note that the hive.conf.restricted.list checks are still enforced after the white list\n" +
"check"),
HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST_APPEND(
"hive.security.authorization.sqlstd.confwhitelist.append", "",
"2nd Java regex that it would match in addition to\n" +
"hive.security.authorization.sqlstd.confwhitelist.\n" +
"Do not include a starting \"|\" in the value. Using this regex instead\n" +
"of updating the original regex means that you can append to the default\n" +
"set by SQL standard authorization instead of replacing it entirely."),
HIVE_CLI_PRINT_HEADER("hive.cli.print.header", false, "Whether to print the names of the columns in query output."),
HIVE_CLI_PRINT_ESCAPE_CRLF("hive.cli.print.escape.crlf", false,
"Whether to print carriage returns and line feeds in row output as escaped \\r and \\n"),
HIVE_CLI_TEZ_SESSION_ASYNC("hive.cli.tez.session.async", true, "Whether to start Tez\n" +
"session in background when running CLI with Tez, allowing CLI to be available earlier."),
HIVE_DISABLE_UNSAFE_EXTERNALTABLE_OPERATIONS("hive.disable.unsafe.external.table.operations", true,
"Whether to disable certain optimizations and operations on external tables," +
" on the assumption that data changes by external applications may have negative effects" +
" on these operations."),
HIVE_STRICT_MANAGED_TABLES("hive.strict.managed.tables", false,
"Whether strict managed tables mode is enabled. With this mode enabled, " +
"only transactional tables (both full and insert-only) are allowed to be created as managed tables"),
HIVE_EXTERNALTABLE_PURGE_DEFAULT("hive.external.table.purge.default", false,
"Set to true to set external.table.purge=true on newly created external tables," +
" which will specify that the table data should be deleted when the table is dropped." +
" Set to false maintain existing behavior that external tables do not delete data" +
" when the table is dropped."),
HIVE_ERROR_ON_EMPTY_PARTITION("hive.error.on.empty.partition", false,
"Whether to throw an exception if dynamic partition insert generates empty results."),
HIVE_EXIM_URI_SCHEME_WL("hive.exim.uri.scheme.whitelist", "hdfs,pfile,file,s3,s3a,gs",
"A comma separated list of acceptable URI schemes for import and export."),
// temporary variable for testing. This is added just to turn off this feature in case of a bug in
// deployment. It has not been documented in hive-default.xml intentionally, this should be removed
// once the feature is stable
HIVE_EXIM_RESTRICT_IMPORTS_INTO_REPLICATED_TABLES("hive.exim.strict.repl.tables",true,
"Parameter that determines if 'regular' (non-replication) export dumps can be\n" +
"imported on to tables that are the target of replication. If this parameter is\n" +
"set, regular imports will check if the destination table(if it exists) has a " +
"'repl.last.id' set on it. If so, it will fail."),
HIVE_REPL_TASK_FACTORY("hive.repl.task.factory",
"org.apache.hive.hcatalog.api.repl.exim.EximReplicationTaskFactory",
"Parameter that can be used to override which ReplicationTaskFactory will be\n" +
"used to instantiate ReplicationTask events. Override for third party repl plugins"),
HIVE_MAPPER_CANNOT_SPAN_MULTIPLE_PARTITIONS("hive.mapper.cannot.span.multiple.partitions", false, ""),
HIVE_REWORK_MAPREDWORK("hive.rework.mapredwork", false,
"should rework the mapred work or not.\n" +
"This is first introduced by SymlinkTextInputFormat to replace symlink files with real paths at compile time."),
HIVE_IO_EXCEPTION_HANDLERS("hive.io.exception.handlers", "",
"A list of io exception handler class names. This is used\n" +
"to construct a list exception handlers to handle exceptions thrown\n" +
"by record readers"),
// logging configuration
HIVE_LOG4J_FILE("hive.log4j.file", "",
"Hive log4j configuration file.\n" +
"If the property is not set, then logging will be initialized using hive-log4j2.properties found on the classpath.\n" +
"If the property is set, the value must be a valid URI (java.net.URI, e.g. \"file:///tmp/my-logging.xml\"), \n" +
"which you can then extract a URL from and pass to PropertyConfigurator.configure(URL)."),
HIVE_EXEC_LOG4J_FILE("hive.exec.log4j.file", "",
"Hive log4j configuration file for execution mode(sub command).\n" +
"If the property is not set, then logging will be initialized using hive-exec-log4j2.properties found on the classpath.\n" +
"If the property is set, the value must be a valid URI (java.net.URI, e.g. \"file:///tmp/my-logging.xml\"), \n" +
"which you can then extract a URL from and pass to PropertyConfigurator.configure(URL)."),
HIVE_ASYNC_LOG_ENABLED("hive.async.log.enabled", true,
"Whether to enable Log4j2's asynchronous logging. Asynchronous logging can give\n" +
" significant performance improvement as logging will be handled in separate thread\n" +
" that uses LMAX disruptor queue for buffering log messages.\n" +
" Refer https://logging.apache.org/log4j/2.x/manual/async.html for benefits and\n" +
" drawbacks."),
HIVE_LOG_EXPLAIN_OUTPUT("hive.log.explain.output", false,
"Whether to log explain output for every query.\n"
+ "When enabled, will log EXPLAIN EXTENDED output for the query at INFO log4j log level."),
HIVE_EXPLAIN_USER("hive.explain.user", true,
"Whether to show explain result at user level.\n" +
"When enabled, will log EXPLAIN output for the query at user level. Tez only."),
HIVE_SPARK_EXPLAIN_USER("hive.spark.explain.user", false,
"Whether to show explain result at user level.\n" +
"When enabled, will log EXPLAIN output for the query at user level. Spark only."),
HIVE_SPARK_LOG_EXPLAIN_WEBUI("hive.spark.log.explain.webui", true, "Whether to show the " +
"explain plan in the Spark Web UI. Only shows the regular EXPLAIN plan, and ignores " +
"any extra EXPLAIN configuration (e.g. hive.spark.explain.user, etc.). The explain " +
"plan for each stage is truncated at 100,000 characters."),
// prefix used to auto generated column aliases (this should be s,tarted with '_')
HIVE_AUTOGEN_COLUMNALIAS_PREFIX_LABEL("hive.autogen.columnalias.prefix.label", "_c",
"String used as a prefix when auto generating column alias.\n" +
"By default the prefix label will be appended with a column position number to form the column alias. \n" +
"Auto generation would happen if an aggregate function is used in a select clause without an explicit alias."),
HIVE_AUTOGEN_COLUMNALIAS_PREFIX_INCLUDEFUNCNAME(
"hive.autogen.columnalias.prefix.includefuncname", false,
"Whether to include function name in the column alias auto generated by Hive."),
HIVE_METRICS_CLASS("hive.service.metrics.class",
"org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics",
new StringSet(
"org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics",
"org.apache.hadoop.hive.common.metrics.LegacyMetrics"),
"Hive metrics subsystem implementation class."),
HIVE_CODAHALE_METRICS_REPORTER_CLASSES("hive.service.metrics.codahale.reporter.classes",
"org.apache.hadoop.hive.common.metrics.metrics2.JsonFileMetricsReporter, " +
"org.apache.hadoop.hive.common.metrics.metrics2.JmxMetricsReporter",
"Comma separated list of reporter implementation classes for metric class "
+ "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics. Overrides "
+ "HIVE_METRICS_REPORTER conf if present"),
@Deprecated
HIVE_METRICS_REPORTER("hive.service.metrics.reporter", "",
"Reporter implementations for metric class "
+ "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics;" +
"Deprecated, use HIVE_CODAHALE_METRICS_REPORTER_CLASSES instead. This configuraiton will be"
+ " overridden by HIVE_CODAHALE_METRICS_REPORTER_CLASSES if present. " +
"Comma separated list of JMX, CONSOLE, JSON_FILE, HADOOP2"),
HIVE_METRICS_JSON_FILE_LOCATION("hive.service.metrics.file.location", "/tmp/report.json",
"For metric class org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics JSON_FILE reporter, the location of local JSON metrics file. " +
"This file will get overwritten at every interval."),
HIVE_METRICS_JSON_FILE_INTERVAL("hive.service.metrics.file.frequency", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"For metric class org.apache.hadoop.hive.common.metrics.metrics2.JsonFileMetricsReporter, " +
"the frequency of updating JSON metrics file."),
HIVE_METRICS_HADOOP2_INTERVAL("hive.service.metrics.hadoop2.frequency", "30s",
new TimeValidator(TimeUnit.SECONDS),
"For metric class org.apache.hadoop.hive.common.metrics.metrics2.Metrics2Reporter, " +
"the frequency of updating the HADOOP2 metrics system."),
HIVE_METRICS_HADOOP2_COMPONENT_NAME("hive.service.metrics.hadoop2.component",
"hive",
"Component name to provide to Hadoop2 Metrics system. Ideally 'hivemetastore' for the MetaStore " +
" and and 'hiveserver2' for HiveServer2."
),
HIVE_PERF_LOGGER("hive.exec.perf.logger", "org.apache.hadoop.hive.ql.log.PerfLogger",
"The class responsible for logging client side performance metrics. \n" +
"Must be a subclass of org.apache.hadoop.hive.ql.log.PerfLogger"),
HIVE_START_CLEANUP_SCRATCHDIR("hive.start.cleanup.scratchdir", false,
"To cleanup the Hive scratchdir when starting the Hive Server"),
HIVE_SCRATCH_DIR_LOCK("hive.scratchdir.lock", false,
"To hold a lock file in scratchdir to prevent to be removed by cleardanglingscratchdir"),
HIVE_INSERT_INTO_MULTILEVEL_DIRS("hive.insert.into.multilevel.dirs", false,
"Where to insert into multilevel directories like\n" +
"\"insert directory '/HIVEFT25686/chinna/' from table\""),
HIVE_CTAS_EXTERNAL_TABLES("hive.ctas.external.tables", true,
"whether CTAS for external tables is allowed"),
HIVE_INSERT_INTO_EXTERNAL_TABLES("hive.insert.into.external.tables", true,
"whether insert into external tables is allowed"),
HIVE_TEMPORARY_TABLE_STORAGE(
"hive.exec.temporary.table.storage", "default", new StringSet("memory",
"ssd", "default"), "Define the storage policy for temporary tables." +
"Choices between memory, ssd and default"),
HIVE_QUERY_LIFETIME_HOOKS("hive.query.lifetime.hooks", "",
"A comma separated list of hooks which implement QueryLifeTimeHook. These will be triggered" +
" before/after query compilation and before/after query execution, in the order specified." +
"Implementations of QueryLifeTimeHookWithParseHooks can also be specified in this list. If they are" +
"specified then they will be invoked in the same places as QueryLifeTimeHooks and will be invoked during pre " +
"and post query parsing"),
HIVE_DRIVER_RUN_HOOKS("hive.exec.driver.run.hooks", "",
"A comma separated list of hooks which implement HiveDriverRunHook. Will be run at the beginning " +
"and end of Driver.run, these will be run in the order specified."),
HIVE_DDL_OUTPUT_FORMAT("hive.ddl.output.format", null,
"The data format to use for DDL output. One of \"text\" (for human\n" +
"readable text) or \"json\" (for a json object)."),
HIVE_ENTITY_SEPARATOR("hive.entity.separator", "@",
"Separator used to construct names of tables and partitions. For example, dbname@tablename@partitionname"),
HIVE_CAPTURE_TRANSFORM_ENTITY("hive.entity.capture.transform", false,
"Compiler to capture transform URI referred in the query"),
HIVE_DISPLAY_PARTITION_COLUMNS_SEPARATELY("hive.display.partition.cols.separately", true,
"In older Hive version (0.10 and earlier) no distinction was made between\n" +
"partition columns or non-partition columns while displaying columns in describe\n" +
"table. From 0.12 onwards, they are displayed separately. This flag will let you\n" +
"get old behavior, if desired. See, test-case in patch for HIVE-6689."),
HIVE_LINEAGE_INFO("hive.lineage.hook.info.enabled", false,
"Whether Hive provides lineage information to hooks."),
HIVE_SSL_PROTOCOL_BLACKLIST("hive.ssl.protocol.blacklist", "SSLv2,SSLv3",
"SSL Versions to disable for all Hive Servers"),
HIVE_PRIVILEGE_SYNCHRONIZER("hive.privilege.synchronizer", true,
"Whether to synchronize privileges from external authorizer periodically in HS2"),
HIVE_PRIVILEGE_SYNCHRONIZER_INTERVAL("hive.privilege.synchronizer.interval",
"1800s", new TimeValidator(TimeUnit.SECONDS),
"Interval to synchronize privileges from external authorizer periodically in HS2"),
// HiveServer2 specific configs
HIVE_SERVER2_CLEAR_DANGLING_SCRATCH_DIR("hive.server2.clear.dangling.scratchdir", false,
"Clear dangling scratch dir periodically in HS2"),
HIVE_SERVER2_CLEAR_DANGLING_SCRATCH_DIR_INTERVAL("hive.server2.clear.dangling.scratchdir.interval",
"1800s", new TimeValidator(TimeUnit.SECONDS),
"Interval to clear dangling scratch dir periodically in HS2"),
HIVE_SERVER2_SLEEP_INTERVAL_BETWEEN_START_ATTEMPTS("hive.server2.sleep.interval.between.start.attempts",
"60s", new TimeValidator(TimeUnit.MILLISECONDS, 0l, true, Long.MAX_VALUE, true),
"Amount of time to sleep between HiveServer2 start attempts. Primarily meant for tests"),
HIVE_SERVER2_MAX_START_ATTEMPTS("hive.server2.max.start.attempts", 30L, new RangeValidator(0L, null),
"Number of times HiveServer2 will attempt to start before exiting. The sleep interval between retries" +
" is determined by " + ConfVars.HIVE_SERVER2_SLEEP_INTERVAL_BETWEEN_START_ATTEMPTS.varname +
"\n The default of 30 will keep trying for 30 minutes."),
HIVE_SERVER2_SUPPORT_DYNAMIC_SERVICE_DISCOVERY("hive.server2.support.dynamic.service.discovery", false,
"Whether HiveServer2 supports dynamic service discovery for its clients. " +
"To support this, each instance of HiveServer2 currently uses ZooKeeper to register itself, " +
"when it is brought up. JDBC/ODBC clients should use the ZooKeeper ensemble: " +
"hive.zookeeper.quorum in their connection string."),
HIVE_SERVER2_ZOOKEEPER_NAMESPACE("hive.server2.zookeeper.namespace", "hiveserver2",
"The parent node in ZooKeeper used by HiveServer2 when supporting dynamic service discovery."),
HIVE_SERVER2_ZOOKEEPER_PUBLISH_CONFIGS("hive.server2.zookeeper.publish.configs", true,
"Whether we should publish HiveServer2's configs to ZooKeeper."),
HIVE_SERVER2_OOM_HOOKS("hive.server2.oom.hooks", null,
"A comma separated list of hooks which implement Runnable. Will be run in the order specified \n" +
"before HiveServer2 stops due to OutOfMemoryError."),
// HiveServer2 global init file location
HIVE_SERVER2_GLOBAL_INIT_FILE_LOCATION("hive.server2.global.init.file.location", "${env:HIVE_CONF_DIR}",
"Either the location of a HS2 global init file or a directory containing a .hiverc file. If the \n" +
"property is set, the value must be a valid path to an init file or directory where the init file is located."),
HIVE_SERVER2_TRANSPORT_MODE("hive.server2.transport.mode",
HiveServer2TransportMode.binary.toString(),
new StringSet(HiveServer2TransportMode.binary.toString(),
HiveServer2TransportMode.http.toString(), HiveServer2TransportMode.all.toString()),
"Transport mode of HiveServer2."),
HIVE_SERVER2_THRIFT_BIND_HOST("hive.server2.thrift.bind.host", "",
"Bind host on which to run the HiveServer2 Thrift service."),
HIVE_SERVER2_PARALLEL_COMPILATION("hive.driver.parallel.compilation", false, "Whether to\n" +
"enable parallel compilation of the queries between sessions and within the same session on HiveServer2. The default is false."),
HIVE_SERVER2_PARALLEL_COMPILATION_LIMIT("hive.driver.parallel.compilation.global.limit", -1, "Determines the " +
"degree of parallelism for queries compilation between sessions on HiveServer2. The default is -1."),
HIVE_SERVER2_COMPILE_LOCK_TIMEOUT("hive.server2.compile.lock.timeout", "0s",
new TimeValidator(TimeUnit.SECONDS),
"Number of seconds a request will wait to acquire the compile lock before giving up. " +
"Setting it to 0s disables the timeout."),
HIVE_SERVER2_PARALLEL_OPS_IN_SESSION("hive.server2.parallel.ops.in.session", true,
"Whether to allow several parallel operations (such as SQL statements) in one session."),
HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL("hive.server2.materializedviews.registry.impl", "DEFAULT",
new StringSet("DEFAULT", "DUMMY"),
"The implementation that we should use for the materialized views registry. \n" +
" DEFAULT: Default cache for materialized views\n" +
" DUMMY: Do not cache materialized views and hence forward requests to metastore"),
HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_REFRESH("hive.server2.materializedviews.registry.refresh.period", "1500s",
new TimeValidator(TimeUnit.SECONDS),
"Period, specified in seconds, between successive refreshes of the registry to pull new materializations " +
"from the metastore that may have been created by other HS2 instances."),
// HiveServer2 WebUI
HIVE_SERVER2_WEBUI_BIND_HOST("hive.server2.webui.host", "0.0.0.0", "The host address the HiveServer2 WebUI will listen on"),
HIVE_SERVER2_WEBUI_PORT("hive.server2.webui.port", 10002, "The port the HiveServer2 WebUI will listen on. This can be"
+ "set to 0 or a negative integer to disable the web UI"),
HIVE_SERVER2_WEBUI_MAX_THREADS("hive.server2.webui.max.threads", 50, "The max HiveServer2 WebUI threads"),
HIVE_SERVER2_WEBUI_USE_SSL("hive.server2.webui.use.ssl", false,
"Set this to true for using SSL encryption for HiveServer2 WebUI."),
HIVE_SERVER2_WEBUI_SSL_KEYSTORE_PATH("hive.server2.webui.keystore.path", "",
"SSL certificate keystore location for HiveServer2 WebUI."),
HIVE_SERVER2_WEBUI_SSL_KEYSTORE_PASSWORD("hive.server2.webui.keystore.password", "",
"SSL certificate keystore password for HiveServer2 WebUI."),
HIVE_SERVER2_WEBUI_SSL_KEYSTORE_TYPE("hive.server2.webui.keystore.type", "",
"SSL certificate keystore type for HiveServer2 WebUI."),
HIVE_SERVER2_WEBUI_SSL_KEYMANAGERFACTORY_ALGORITHM("hive.server2.webui.keymanagerfactory.algorithm",
"","SSL certificate key manager factory algorithm for HiveServer2 WebUI."),
HIVE_SERVER2_WEBUI_USE_SPNEGO("hive.server2.webui.use.spnego", false,
"If true, the HiveServer2 WebUI will be secured with SPNEGO. Clients must authenticate with Kerberos."),
HIVE_SERVER2_WEBUI_SPNEGO_KEYTAB("hive.server2.webui.spnego.keytab", "",
"The path to the Kerberos Keytab file containing the HiveServer2 WebUI SPNEGO service principal."),
HIVE_SERVER2_WEBUI_SPNEGO_PRINCIPAL("hive.server2.webui.spnego.principal",
"HTTP/[email protected]", "The HiveServer2 WebUI SPNEGO service principal.\n" +
"The special string _HOST will be replaced automatically with \n" +
"the value of hive.server2.webui.host or the correct host name."),
HIVE_SERVER2_WEBUI_MAX_HISTORIC_QUERIES("hive.server2.webui.max.historic.queries", 25,
"The maximum number of past queries to show in HiverSever2 WebUI."),
HIVE_SERVER2_WEBUI_USE_PAM("hive.server2.webui.use.pam", false,
"If true, the HiveServer2 WebUI will be secured with PAM."),
HIVE_SERVER2_WEBUI_EXPLAIN_OUTPUT("hive.server2.webui.explain.output", false,
"When set to true, the EXPLAIN output for every query is displayed"
+ " in the HS2 WebUI / Drilldown / Query Plan tab.\n"),
HIVE_SERVER2_WEBUI_SHOW_GRAPH("hive.server2.webui.show.graph", false,
"Set this to true to to display query plan as a graph instead of text in the WebUI. " +
"Only works with hive.server2.webui.explain.output set to true."),
HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE("hive.server2.webui.max.graph.size", 25,
"Max number of stages graph can display. If number of stages exceeds this, no query" +
"plan will be shown. Only works when hive.server2.webui.show.graph and " +
"hive.server2.webui.explain.output set to true."),
HIVE_SERVER2_WEBUI_SHOW_STATS("hive.server2.webui.show.stats", false,
"Set this to true to to display statistics for MapReduce tasks in the WebUI. " +
"Only works when hive.server2.webui.show.graph and hive.server2.webui.explain.output " +
"set to true."),
HIVE_SERVER2_WEBUI_ENABLE_CORS("hive.server2.webui.enable.cors", false,
"Whether to enable cross origin requests (CORS)\n"),
HIVE_SERVER2_WEBUI_CORS_ALLOWED_ORIGINS("hive.server2.webui.cors.allowed.origins", "*",
"Comma separated list of origins that are allowed when CORS is enabled.\n"),
HIVE_SERVER2_WEBUI_CORS_ALLOWED_METHODS("hive.server2.webui.cors.allowed.methods", "GET,POST,DELETE,HEAD",
"Comma separated list of http methods that are allowed when CORS is enabled.\n"),
HIVE_SERVER2_WEBUI_CORS_ALLOWED_HEADERS("hive.server2.webui.cors.allowed.headers",
"X-Requested-With,Content-Type,Accept,Origin",
"Comma separated list of http headers that are allowed when CORS is enabled.\n"),
HIVE_SERVER2_WEBUI_XFRAME_ENABLED("hive.server2.webui.xframe.enabled", true,
"Whether to enable xframe\n"),
HIVE_SERVER2_WEBUI_XFRAME_VALUE("hive.server2.webui.xframe.value", "SAMEORIGIN",
"Configuration to allow the user to set the x_frame-options value\n"),
HIVE_SERVER2_SHOW_OPERATION_DRILLDOWN_LINK("hive.server2.show.operation.drilldown.link", false,
"Whether to show the operation's drilldown link to thrift client.\n"),
// Tez session settings
HIVE_SERVER2_ACTIVE_PASSIVE_HA_ENABLE("hive.server2.active.passive.ha.enable", false,
"Whether HiveServer2 Active/Passive High Availability be enabled when Hive Interactive sessions are enabled." +
"This will also require hive.server2.support.dynamic.service.discovery to be enabled."),
HIVE_SERVER2_ACTIVE_PASSIVE_HA_REGISTRY_NAMESPACE("hive.server2.active.passive.ha.registry.namespace",
"hs2ActivePassiveHA",
"When HiveServer2 Active/Passive High Availability is enabled, uses this namespace for registering HS2\n" +
"instances with zookeeper"),
HIVE_SERVER2_TEZ_INTERACTIVE_QUEUE("hive.server2.tez.interactive.queue", "",
"A single YARN queues to use for Hive Interactive sessions. When this is specified,\n" +
"workload management is enabled and used for these sessions."),
HIVE_SERVER2_WM_NAMESPACE("hive.server2.wm.namespace", "default",
"The WM namespace to use when one metastore is used by multiple compute clusters each \n" +
"with their own workload management. The special value 'default' (the default) will \n" +
"also include any resource plans created before the namespaces were introduced."),
HIVE_SERVER2_WM_WORKER_THREADS("hive.server2.wm.worker.threads", 4,
"Number of worker threads to use to perform the synchronous operations with Tez\n" +
"sessions for workload management (e.g. opening, closing, etc.)"),
HIVE_SERVER2_WM_ALLOW_ANY_POOL_VIA_JDBC("hive.server2.wm.allow.any.pool.via.jdbc", false,
"Applies when a user specifies a target WM pool in the JDBC connection string. If\n" +
"false, the user can only specify a pool he is mapped to (e.g. make a choice among\n" +
"multiple group mappings); if true, the user can specify any existing pool."),
HIVE_SERVER2_WM_POOL_METRICS("hive.server2.wm.pool.metrics", true,
"Whether per-pool WM metrics should be enabled."),
HIVE_SERVER2_TEZ_WM_AM_REGISTRY_TIMEOUT("hive.server2.tez.wm.am.registry.timeout", "30s",
new TimeValidator(TimeUnit.SECONDS),
"The timeout for AM registry registration, after which (on attempting to use the\n" +
"session), we kill it and try to get another one."),
HIVE_SERVER2_TEZ_DEFAULT_QUEUES("hive.server2.tez.default.queues", "",
"A list of comma separated values corresponding to YARN queues of the same name.\n" +
"When HiveServer2 is launched in Tez mode, this configuration needs to be set\n" +
"for multiple Tez sessions to run in parallel on the cluster."),
HIVE_SERVER2_TEZ_SESSIONS_PER_DEFAULT_QUEUE("hive.server2.tez.sessions.per.default.queue", 1,
"A positive integer that determines the number of Tez sessions that should be\n" +
"launched on each of the queues specified by \"hive.server2.tez.default.queues\".\n" +
"Determines the parallelism on each queue."),
HIVE_SERVER2_TEZ_INITIALIZE_DEFAULT_SESSIONS("hive.server2.tez.initialize.default.sessions",
true,
"This flag is used in HiveServer2 to enable a user to use HiveServer2 without\n" +
"turning on Tez for HiveServer2. The user could potentially want to run queries\n" +
"over Tez without the pool of sessions."),
HIVE_SERVER2_TEZ_QUEUE_ACCESS_CHECK("hive.server2.tez.queue.access.check", false,
"Whether to check user access to explicitly specified YARN queues. " +
"yarn.resourcemanager.webapp.address must be configured to use this."),
HIVE_SERVER2_TEZ_SESSION_LIFETIME("hive.server2.tez.session.lifetime", "162h",
new TimeValidator(TimeUnit.HOURS),
"The lifetime of the Tez sessions launched by HS2 when default sessions are enabled.\n" +
"Set to 0 to disable session expiration."),
HIVE_SERVER2_TEZ_SESSION_LIFETIME_JITTER("hive.server2.tez.session.lifetime.jitter", "3h",
new TimeValidator(TimeUnit.HOURS),
"The jitter for Tez session lifetime; prevents all the sessions from restarting at once."),
HIVE_SERVER2_TEZ_SESSION_MAX_INIT_THREADS("hive.server2.tez.sessions.init.threads", 16,
"If hive.server2.tez.initialize.default.sessions is enabled, the maximum number of\n" +
"threads to use to initialize the default sessions."),
HIVE_SERVER2_TEZ_SESSION_RESTRICTED_CONFIGS("hive.server2.tez.sessions.restricted.configs", "",
"The configuration settings that cannot be set when submitting jobs to HiveServer2. If\n" +
"any of these are set to values different from those in the server configuration, an\n" +
"exception will be thrown."),
HIVE_SERVER2_TEZ_SESSION_CUSTOM_QUEUE_ALLOWED("hive.server2.tez.sessions.custom.queue.allowed",
"true", new StringSet("true", "false", "ignore"),
"Whether Tez session pool should allow submitting queries to custom queues. The options\n" +
"are true, false (error out), ignore (accept the query but ignore the queue setting)."),
// Operation log configuration
HIVE_SERVER2_LOGGING_OPERATION_ENABLED("hive.server2.logging.operation.enabled", true,
"When true, HS2 will save operation logs and make them available for clients"),
HIVE_SERVER2_LOGGING_OPERATION_LOG_LOCATION("hive.server2.logging.operation.log.location",
"${system:java.io.tmpdir}" + File.separator + "${system:user.name}" + File.separator +
"operation_logs",
"Top level directory where operation logs are stored if logging functionality is enabled"),
HIVE_SERVER2_LOGGING_OPERATION_LEVEL("hive.server2.logging.operation.level", "EXECUTION",
new StringSet("NONE", "EXECUTION", "PERFORMANCE", "VERBOSE"),
"HS2 operation logging mode available to clients to be set at session level.\n" +
"For this to work, hive.server2.logging.operation.enabled should be set to true.\n" +
" NONE: Ignore any logging\n" +
" EXECUTION: Log completion of tasks\n" +
" PERFORMANCE: Execution + Performance logs \n" +
" VERBOSE: All logs" ),
HIVE_SERVER2_OPERATION_LOG_CLEANUP_DELAY("hive.server2.operation.log.cleanup.delay", "300s",
new TimeValidator(TimeUnit.SECONDS), "When a query is cancelled (via kill query, query timeout or triggers),\n" +
" operation logs gets cleaned up after this delay"),
// HS2 connections guard rails
HIVE_SERVER2_LIMIT_CONNECTIONS_PER_USER("hive.server2.limit.connections.per.user", 0,
"Maximum hive server2 connections per user. Any user exceeding this limit will not be allowed to connect. " +
"Default=0 does not enforce limits."),
HIVE_SERVER2_LIMIT_CONNECTIONS_PER_IPADDRESS("hive.server2.limit.connections.per.ipaddress", 0,
"Maximum hive server2 connections per ipaddress. Any ipaddress exceeding this limit will not be allowed " +
"to connect. Default=0 does not enforce limits."),
HIVE_SERVER2_LIMIT_CONNECTIONS_PER_USER_IPADDRESS("hive.server2.limit.connections.per.user.ipaddress", 0,
"Maximum hive server2 connections per user:ipaddress combination. Any user-ipaddress exceeding this limit will " +
"not be allowed to connect. Default=0 does not enforce limits."),
// Enable metric collection for HiveServer2
HIVE_SERVER2_METRICS_ENABLED("hive.server2.metrics.enabled", false, "Enable metrics on the HiveServer2."),
// http (over thrift) transport settings
HIVE_SERVER2_THRIFT_HTTP_PORT("hive.server2.thrift.http.port", 10001,
"Port number of HiveServer2 Thrift interface when hive.server2.transport.mode is 'http'."),
HIVE_SERVER2_THRIFT_HTTP_PATH("hive.server2.thrift.http.path", "cliservice",
"Path component of URL endpoint when in HTTP mode."),
HIVE_SERVER2_THRIFT_MAX_MESSAGE_SIZE("hive.server2.thrift.max.message.size", 100*1024*1024,
"Maximum message size in bytes a HS2 server will accept."),
HIVE_SERVER2_THRIFT_HTTP_MAX_IDLE_TIME("hive.server2.thrift.http.max.idle.time", "1800s",
new TimeValidator(TimeUnit.MILLISECONDS),
"Maximum idle time for a connection on the server when in HTTP mode."),
HIVE_SERVER2_THRIFT_HTTP_WORKER_KEEPALIVE_TIME("hive.server2.thrift.http.worker.keepalive.time", "60s",
new TimeValidator(TimeUnit.SECONDS),
"Keepalive time for an idle http worker thread. When the number of workers exceeds min workers, " +
"excessive threads are killed after this time interval."),
HIVE_SERVER2_THRIFT_HTTP_REQUEST_HEADER_SIZE("hive.server2.thrift.http.request.header.size", 6*1024,
"Request header size in bytes, when using HTTP transport mode. Jetty defaults used."),
HIVE_SERVER2_THRIFT_HTTP_RESPONSE_HEADER_SIZE("hive.server2.thrift.http.response.header.size", 6*1024,
"Response header size in bytes, when using HTTP transport mode. Jetty defaults used."),
HIVE_SERVER2_THRIFT_HTTP_COMPRESSION_ENABLED("hive.server2.thrift.http.compression.enabled", true,
"Enable thrift http compression via Jetty compression support"),
// Cookie based authentication when using HTTP Transport
HIVE_SERVER2_THRIFT_HTTP_COOKIE_AUTH_ENABLED("hive.server2.thrift.http.cookie.auth.enabled", true,
"When true, HiveServer2 in HTTP transport mode, will use cookie based authentication mechanism."),
HIVE_SERVER2_THRIFT_HTTP_COOKIE_MAX_AGE("hive.server2.thrift.http.cookie.max.age", "86400s",
new TimeValidator(TimeUnit.SECONDS),
"Maximum age in seconds for server side cookie used by HS2 in HTTP mode."),
HIVE_SERVER2_THRIFT_HTTP_COOKIE_DOMAIN("hive.server2.thrift.http.cookie.domain", null,
"Domain for the HS2 generated cookies"),
HIVE_SERVER2_THRIFT_HTTP_COOKIE_PATH("hive.server2.thrift.http.cookie.path", null,
"Path for the HS2 generated cookies"),
@Deprecated
HIVE_SERVER2_THRIFT_HTTP_COOKIE_IS_SECURE("hive.server2.thrift.http.cookie.is.secure", true,
"Deprecated: Secure attribute of the HS2 generated cookie (this is automatically enabled for SSL enabled HiveServer2)."),
HIVE_SERVER2_THRIFT_HTTP_COOKIE_IS_HTTPONLY("hive.server2.thrift.http.cookie.is.httponly", true,
"HttpOnly attribute of the HS2 generated cookie."),
// binary transport settings
HIVE_SERVER2_THRIFT_PORT("hive.server2.thrift.port", 10000,
"Port number of HiveServer2 Thrift interface when hive.server2.transport.mode is 'binary'."),
HIVE_SERVER2_THRIFT_SASL_QOP("hive.server2.thrift.sasl.qop", "auth",
new StringSet("auth", "auth-int", "auth-conf"),
"Sasl QOP value; set it to one of following values to enable higher levels of\n" +
"protection for HiveServer2 communication with clients.\n" +
"Setting hadoop.rpc.protection to a higher level than HiveServer2 does not\n" +
"make sense in most situations. HiveServer2 ignores hadoop.rpc.protection in favor\n" +
"of hive.server2.thrift.sasl.qop.\n" +
" \"auth\" - authentication only (default)\n" +
" \"auth-int\" - authentication plus integrity protection\n" +
" \"auth-conf\" - authentication plus integrity and confidentiality protection\n" +
"This is applicable only if HiveServer2 is configured to use Kerberos authentication."),
HIVE_SERVER2_THRIFT_MIN_WORKER_THREADS("hive.server2.thrift.min.worker.threads", 5,
"Minimum number of Thrift worker threads"),
HIVE_SERVER2_THRIFT_MAX_WORKER_THREADS("hive.server2.thrift.max.worker.threads", 500,
"Maximum number of Thrift worker threads"),
HIVE_SERVER2_THRIFT_LOGIN_BEBACKOFF_SLOT_LENGTH(
"hive.server2.thrift.exponential.backoff.slot.length", "100ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Binary exponential backoff slot time for Thrift clients during login to HiveServer2,\n" +
"for retries until hitting Thrift client timeout"),
HIVE_SERVER2_THRIFT_LOGIN_TIMEOUT("hive.server2.thrift.login.timeout", "20s",
new TimeValidator(TimeUnit.SECONDS), "Timeout for Thrift clients during login to HiveServer2"),
HIVE_SERVER2_THRIFT_WORKER_KEEPALIVE_TIME("hive.server2.thrift.worker.keepalive.time", "60s",
new TimeValidator(TimeUnit.SECONDS),
"Keepalive time (in seconds) for an idle worker thread. When the number of workers exceeds min workers, " +
"excessive threads are killed after this time interval."),
// Configuration for async thread pool in SessionManager
HIVE_SERVER2_ASYNC_EXEC_THREADS("hive.server2.async.exec.threads", 100,
"Number of threads in the async thread pool for HiveServer2"),
HIVE_SERVER2_ASYNC_EXEC_SHUTDOWN_TIMEOUT("hive.server2.async.exec.shutdown.timeout", "10s",
new TimeValidator(TimeUnit.SECONDS),
"How long HiveServer2 shutdown will wait for async threads to terminate."),
HIVE_SERVER2_ASYNC_EXEC_WAIT_QUEUE_SIZE("hive.server2.async.exec.wait.queue.size", 100,
"Size of the wait queue for async thread pool in HiveServer2.\n" +
"After hitting this limit, the async thread pool will reject new requests."),
HIVE_SERVER2_ASYNC_EXEC_KEEPALIVE_TIME("hive.server2.async.exec.keepalive.time", "10s",
new TimeValidator(TimeUnit.SECONDS),
"Time that an idle HiveServer2 async thread (from the thread pool) will wait for a new task\n" +
"to arrive before terminating"),
HIVE_SERVER2_ASYNC_EXEC_ASYNC_COMPILE("hive.server2.async.exec.async.compile", false,
"Whether to enable compiling async query asynchronously. If enabled, it is unknown if the query will have any resultset before compilation completed."),
HIVE_SERVER2_LONG_POLLING_TIMEOUT("hive.server2.long.polling.timeout", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Time that HiveServer2 will wait before responding to asynchronous calls that use long polling"),
HIVE_SESSION_IMPL_CLASSNAME("hive.session.impl.classname", null, "Classname for custom implementation of hive session"),
HIVE_SESSION_IMPL_WITH_UGI_CLASSNAME("hive.session.impl.withugi.classname", null, "Classname for custom implementation of hive session with UGI"),
// HiveServer2 auth configuration
HIVE_SERVER2_AUTHENTICATION("hive.server2.authentication", "NONE",
new StringSet("NOSASL", "NONE", "LDAP", "KERBEROS", "PAM", "CUSTOM"),
"Client authentication types.\n" +
" NONE: no authentication check\n" +
" LDAP: LDAP/AD based authentication\n" +
" KERBEROS: Kerberos/GSSAPI authentication\n" +
" CUSTOM: Custom authentication provider\n" +
" (Use with property hive.server2.custom.authentication.class)\n" +
" PAM: Pluggable authentication module\n" +
" NOSASL: Raw transport"),
HIVE_SERVER2_TRUSTED_DOMAIN("hive.server2.trusted.domain", "",
"Specifies the host or a domain to trust connections from. Authentication is skipped " +
"for any connection coming from a host whose hostname ends with the value of this" +
" property. If authentication is expected to be skipped for connections from " +
"only a given host, fully qualified hostname of that host should be specified. By default" +
" it is empty, which means that all the connections to HiveServer2 are authenticated. " +
"When it is non-empty, the client has to provide a Hive user name. Any password, if " +
"provided, will not be used when authentication is skipped."),
HIVE_SERVER2_TRUSTED_DOMAIN_USE_XFF_HEADER("hive.server2.trusted.domain.use.xff.header", false,
"When trusted domain authentication is enabled, the clients connecting to the HS2 could pass" +
"through many layers of proxy. Some proxies append its own ip address to 'X-Forwarded-For' header" +
"before passing on the request to another proxy or HS2. Some proxies also connect on behalf of client" +
"and may create a separate connection to HS2 without binding using client IP. For such environments, instead" +
"of looking at client IP from the request, if this config is set and if 'X-Forwarded-For' is present," +
"trusted domain authentication will use left most ip address from X-Forwarded-For header."),
HIVE_SERVER2_ALLOW_USER_SUBSTITUTION("hive.server2.allow.user.substitution", true,
"Allow alternate user to be specified as part of HiveServer2 open connection request."),
HIVE_SERVER2_KERBEROS_KEYTAB("hive.server2.authentication.kerberos.keytab", "",
"Kerberos keytab file for server principal"),
HIVE_SERVER2_KERBEROS_PRINCIPAL("hive.server2.authentication.kerberos.principal", "",
"Kerberos server principal"),
HIVE_SERVER2_CLIENT_KERBEROS_PRINCIPAL("hive.server2.authentication.client.kerberos.principal", "",
"Kerberos principal used by the HA hive_server2s."),
HIVE_SERVER2_SPNEGO_KEYTAB("hive.server2.authentication.spnego.keytab", "",
"keytab file for SPNego principal, optional,\n" +
"typical value would look like /etc/security/keytabs/spnego.service.keytab,\n" +
"This keytab would be used by HiveServer2 when Kerberos security is enabled and \n" +
"HTTP transport mode is used.\n" +
"This needs to be set only if SPNEGO is to be used in authentication.\n" +
"SPNego authentication would be honored only if valid\n" +
" hive.server2.authentication.spnego.principal\n" +
"and\n" +
" hive.server2.authentication.spnego.keytab\n" +
"are specified."),
HIVE_SERVER2_SPNEGO_PRINCIPAL("hive.server2.authentication.spnego.principal", "",
"SPNego service principal, optional,\n" +
"typical value would look like HTTP/[email protected]\n" +
"SPNego service principal would be used by HiveServer2 when Kerberos security is enabled\n" +
"and HTTP transport mode is used.\n" +
"This needs to be set only if SPNEGO is to be used in authentication."),
HIVE_SERVER2_PLAIN_LDAP_URL("hive.server2.authentication.ldap.url", null,
"LDAP connection URL(s),\n" +
"this value could contain URLs to multiple LDAP servers instances for HA,\n" +
"each LDAP URL is separated by a SPACE character. URLs are used in the \n" +
" order specified until a connection is successful."),
HIVE_SERVER2_PLAIN_LDAP_BASEDN("hive.server2.authentication.ldap.baseDN", null, "LDAP base DN"),
HIVE_SERVER2_PLAIN_LDAP_DOMAIN("hive.server2.authentication.ldap.Domain", null, ""),
HIVE_SERVER2_PLAIN_LDAP_GROUPDNPATTERN("hive.server2.authentication.ldap.groupDNPattern", null,
"COLON-separated list of patterns to use to find DNs for group entities in this directory.\n" +
"Use %s where the actual group name is to be substituted for.\n" +
"For example: CN=%s,CN=Groups,DC=subdomain,DC=domain,DC=com."),
HIVE_SERVER2_PLAIN_LDAP_GROUPFILTER("hive.server2.authentication.ldap.groupFilter", null,
"COMMA-separated list of LDAP Group names (short name not full DNs).\n" +
"For example: HiveAdmins,HadoopAdmins,Administrators"),
HIVE_SERVER2_PLAIN_LDAP_USERDNPATTERN("hive.server2.authentication.ldap.userDNPattern", null,
"COLON-separated list of patterns to use to find DNs for users in this directory.\n" +
"Use %s where the actual group name is to be substituted for.\n" +
"For example: CN=%s,CN=Users,DC=subdomain,DC=domain,DC=com."),
HIVE_SERVER2_PLAIN_LDAP_USERFILTER("hive.server2.authentication.ldap.userFilter", null,
"COMMA-separated list of LDAP usernames (just short names, not full DNs).\n" +
"For example: hiveuser,impalauser,hiveadmin,hadoopadmin"),
HIVE_SERVER2_PLAIN_LDAP_GUIDKEY("hive.server2.authentication.ldap.guidKey", "uid",
"LDAP attribute name whose values are unique in this LDAP server.\n" +
"For example: uid or CN."),
HIVE_SERVER2_PLAIN_LDAP_GROUPMEMBERSHIP_KEY("hive.server2.authentication.ldap.groupMembershipKey", "member",
"LDAP attribute name on the group object that contains the list of distinguished names\n" +
"for the user, group, and contact objects that are members of the group.\n" +
"For example: member, uniqueMember or memberUid"),
HIVE_SERVER2_PLAIN_LDAP_USERMEMBERSHIP_KEY(HIVE_SERVER2_AUTHENTICATION_LDAP_USERMEMBERSHIPKEY_NAME, null,
"LDAP attribute name on the user object that contains groups of which the user is\n" +
"a direct member, except for the primary group, which is represented by the\n" +
"primaryGroupId.\n" +
"For example: memberOf"),
HIVE_SERVER2_PLAIN_LDAP_GROUPCLASS_KEY("hive.server2.authentication.ldap.groupClassKey", "groupOfNames",
"LDAP attribute name on the group entry that is to be used in LDAP group searches.\n" +
"For example: group, groupOfNames or groupOfUniqueNames."),
HIVE_SERVER2_PLAIN_LDAP_CUSTOMLDAPQUERY("hive.server2.authentication.ldap.customLDAPQuery", null,
"A full LDAP query that LDAP Atn provider uses to execute against LDAP Server.\n" +
"If this query returns a null resultset, the LDAP Provider fails the Authentication\n" +
"request, succeeds if the user is part of the resultset." +
"For example: (&(objectClass=group)(objectClass=top)(instanceType=4)(cn=Domain*)) \n" +
"(&(objectClass=person)(|(sAMAccountName=admin)(|(memberOf=CN=Domain Admins,CN=Users,DC=domain,DC=com)" +
"(memberOf=CN=Administrators,CN=Builtin,DC=domain,DC=com))))"),
HIVE_SERVER2_PLAIN_LDAP_BIND_USER("hive.server2.authentication.ldap.binddn", null,
"The user with which to bind to the LDAP server, and search for the full domain name " +
"of the user being authenticated.\n" +
"This should be the full domain name of the user, and should have search access across all " +
"users in the LDAP tree.\n" +
"If not specified, then the user being authenticated will be used as the bind user.\n" +
"For example: CN=bindUser,CN=Users,DC=subdomain,DC=domain,DC=com"),
HIVE_SERVER2_PLAIN_LDAP_BIND_PASSWORD("hive.server2.authentication.ldap.bindpw", null,
"The password for the bind user, to be used to search for the full name of the user being authenticated.\n" +
"If the username is specified, this parameter must also be specified."),
HIVE_SERVER2_CUSTOM_AUTHENTICATION_CLASS("hive.server2.custom.authentication.class", null,
"Custom authentication class. Used when property\n" +
"'hive.server2.authentication' is set to 'CUSTOM'. Provided class\n" +
"must be a proper implementation of the interface\n" +
"org.apache.hive.service.auth.PasswdAuthenticationProvider. HiveServer2\n" +
"will call its Authenticate(user, passed) method to authenticate requests.\n" +
"The implementation may optionally implement Hadoop's\n" +
"org.apache.hadoop.conf.Configurable class to grab Hive's Configuration object."),
HIVE_SERVER2_PAM_SERVICES("hive.server2.authentication.pam.services", null,
"List of the underlying pam services that should be used when auth type is PAM\n" +
"A file with the same name must exist in /etc/pam.d"),
HIVE_SERVER2_ENABLE_DOAS("hive.server2.enable.doAs", true,
"Setting this property to true will have HiveServer2 execute\n" +
"Hive operations as the user making the calls to it."),
HIVE_DISTCP_DOAS_USER("hive.distcp.privileged.doAs","hive",
"This property allows privileged distcp executions done by hive\n" +
"to run as this user."),
HIVE_SERVER2_TABLE_TYPE_MAPPING("hive.server2.table.type.mapping", "CLASSIC", new StringSet("CLASSIC", "HIVE"),
"This setting reflects how HiveServer2 will report the table types for JDBC and other\n" +
"client implementations that retrieve the available tables and supported table types\n" +
" HIVE : Exposes Hive's native table types like MANAGED_TABLE, EXTERNAL_TABLE, VIRTUAL_VIEW\n" +
" CLASSIC : More generic types like TABLE and VIEW"),
HIVE_SERVER2_SESSION_HOOK("hive.server2.session.hook", "", ""),
// SSL settings
HIVE_SERVER2_USE_SSL("hive.server2.use.SSL", false,
"Set this to true for using SSL encryption in HiveServer2."),
HIVE_SERVER2_SSL_KEYSTORE_PATH("hive.server2.keystore.path", "",
"SSL certificate keystore location."),
HIVE_SERVER2_SSL_KEYSTORE_PASSWORD("hive.server2.keystore.password", "",
"SSL certificate keystore password."),
HIVE_SERVER2_SSL_KEYSTORE_TYPE("hive.server2.keystore.type", "",
"SSL certificate keystore type."),
HIVE_SERVER2_SSL_KEYMANAGERFACTORY_ALGORITHM("hive.server2.keymanagerfactory.algorithm", "",
"SSL certificate keystore algorithm."),
HIVE_SERVER2_BUILTIN_UDF_WHITELIST("hive.server2.builtin.udf.whitelist", "",
"Comma separated list of builtin udf names allowed in queries.\n" +
"An empty whitelist allows all builtin udfs to be executed. " +
" The udf black list takes precedence over udf white list"),
HIVE_SERVER2_BUILTIN_UDF_BLACKLIST("hive.server2.builtin.udf.blacklist", "",
"Comma separated list of udfs names. These udfs will not be allowed in queries." +
" The udf black list takes precedence over udf white list"),
HIVE_ALLOW_UDF_LOAD_ON_DEMAND("hive.allow.udf.load.on.demand", false,
"Whether enable loading UDFs from metastore on demand; this is mostly relevant for\n" +
"HS2 and was the default behavior before Hive 1.2. Off by default."),
HIVE_SERVER2_SESSION_CHECK_INTERVAL("hive.server2.session.check.interval", "15m",
new TimeValidator(TimeUnit.MILLISECONDS, 3000l, true, null, false),
"The check interval for session/operation timeout, which can be disabled by setting to zero or negative value."),
HIVE_SERVER2_CLOSE_SESSION_ON_DISCONNECT("hive.server2.close.session.on.disconnect", true,
"Session will be closed when connection is closed. Set this to false to have session outlive its parent connection."),
HIVE_SERVER2_IDLE_SESSION_TIMEOUT("hive.server2.idle.session.timeout", "4h",
new TimeValidator(TimeUnit.MILLISECONDS),
"Session will be closed when it's not accessed for this duration, which can be disabled by setting to zero or negative value."),
HIVE_SERVER2_IDLE_OPERATION_TIMEOUT("hive.server2.idle.operation.timeout", "2h",
new TimeValidator(TimeUnit.MILLISECONDS),
"Operation will be closed when it's not accessed for this duration of time, which can be disabled by setting to zero value.\n" +
" With positive value, it's checked for operations in terminal state only (FINISHED, CANCELED, CLOSED, ERROR).\n" +
" With negative value, it's checked for all of the operations regardless of state."),
HIVE_SERVER2_IDLE_SESSION_CHECK_OPERATION("hive.server2.idle.session.check.operation", true,
"Session will be considered to be idle only if there is no activity, and there is no pending operation.\n" +
" This setting takes effect only if session idle timeout (hive.server2.idle.session.timeout) and checking\n" +
"(hive.server2.session.check.interval) are enabled."),
HIVE_SERVER2_THRIFT_CLIENT_RETRY_LIMIT("hive.server2.thrift.client.retry.limit", 1,"Number of retries upon " +
"failure of Thrift HiveServer2 calls"),
HIVE_SERVER2_THRIFT_CLIENT_CONNECTION_RETRY_LIMIT("hive.server2.thrift.client.connect.retry.limit", 1,"Number of " +
"retries while opening a connection to HiveServe2"),
HIVE_SERVER2_THRIFT_CLIENT_RETRY_DELAY_SECONDS("hive.server2.thrift.client.retry.delay.seconds", "1s",
new TimeValidator(TimeUnit.SECONDS), "Number of seconds for the HiveServer2 thrift client to wait between " +
"consecutive connection attempts. Also specifies the time to wait between retrying thrift calls upon failures"),
HIVE_SERVER2_THRIFT_CLIENT_USER("hive.server2.thrift.client.user", "anonymous","Username to use against thrift" +
" client"),
HIVE_SERVER2_THRIFT_CLIENT_PASSWORD("hive.server2.thrift.client.password", "anonymous","Password to use against " +
"thrift client"),
// ResultSet serialization settings
HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS("hive.server2.thrift.resultset.serialize.in.tasks", false,
"Whether we should serialize the Thrift structures used in JDBC ResultSet RPC in task nodes.\n " +
"We use SequenceFile and ThriftJDBCBinarySerDe to read and write the final results if this is true."),
// TODO: Make use of this config to configure fetch size
HIVE_SERVER2_THRIFT_RESULTSET_MAX_FETCH_SIZE("hive.server2.thrift.resultset.max.fetch.size",
10000, "Max number of rows sent in one Fetch RPC call by the server to the client."),
HIVE_SERVER2_THRIFT_RESULTSET_DEFAULT_FETCH_SIZE("hive.server2.thrift.resultset.default.fetch.size", 1000,
"The number of rows sent in one Fetch RPC call by the server to the client, if not\n" +
"specified by the client."),
HIVE_SERVER2_XSRF_FILTER_ENABLED("hive.server2.xsrf.filter.enabled",false,
"If enabled, HiveServer2 will block any requests made to it over http " +
"if an X-XSRF-HEADER header is not present"),
HIVE_SECURITY_COMMAND_WHITELIST("hive.security.command.whitelist",
"set,reset,dfs,add,list,delete,reload,compile,llap",
"Comma separated list of non-SQL Hive commands users are authorized to execute"),
HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH("hive.server2.job.credential.provider.path", "",
"If set, this configuration property should provide a comma-separated list of URLs that indicates the type and " +
"location of providers to be used by hadoop credential provider API. It provides HiveServer2 the ability to provide job-specific " +
"credential providers for jobs run using MR and Spark execution engines. This functionality has not been tested against Tez."),
HIVE_MOVE_FILES_THREAD_COUNT("hive.mv.files.thread", 15, new SizeValidator(0L, true, 1024L, true), "Number of threads"
+ " used to move files in move task. Set it to 0 to disable multi-threaded file moves. This parameter is also used by"
+ " MSCK to check tables."),
HIVE_LOAD_DYNAMIC_PARTITIONS_THREAD_COUNT("hive.load.dynamic.partitions.thread", 15,
new SizeValidator(1L, true, 1024L, true),
"Number of threads used to load dynamic partitions."),
// If this is set all move tasks at the end of a multi-insert query will only begin once all
// outputs are ready
HIVE_MULTI_INSERT_MOVE_TASKS_SHARE_DEPENDENCIES(
"hive.multi.insert.move.tasks.share.dependencies", false,
"If this is set all move tasks for tables/partitions (not directories) at the end of a\n" +
"multi-insert query will only begin once the dependencies for all these move tasks have been\n" +
"met.\n" +
"Advantages: If concurrency is enabled, the locks will only be released once the query has\n" +
" finished, so with this config enabled, the time when the table/partition is\n" +
" generated will be much closer to when the lock on it is released.\n" +
"Disadvantages: If concurrency is not enabled, with this disabled, the tables/partitions which\n" +
" are produced by this query and finish earlier will be available for querying\n" +
" much earlier. Since the locks are only released once the query finishes, this\n" +
" does not apply if concurrency is enabled."),
HIVE_HDFS_ENCRYPTION_SHIM_CACHE_ON("hive.hdfs.encryption.shim.cache.on", true,
"Hive keeps a cache of hdfs encryption shims in SessionState. Each encryption shim in the cache stores a "
+ "FileSystem object. If one of these FileSystems is closed anywhere in the system and HDFS config"
+ "fs.hdfs.impl.disable.cache is false, its encryption shim in the cache will be unusable. "
+ "If this is config set to false, then the encryption shim cache will be disabled."),
HIVE_INFER_BUCKET_SORT("hive.exec.infer.bucket.sort", false,
"If this is set, when writing partitions, the metadata will include the bucketing/sorting\n" +
"properties with which the data was written if any (this will not overwrite the metadata\n" +
"inherited from the table if the table is bucketed/sorted)"),
HIVE_INFER_BUCKET_SORT_NUM_BUCKETS_POWER_TWO(
"hive.exec.infer.bucket.sort.num.buckets.power.two", false,
"If this is set, when setting the number of reducers for the map reduce task which writes the\n" +
"final output files, it will choose a number which is a power of two, unless the user specifies\n" +
"the number of reducers to use using mapred.reduce.tasks. The number of reducers\n" +
"may be set to a power of two, only to be followed by a merge task meaning preventing\n" +
"anything from being inferred.\n" +
"With hive.exec.infer.bucket.sort set to true:\n" +
"Advantages: If this is not set, the number of buckets for partitions will seem arbitrary,\n" +
" which means that the number of mappers used for optimized joins, for example, will\n" +
" be very low. With this set, since the number of buckets used for any partition is\n" +
" a power of two, the number of mappers used for optimized joins will be the least\n" +
" number of buckets used by any partition being joined.\n" +
"Disadvantages: This may mean a much larger or much smaller number of reducers being used in the\n" +
" final map reduce job, e.g. if a job was originally going to take 257 reducers,\n" +
" it will now take 512 reducers, similarly if the max number of reducers is 511,\n" +
" and a job was going to use this many, it will now use 256 reducers."),
HIVEOPTLISTBUCKETING("hive.optimize.listbucketing", false,
"Enable list bucketing optimizer. Default value is false so that we disable it by default."),
// Allow TCP Keep alive socket option for for HiveServer or a maximum timeout for the socket.
SERVER_READ_SOCKET_TIMEOUT("hive.server.read.socket.timeout", "10s",
new TimeValidator(TimeUnit.SECONDS),
"Timeout for the HiveServer to close the connection if no response from the client. By default, 10 seconds."),
SERVER_TCP_KEEP_ALIVE("hive.server.tcp.keepalive", true,
"Whether to enable TCP keepalive for the Hive Server. Keepalive will prevent accumulation of half-open connections."),
HIVE_DECODE_PARTITION_NAME("hive.decode.partition.name", false,
"Whether to show the unquoted partition names in query results."),
HIVE_EXECUTION_ENGINE("hive.execution.engine", "mr", new StringSet(true, "mr", "tez", "spark"),
"Chooses execution engine. Options are: mr (Map reduce, default), tez, spark. While MR\n" +
"remains the default engine for historical reasons, it is itself a historical engine\n" +
"and is deprecated in Hive 2 line. It may be removed without further warning."),
HIVE_EXECUTION_MODE("hive.execution.mode", "container", new StringSet("container", "llap"),
"Chooses whether query fragments will run in container or in llap"),
HIVE_JAR_DIRECTORY("hive.jar.directory", null,
"This is the location hive in tez mode will look for to find a site wide \n" +
"installed hive instance."),
HIVE_USER_INSTALL_DIR("hive.user.install.directory", "/user/",
"If hive (in tez mode only) cannot find a usable hive jar in \"hive.jar.directory\", \n" +
"it will upload the hive jar to \"hive.user.install.directory/user.name\"\n" +
"and use it to run queries."),
// Vectorization enabled
HIVE_VECTORIZATION_ENABLED("hive.vectorized.execution.enabled", true,
"This flag should be set to true to enable vectorized mode of query execution.\n" +
"The default value is true to reflect that our most expected Hive deployment will be using vectorization."),
HIVE_VECTORIZATION_REDUCE_ENABLED("hive.vectorized.execution.reduce.enabled", true,
"This flag should be set to true to enable vectorized mode of the reduce-side of query execution.\n" +
"The default value is true."),
HIVE_VECTORIZATION_REDUCE_GROUPBY_ENABLED("hive.vectorized.execution.reduce.groupby.enabled", true,
"This flag should be set to true to enable vectorized mode of the reduce-side GROUP BY query execution.\n" +
"The default value is true."),
HIVE_VECTORIZATION_MAPJOIN_NATIVE_ENABLED("hive.vectorized.execution.mapjoin.native.enabled", true,
"This flag should be set to true to enable native (i.e. non-pass through) vectorization\n" +
"of queries using MapJoin.\n" +
"The default value is true."),
HIVE_VECTORIZATION_MAPJOIN_NATIVE_MULTIKEY_ONLY_ENABLED("hive.vectorized.execution.mapjoin.native.multikey.only.enabled", false,
"This flag should be set to true to restrict use of native vector map join hash tables to\n" +
"the MultiKey in queries using MapJoin.\n" +
"The default value is false."),
HIVE_VECTORIZATION_MAPJOIN_NATIVE_MINMAX_ENABLED("hive.vectorized.execution.mapjoin.minmax.enabled", false,
"This flag should be set to true to enable vector map join hash tables to\n" +
"use max / max filtering for integer join queries using MapJoin.\n" +
"The default value is false."),
HIVE_VECTORIZATION_MAPJOIN_NATIVE_OVERFLOW_REPEATED_THRESHOLD("hive.vectorized.execution.mapjoin.overflow.repeated.threshold", -1,
"The number of small table rows for a match in vector map join hash tables\n" +
"where we use the repeated field optimization in overflow vectorized row batch for join queries using MapJoin.\n" +
"A value of -1 means do use the join result optimization. Otherwise, threshold value can be 0 to maximum integer."),
HIVE_VECTORIZATION_MAPJOIN_NATIVE_FAST_HASHTABLE_ENABLED("hive.vectorized.execution.mapjoin.native.fast.hashtable.enabled", false,
"This flag should be set to true to enable use of native fast vector map join hash tables in\n" +
"queries using MapJoin.\n" +
"The default value is false."),
HIVE_VECTORIZATION_GROUPBY_CHECKINTERVAL("hive.vectorized.groupby.checkinterval", 100000,
"Number of entries added to the group by aggregation hash before a recomputation of average entry size is performed."),
HIVE_VECTORIZATION_GROUPBY_MAXENTRIES("hive.vectorized.groupby.maxentries", 1000000,
"Max number of entries in the vector group by aggregation hashtables. \n" +
"Exceeding this will trigger a flush irrelevant of memory pressure condition."),
HIVE_VECTORIZATION_GROUPBY_FLUSH_PERCENT("hive.vectorized.groupby.flush.percent", (float) 0.1,
"Percent of entries in the group by aggregation hash flushed when the memory threshold is exceeded."),
HIVE_VECTORIZATION_REDUCESINK_NEW_ENABLED("hive.vectorized.execution.reducesink.new.enabled", true,
"This flag should be set to true to enable the new vectorization\n" +
"of queries using ReduceSink.\ni" +
"The default value is true."),
HIVE_VECTORIZATION_USE_VECTORIZED_INPUT_FILE_FORMAT("hive.vectorized.use.vectorized.input.format", true,
"This flag should be set to true to enable vectorizing with vectorized input file format capable SerDe.\n" +
"The default value is true."),
HIVE_VECTORIZATION_VECTORIZED_INPUT_FILE_FORMAT_EXCLUDES("hive.vectorized.input.format.excludes","",
"This configuration should be set to fully described input format class names for which \n"
+ " vectorized input format should not be used for vectorized execution."),
HIVE_VECTORIZATION_USE_VECTOR_DESERIALIZE("hive.vectorized.use.vector.serde.deserialize", true,
"This flag should be set to true to enable vectorizing rows using vector deserialize.\n" +
"The default value is true."),
HIVE_VECTORIZATION_USE_ROW_DESERIALIZE("hive.vectorized.use.row.serde.deserialize", true,
"This flag should be set to true to enable vectorizing using row deserialize.\n" +
"The default value is false."),
HIVE_VECTORIZATION_ROW_DESERIALIZE_INPUTFORMAT_EXCLUDES(
"hive.vectorized.row.serde.inputformat.excludes",
"org.apache.parquet.hadoop.ParquetInputFormat,org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat",
"The input formats not supported by row deserialize vectorization."),
HIVE_VECTOR_ADAPTOR_USAGE_MODE("hive.vectorized.adaptor.usage.mode", "all", new StringSet("none", "chosen", "all"),
"Specifies the extent to which the VectorUDFAdaptor will be used for UDFs that do not have a corresponding vectorized class.\n" +
"0. none : disable any usage of VectorUDFAdaptor\n" +
"1. chosen : use VectorUDFAdaptor for a small set of UDFs that were chosen for good performance\n" +
"2. all : use VectorUDFAdaptor for all UDFs"
),
HIVE_TEST_VECTOR_ADAPTOR_OVERRIDE("hive.test.vectorized.adaptor.override", false,
"internal use only, used to force always using the VectorUDFAdaptor.\n" +
"The default is false, of course",
true),
HIVE_VECTORIZATION_PTF_ENABLED("hive.vectorized.execution.ptf.enabled", true,
"This flag should be set to true to enable vectorized mode of the PTF of query execution.\n" +
"The default value is true."),
HIVE_VECTORIZATION_PTF_MAX_MEMORY_BUFFERING_BATCH_COUNT("hive.vectorized.ptf.max.memory.buffering.batch.count", 25,
"Maximum number of vectorized row batches to buffer in memory for PTF\n" +
"The default value is 25"),
HIVE_VECTORIZATION_TESTING_REDUCER_BATCH_SIZE("hive.vectorized.testing.reducer.batch.size", -1,
"internal use only, used for creating small group key vectorized row batches to exercise more logic\n" +
"The default value is -1 which means don't restrict for testing",
true),
HIVE_VECTORIZATION_TESTING_REUSE_SCRATCH_COLUMNS("hive.vectorized.reuse.scratch.columns", true,
"internal use only. Disable this to debug scratch column state issues",
true),
HIVE_VECTORIZATION_COMPLEX_TYPES_ENABLED("hive.vectorized.complex.types.enabled", true,
"This flag should be set to true to enable vectorization\n" +
"of expressions with complex types.\n" +
"The default value is true."),
HIVE_VECTORIZATION_GROUPBY_COMPLEX_TYPES_ENABLED("hive.vectorized.groupby.complex.types.enabled", true,
"This flag should be set to true to enable group by vectorization\n" +
"of aggregations that use complex types.\n" +
"For example, AVG uses a complex type (STRUCT) for partial aggregation results" +
"The default value is true."),
HIVE_VECTORIZATION_ROW_IDENTIFIER_ENABLED("hive.vectorized.row.identifier.enabled", true,
"This flag should be set to true to enable vectorization of ROW__ID."),
HIVE_VECTORIZATION_USE_CHECKED_EXPRESSIONS("hive.vectorized.use.checked.expressions", false,
"This flag should be set to true to use overflow checked vector expressions when available.\n" +
"For example, arithmetic expressions which can overflow the output data type can be evaluated using\n" +
" checked vector expressions so that they produce same result as non-vectorized evaluation."),
HIVE_VECTORIZED_ADAPTOR_SUPPRESS_EVALUATE_EXCEPTIONS(
"hive.vectorized.adaptor.suppress.evaluate.exceptions", false,
"This flag should be set to true to suppress HiveException from the generic UDF function\n" +
"evaluate call and turn them into NULLs. Assume, by default, this is not needed"),
HIVE_VECTORIZED_INPUT_FORMAT_SUPPORTS_ENABLED(
"hive.vectorized.input.format.supports.enabled",
"decimal_64",
"Which vectorized input format support features are enabled for vectorization.\n" +
"That is, if a VectorizedInputFormat input format does support \"decimal_64\" for example\n" +
"this variable must enable that to be used in vectorization"),
HIVE_VECTORIZED_IF_EXPR_MODE("hive.vectorized.if.expr.mode", "better", new StringSet("adaptor", "good", "better"),
"Specifies the extent to which SQL IF statements will be vectorized.\n" +
"0. adaptor: only use the VectorUDFAdaptor to vectorize IF statements\n" +
"1. good : use regular vectorized IF expression classes that get good performance\n" +
"2. better : use vectorized IF expression classes that conditionally execute THEN/ELSE\n" +
" expressions for better performance.\n"),
HIVE_TEST_VECTORIZATION_ENABLED_OVERRIDE("hive.test.vectorized.execution.enabled.override",
"none", new StringSet("none", "enable", "disable"),
"internal use only, used to override the hive.vectorized.execution.enabled setting and\n" +
"turn off vectorization. The default is false, of course",
true),
HIVE_TEST_VECTORIZATION_SUPPRESS_EXPLAIN_EXECUTION_MODE(
"hive.test.vectorization.suppress.explain.execution.mode", false,
"internal use only, used to suppress \"Execution mode: vectorized\" EXPLAIN display.\n" +
"The default is false, of course",
true),
HIVE_TEST_VECTORIZER_SUPPRESS_FATAL_EXCEPTIONS(
"hive.test.vectorizer.suppress.fatal.exceptions", true,
"internal use only. When false, don't suppress fatal exceptions like\n" +
"NullPointerException, etc so the query will fail and assure it will be noticed",
true),
HIVE_VECTORIZATION_FILESINK_ARROW_NATIVE_ENABLED(
"hive.vectorized.execution.filesink.arrow.native.enabled", false,
"This flag should be set to true to enable the native vectorization\n" +
"of queries using the Arrow SerDe and FileSink.\n" +
"The default value is false."),
HIVE_TYPE_CHECK_ON_INSERT("hive.typecheck.on.insert", true, "This property has been extended to control "
+ "whether to check, convert, and normalize partition value to conform to its column type in "
+ "partition operations including but not limited to insert, such as alter, describe etc."),
HIVE_HADOOP_CLASSPATH("hive.hadoop.classpath", null,
"For Windows OS, we need to pass HIVE_HADOOP_CLASSPATH Java parameter while starting HiveServer2 \n" +
"using \"-hiveconf hive.hadoop.classpath=%HIVE_LIB%\"."),
HIVE_RPC_QUERY_PLAN("hive.rpc.query.plan", false,
"Whether to send the query plan via local resource or RPC"),
HIVE_AM_SPLIT_GENERATION("hive.compute.splits.in.am", true,
"Whether to generate the splits locally or in the AM (tez only)"),
HIVE_TEZ_GENERATE_CONSISTENT_SPLITS("hive.tez.input.generate.consistent.splits", true,
"Whether to generate consistent split locations when generating splits in the AM"),
HIVE_PREWARM_ENABLED("hive.prewarm.enabled", false, "Enables container prewarm for Tez/Spark (Hadoop 2 only)"),
HIVE_PREWARM_NUM_CONTAINERS("hive.prewarm.numcontainers", 10, "Controls the number of containers to prewarm for Tez/Spark (Hadoop 2 only)"),
HIVE_PREWARM_SPARK_TIMEOUT("hive.prewarm.spark.timeout", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Time to wait to finish prewarming spark executors"),
HIVESTAGEIDREARRANGE("hive.stageid.rearrange", "none", new StringSet("none", "idonly", "traverse", "execution"), ""),
HIVEEXPLAINDEPENDENCYAPPENDTASKTYPES("hive.explain.dependency.append.tasktype", false, ""),
HIVEUSEGOOGLEREGEXENGINE("hive.use.googleregex.engine",false,"whether to use google regex engine or not, default regex engine is java.util.regex"),
HIVECOUNTERGROUP("hive.counters.group.name", "HIVE",
"The name of counter group for internal Hive variables (CREATED_FILE, FATAL_ERROR, etc.)"),
HIVE_QUOTEDID_SUPPORT("hive.support.quoted.identifiers", "column",
new StringSet("none", "column", "standard"),
"Whether to use quoted identifier. 'none', 'column', and 'standard' can be used. \n" +
" none: Quotation of identifiers and special characters in identifiers are not allowed but regular " +
"expressions in backticks are supported for column names.\n" +
" column: Use the backtick character to quote identifiers having special characters. `col1` " +
"Use single quotes to quote string literals. 'value' " +
"Double quotes are also accepted but not recommended." +
" standard: SQL standard way to quote identifiers. " +
"Use double quotes to quote identifiers having special characters \"col1\" " +
"and single quotes for string literals. 'value'"
),
/**
* @deprecated Use MetastoreConf.SUPPORT_SPECIAL_CHARACTERS_IN_TABLE_NAMES
*/
@Deprecated
HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES("hive.support.special.characters.tablename", true,
"This flag should be set to true to enable support for special characters in table names.\n"
+ "When it is set to false, only [a-zA-Z_0-9]+ are supported.\n"
+ "The supported special characters are %&'()*+,-./:;<=>?[]_|{}$^!~#@ and space. This flag applies only to"
+ " quoted table names.\nThe default value is true."),
// This config is temporary and will be deprecated later
CREATE_TABLE_AS_EXTERNAL("hive.create.as.external.legacy", false,
"When this flag set to true. it will ignore hive.create.as.acid and hive.create.as.insert.only,"
+ "create external purge table by default."),
/**
* Expose MetastoreConf.CREATE_TABLES_AS_ACID in HiveConf
* so user can set hive.create.as.acid in session level
*/
CREATE_TABLES_AS_ACID("hive.create.as.acid", false,
"Whether the eligible tables should be created as full ACID by default. Does \n" +
"not apply to external tables, the ones using storage handlers, etc."),
HIVE_CREATE_TABLES_AS_INSERT_ONLY("hive.create.as.insert.only", false,
"Whether the eligible tables should be created as ACID insert-only by default. Does \n" +
"not apply to external tables, the ones using storage handlers, etc."),
HIVE_ACID_DIRECT_INSERT_ENABLED("hive.acid.direct.insert.enabled", true,
"Enable writing the data files directly to the table's final destination instead of the staging directory."
+ "This optimization only applies on INSERT operations on ACID tables."),
// role names are case-insensitive
USERS_IN_ADMIN_ROLE("hive.users.in.admin.role", "", false,
"Comma separated list of users who are in admin role for bootstrapping.\n" +
"More users can be added in ADMIN role later."),
HIVE_COMPAT("hive.compat", HiveCompat.DEFAULT_COMPAT_LEVEL,
"Enable (configurable) deprecated behaviors by setting desired level of backward compatibility.\n" +
"Setting to 0.12:\n" +
" Maintains division behavior: int / int = double"),
HIVE_CONVERT_JOIN_BUCKET_MAPJOIN_TEZ("hive.convert.join.bucket.mapjoin.tez", true,
"Whether joins can be automatically converted to bucket map joins in hive \n" +
"when tez is used as the execution engine."),
HIVE_TEZ_BMJ_USE_SUBCACHE("hive.tez.bmj.use.subcache", true,
"Use subcache to reuse hashtable across multiple tasks"),
HIVE_CHECK_CROSS_PRODUCT("hive.exec.check.crossproducts", true,
"Check if a plan contains a Cross Product. If there is one, output a warning to the Session's console."),
HIVE_LOCALIZE_RESOURCE_WAIT_INTERVAL("hive.localize.resource.wait.interval", "5000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Time to wait for another thread to localize the same resource for hive-tez."),
HIVE_LOCALIZE_RESOURCE_NUM_WAIT_ATTEMPTS("hive.localize.resource.num.wait.attempts", 5,
"The number of attempts waiting for localizing a resource in hive-tez."),
TEZ_AUTO_REDUCER_PARALLELISM("hive.tez.auto.reducer.parallelism", false,
"Turn on Tez' auto reducer parallelism feature. When enabled, Hive will still estimate data sizes\n" +
"and set parallelism estimates. Tez will sample source vertices' output sizes and adjust the estimates at runtime as\n" +
"necessary."),
TEZ_LLAP_MIN_REDUCER_PER_EXECUTOR("hive.tez.llap.min.reducer.per.executor", 0.33f,
"If above 0, the min number of reducers for auto-parallelism for LLAP scheduling will\n" +
"be set to this fraction of the number of executors."),
TEZ_MAX_PARTITION_FACTOR("hive.tez.max.partition.factor", 2f,
"When auto reducer parallelism is enabled this factor will be used to over-partition data in shuffle edges."),
TEZ_MIN_PARTITION_FACTOR("hive.tez.min.partition.factor", 0.25f,
"When auto reducer parallelism is enabled this factor will be used to put a lower limit to the number\n" +
"of reducers that tez specifies."),
TEZ_OPTIMIZE_BUCKET_PRUNING(
"hive.tez.bucket.pruning", true,
"When pruning is enabled, filters on bucket columns will be processed by \n" +
"filtering the splits against a bitset of included buckets. This needs predicates \n"+
"produced by hive.optimize.ppd and hive.optimize.index.filters."),
TEZ_OPTIMIZE_BUCKET_PRUNING_COMPAT(
"hive.tez.bucket.pruning.compat", true,
"When pruning is enabled, handle possibly broken inserts due to negative hashcodes.\n" +
"This occasionally doubles the data scan cost, but is default enabled for safety"),
TEZ_DYNAMIC_PARTITION_PRUNING(
"hive.tez.dynamic.partition.pruning", true,
"When dynamic pruning is enabled, joins on partition keys will be processed by sending\n" +
"events from the processing vertices to the Tez application master. These events will be\n" +
"used to prune unnecessary partitions."),
TEZ_DYNAMIC_PARTITION_PRUNING_EXTENDED("hive.tez.dynamic.partition.pruning.extended", true,
"Whether we should try to create additional opportunities for dynamic pruning, e.g., considering\n" +
"siblings that may not be created by normal dynamic pruning logic.\n" +
"Only works when dynamic pruning is enabled."),
TEZ_DYNAMIC_PARTITION_PRUNING_MAX_EVENT_SIZE("hive.tez.dynamic.partition.pruning.max.event.size", 1*1024*1024L,
"Maximum size of events sent by processors in dynamic pruning. If this size is crossed no pruning will take place."),
TEZ_DYNAMIC_PARTITION_PRUNING_MAX_DATA_SIZE("hive.tez.dynamic.partition.pruning.max.data.size", 100*1024*1024L,
"Maximum total data size of events in dynamic pruning."),
TEZ_DYNAMIC_SEMIJOIN_REDUCTION("hive.tez.dynamic.semijoin.reduction", true,
"When dynamic semijoin is enabled, shuffle joins will perform a leaky semijoin before shuffle. This " +
"requires hive.tez.dynamic.partition.pruning to be enabled."),
TEZ_MIN_BLOOM_FILTER_ENTRIES("hive.tez.min.bloom.filter.entries", 1000000L,
"Bloom filter should be of at min certain size to be effective"),
TEZ_MAX_BLOOM_FILTER_ENTRIES("hive.tez.max.bloom.filter.entries", 100000000L,
"Bloom filter should be of at max certain size to be effective"),
TEZ_BLOOM_FILTER_FACTOR("hive.tez.bloom.filter.factor", (float) 1.0,
"Bloom filter should be a multiple of this factor with nDV"),
TEZ_BLOOM_FILTER_MERGE_THREADS("hive.tez.bloom.filter.merge.threads", 1,
"How many threads are used for merging bloom filters in addition to task's main thread?\n"
+ "-1: sanity check, it will fail if execution hits bloom filter merge codepath\n"
+ " 0: feature is disabled, use only task's main thread for bloom filter merging\n"
+ " 1: recommended value: there is only 1 merger thread (additionally to the task's main thread),"
+ "according perf tests, this can lead to serious improvement \n"),
TEZ_BIGTABLE_MIN_SIZE_SEMIJOIN_REDUCTION("hive.tez.bigtable.minsize.semijoin.reduction", 100000000L,
"Big table for runtime filteting should be of atleast this size"),
TEZ_DYNAMIC_SEMIJOIN_REDUCTION_THRESHOLD("hive.tez.dynamic.semijoin.reduction.threshold", (float) 0.50,
"Only perform semijoin optimization if the estimated benefit at or above this fraction of the target table"),
TEZ_DYNAMIC_SEMIJOIN_REDUCTION_MULTICOLUMN(
"hive.tez.dynamic.semijoin.reduction.multicolumn",
true,
"Whether to consider multicolumn semijoin reducers or not.\n"
+ "This should always be set to true. Since it is a new feature, it has been made configurable."),
TEZ_DYNAMIC_SEMIJOIN_REDUCTION_FOR_MAPJOIN("hive.tez.dynamic.semijoin.reduction.for.mapjoin", false,
"Use a semi-join branch for map-joins. This may not make it faster, but is helpful in certain join patterns."),
TEZ_DYNAMIC_SEMIJOIN_REDUCTION_FOR_DPP_FACTOR("hive.tez.dynamic.semijoin.reduction.for.dpp.factor",
(float) 1.0,
"The factor to decide if semijoin branch feeds into a TableScan\n" +
"which has an outgoing Dynamic Partition Pruning (DPP) branch based on number of distinct values."),
TEZ_SMB_NUMBER_WAVES(
"hive.tez.smb.number.waves",
(float) 0.5,
"The number of waves in which to run the SMB join. Account for cluster being occupied. Ideally should be 1 wave."),
TEZ_EXEC_SUMMARY(
"hive.tez.exec.print.summary",
false,
"Display breakdown of execution steps, for every query executed by the shell."),
TEZ_SESSION_EVENTS_SUMMARY(
"hive.tez.session.events.print.summary",
"none", new StringSet("none", "text", "json"),
"Display summary of all tez sessions related events in text or json format"),
TEZ_EXEC_INPLACE_PROGRESS(
"hive.tez.exec.inplace.progress",
true,
"Updates tez job execution progress in-place in the terminal when hive-cli is used."),
HIVE_SERVER2_INPLACE_PROGRESS(
"hive.server2.in.place.progress",
true,
"Allows hive server 2 to send progress bar update information. This is currently available"
+ " only if the execution engine is tez or Spark."),
TEZ_DAG_STATUS_CHECK_INTERVAL("hive.tez.dag.status.check.interval", "500ms",
new TimeValidator(TimeUnit.MILLISECONDS), "Interval between subsequent DAG status invocation."),
SPARK_EXEC_INPLACE_PROGRESS("hive.spark.exec.inplace.progress", true,
"Updates spark job execution progress in-place in the terminal."),
TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION("hive.tez.container.max.java.heap.fraction", 0.8f,
"This is to override the tez setting with the same name"),
TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION_MIN("hive.tez.task.scale.memory.reserve-fraction.min",
0.3f, "This is to override the tez setting tez.task.scale.memory.reserve-fraction"),
TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION_MAX("hive.tez.task.scale.memory.reserve.fraction.max",
0.5f, "The maximum fraction of JVM memory which Tez will reserve for the processor"),
TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION("hive.tez.task.scale.memory.reserve.fraction",
-1f, "The customized fraction of JVM memory which Tez will reserve for the processor"),
TEZ_CARTESIAN_PRODUCT_EDGE_ENABLED("hive.tez.cartesian-product.enabled",
false, "Use Tez cartesian product edge to speed up cross product"),
TEZ_SIMPLE_CUSTOM_EDGE_TINY_BUFFER_SIZE_MB("hive.tez.unordered.output.buffer.size.mb", -1,
"When we have an operation that does not need a large buffer, we use this buffer size for simple custom edge.\n" +
"Value is an integer. Default value is -1, which means that we will estimate this value from operators in the plan."),
// The default is different on the client and server, so it's null here.
LLAP_IO_ENABLED("hive.llap.io.enabled", null, "Whether the LLAP IO layer is enabled."),
LLAP_IO_CACHE_ONLY("hive.llap.io.cache.only", false, "Whether the query should read from cache only. If set to " +
"true and a cache miss happens during the read an exception will occur. Primarily used for testing."),
LLAP_IO_ROW_WRAPPER_ENABLED("hive.llap.io.row.wrapper.enabled", true, "Whether the LLAP IO row wrapper is enabled for non-vectorized queries."),
LLAP_IO_ACID_ENABLED("hive.llap.io.acid", true, "Whether the LLAP IO layer is enabled for ACID."),
LLAP_IO_TRACE_SIZE("hive.llap.io.trace.size", "2Mb",
new SizeValidator(0L, true, (long)Integer.MAX_VALUE, false),
"The buffer size for a per-fragment LLAP debug trace. 0 to disable."),
LLAP_IO_TRACE_ALWAYS_DUMP("hive.llap.io.trace.always.dump", false,
"Whether to always dump the LLAP IO trace (if enabled); the default is on error."),
LLAP_IO_NONVECTOR_WRAPPER_ENABLED("hive.llap.io.nonvector.wrapper.enabled", true,
"Whether the LLAP IO layer is enabled for non-vectorized queries that read inputs\n" +
"that can be vectorized"),
LLAP_IO_MEMORY_MODE("hive.llap.io.memory.mode", "cache",
new StringSet("cache", "none"),
"LLAP IO memory usage; 'cache' (the default) uses data and metadata cache with a\n" +
"custom off-heap allocator, 'none' doesn't use either (this mode may result in\n" +
"significant performance degradation)"),
LLAP_ALLOCATOR_MIN_ALLOC("hive.llap.io.allocator.alloc.min", "4Kb", new SizeValidator(),
"Minimum allocation possible from LLAP buddy allocator. Allocations below that are\n" +
"padded to minimum allocation. For ORC, should generally be the same as the expected\n" +
"compression buffer size, or next lowest power of 2. Must be a power of 2."),
LLAP_ALLOCATOR_MAX_ALLOC("hive.llap.io.allocator.alloc.max", "16Mb", new SizeValidator(),
"Maximum allocation possible from LLAP buddy allocator. For ORC, should be as large as\n" +
"the largest expected ORC compression buffer size. Must be a power of 2."),
LLAP_ALLOCATOR_ARENA_COUNT("hive.llap.io.allocator.arena.count", 8,
"Arena count for LLAP low-level cache; cache will be allocated in the steps of\n" +
"(size/arena_count) bytes. This size must be <= 1Gb and >= max allocation; if it is\n" +
"not the case, an adjusted size will be used. Using powers of 2 is recommended."),
LLAP_IO_MEMORY_MAX_SIZE("hive.llap.io.memory.size", "1Gb", new SizeValidator(),
"Maximum size for IO allocator or ORC low-level cache.", "hive.llap.io.cache.orc.size"),
LLAP_ALLOCATOR_DIRECT("hive.llap.io.allocator.direct", true,
"Whether ORC low-level cache should use direct allocation."),
LLAP_ALLOCATOR_PREALLOCATE("hive.llap.io.allocator.preallocate", true,
"Whether to preallocate the entire IO memory at init time."),
LLAP_ALLOCATOR_MAPPED("hive.llap.io.allocator.mmap", false,
"Whether ORC low-level cache should use memory mapped allocation (direct I/O). \n" +
"This is recommended to be used along-side NVDIMM (DAX) or NVMe flash storage."),
LLAP_ALLOCATOR_MAPPED_PATH("hive.llap.io.allocator.mmap.path", "/tmp",
new WritableDirectoryValidator(),
"The directory location for mapping NVDIMM/NVMe flash storage into the ORC low-level cache."),
LLAP_ALLOCATOR_DISCARD_METHOD("hive.llap.io.allocator.discard.method", "both",
new StringSet("freelist", "brute", "both"),
"Which method to use to force-evict blocks to deal with fragmentation:\n" +
"freelist - use half-size free list (discards less, but also less reliable); brute -\n" +
"brute force, discard whatever we can; both - first try free list, then brute force."),
LLAP_ALLOCATOR_DEFRAG_HEADROOM("hive.llap.io.allocator.defrag.headroom", "1Mb",
"How much of a headroom to leave to allow allocator more flexibility to defragment.\n" +
"The allocator would further cap it to a fraction of total memory."),
LLAP_ALLOCATOR_MAX_FORCE_EVICTED("hive.llap.io.allocator.max.force.eviction", "16Mb",
"Fragmentation can lead to some cases where more eviction has to happen to accommodate allocations\n" +
" This configuration puts a limit on how many bytes to force evict before using Allocator Discard method."
+ " Higher values will allow allocator more flexibility and will lead to better caching."),
LLAP_TRACK_CACHE_USAGE("hive.llap.io.track.cache.usage", true,
"Whether to tag LLAP cache contents, mapping them to Hive entities (paths for\n" +
"partitions and tables) for reporting."),
LLAP_USE_LRFU("hive.llap.io.use.lrfu", true,
"Whether ORC low-level cache should use LRFU cache policy instead of default (FIFO)."),
LLAP_LRFU_LAMBDA("hive.llap.io.lrfu.lambda", 0.1f,
"Lambda for ORC low-level cache LRFU cache policy. Must be in [0, 1]. 0 makes LRFU\n" +
"behave like LFU, 1 makes it behave like LRU, values in between balance accordingly.\n" +
"The meaning of this parameter is the inverse of the number of time ticks (cache\n" +
" operations, currently) that cause the combined recency-frequency of a block in cache\n" +
" to be halved."),
LLAP_LRFU_BP_WRAPPER_SIZE("hive.llap.io.lrfu.bp.wrapper.size", 64, "thread local queue "
+ "used to amortize the lock contention, the idea hear is to try locking as soon we reach max size / 2 "
+ "and block when max queue size reached"),
LLAP_CACHE_ALLOW_SYNTHETIC_FILEID("hive.llap.cache.allow.synthetic.fileid", true,
"Whether LLAP cache should use synthetic file ID if real one is not available. Systems\n" +
"like HDFS, Isilon, etc. provide a unique file/inode ID. On other FSes (e.g. local\n" +
"FS), the cache would not work by default because LLAP is unable to uniquely track the\n" +
"files; enabling this setting allows LLAP to generate file ID from the path, size and\n" +
"modification time, which is almost certain to identify file uniquely. However, if you\n" +
"use a FS without file IDs and rewrite files a lot (or are paranoid), you might want\n" +
"to avoid this setting."),
LLAP_CACHE_DEFAULT_FS_FILE_ID("hive.llap.cache.defaultfs.only.native.fileid", true,
"Whether LLAP cache should use native file IDs from the default FS only. This is to\n" +
"avoid file ID collisions when several different DFS instances are in use at the same\n" +
"time. Disable this check to allow native file IDs from non-default DFS."),
LLAP_CACHE_ENABLE_ORC_GAP_CACHE("hive.llap.orc.gap.cache", true,
"Whether LLAP cache for ORC should remember gaps in ORC compression buffer read\n" +
"estimates, to avoid re-reading the data that was read once and discarded because it\n" +
"is unneeded. This is only necessary for ORC files written before HIVE-9660."),
LLAP_IO_USE_FILEID_PATH("hive.llap.io.use.fileid.path", true,
"Whether LLAP should use fileId (inode)-based path to ensure better consistency for the\n" +
"cases of file overwrites. This is supported on HDFS. Disabling this also turns off any\n" +
"cache consistency checks based on fileid comparisons."),
// Restricted to text for now as this is a new feature; only text files can be sliced.
LLAP_IO_ENCODE_ENABLED("hive.llap.io.encode.enabled", true,
"Whether LLAP should try to re-encode and cache data for non-ORC formats. This is used\n" +
"on LLAP Server side to determine if the infrastructure for that is initialized."),
LLAP_IO_ENCODE_FORMATS("hive.llap.io.encode.formats",
"org.apache.hadoop.mapred.TextInputFormat,",
"The table input formats for which LLAP IO should re-encode and cache data.\n" +
"Comma-separated list."),
LLAP_IO_ENCODE_ALLOC_SIZE("hive.llap.io.encode.alloc.size", "256Kb", new SizeValidator(),
"Allocation size for the buffers used to cache encoded data from non-ORC files. Must\n" +
"be a power of two between " + LLAP_ALLOCATOR_MIN_ALLOC + " and\n" +
LLAP_ALLOCATOR_MAX_ALLOC + "."),
LLAP_IO_ENCODE_VECTOR_SERDE_ENABLED("hive.llap.io.encode.vector.serde.enabled", true,
"Whether LLAP should use vectorized SerDe reader to read text data when re-encoding."),
LLAP_IO_ENCODE_VECTOR_SERDE_ASYNC_ENABLED("hive.llap.io.encode.vector.serde.async.enabled",
true,
"Whether LLAP should use async mode in vectorized SerDe reader to read text data."),
LLAP_IO_ENCODE_SLICE_ROW_COUNT("hive.llap.io.encode.slice.row.count", 100000,
"Row count to use to separate cache slices when reading encoded data from row-based\n" +
"inputs into LLAP cache, if this feature is enabled."),
LLAP_IO_ENCODE_SLICE_LRR("hive.llap.io.encode.slice.lrr", true,
"Whether to separate cache slices when reading encoded data from text inputs via MR\n" +
"MR LineRecordRedader into LLAP cache, if this feature is enabled. Safety flag."),
LLAP_ORC_ENABLE_TIME_COUNTERS("hive.llap.io.orc.time.counters", true,
"Whether to enable time counters for LLAP IO layer (time spent in HDFS, etc.)"),
LLAP_IO_VRB_QUEUE_LIMIT_MAX("hive.llap.io.vrb.queue.limit.max", 50000,
"The maximum queue size for VRBs produced by a LLAP IO thread when the processing is\n" +
"slower than the IO. The actual queue size is set per fragment, and is adjusted down\n" +
"from the base, depending on the schema see LLAP_IO_CVB_BUFFERED_SIZE."),
LLAP_IO_VRB_QUEUE_LIMIT_MIN("hive.llap.io.vrb.queue.limit.min", 1,
"The minimum queue size for VRBs produced by a LLAP IO thread when the processing is\n" +
"slower than the IO (used when determining the size from base size)."),
LLAP_IO_CVB_BUFFERED_SIZE("hive.llap.io.cvb.memory.consumption.", 1L << 30,
"The amount of bytes used to buffer CVB between IO and Processor Threads default to 1GB, "
+ "this will be used to compute a best effort queue size for VRBs produced by a LLAP IO thread."),
LLAP_IO_PROACTIVE_EVICTION_ENABLED("hive.llap.io.proactive.eviction.enabled", true,
"If true proactive cache eviction is enabled, thus LLAP will proactively evict buffers" +
" that belong to dropped Hive entities (DBs, tables, partitions, or temp tables."),
LLAP_IO_PROACTIVE_EVICTION_SWEEP_INTERVAL("hive.llap.io.proactive.eviction.sweep.interval", "5s",
new TimeValidator(TimeUnit.SECONDS),
"How frequently (in seconds) LLAP should check for buffers marked for proactive eviction and" +
"proceed with their eviction."),
LLAP_IO_PROACTIVE_EVICTION_INSTANT_DEALLOC("hive.llap.io.proactive.eviction.instant.dealloc", false,
"Experimental feature: when set to true, buffer deallocation will happen as soon as proactive eviction " +
"notifications are received by the daemon. Sweep phase of proactive eviction will only do the cache policy " +
"cleanup in this case. This can increase cache hit ratio but might scale bad in a workload that generates " +
"many proactive eviction events."),
LLAP_IO_SHARE_OBJECT_POOLS("hive.llap.io.share.object.pools", false,
"Whether to used shared object pools in LLAP IO. A safety flag."),
LLAP_AUTO_ALLOW_UBER("hive.llap.auto.allow.uber", false,
"Whether or not to allow the planner to run vertices in the AM."),
LLAP_AUTO_ENFORCE_TREE("hive.llap.auto.enforce.tree", true,
"Enforce that all parents are in llap, before considering vertex"),
LLAP_AUTO_ENFORCE_VECTORIZED("hive.llap.auto.enforce.vectorized", true,
"Enforce that inputs are vectorized, before considering vertex"),
LLAP_AUTO_ENFORCE_STATS("hive.llap.auto.enforce.stats", true,
"Enforce that col stats are available, before considering vertex"),
LLAP_AUTO_MAX_INPUT("hive.llap.auto.max.input.size", 10*1024*1024*1024L,
"Check input size, before considering vertex (-1 disables check)"),
LLAP_AUTO_MAX_OUTPUT("hive.llap.auto.max.output.size", 1*1024*1024*1024L,
"Check output size, before considering vertex (-1 disables check)"),
LLAP_SKIP_COMPILE_UDF_CHECK("hive.llap.skip.compile.udf.check", false,
"Whether to skip the compile-time check for non-built-in UDFs when deciding whether to\n" +
"execute tasks in LLAP. Skipping the check allows executing UDFs from pre-localized\n" +
"jars in LLAP; if the jars are not pre-localized, the UDFs will simply fail to load."),
LLAP_ALLOW_PERMANENT_FNS("hive.llap.allow.permanent.fns", true,
"Whether LLAP decider should allow permanent UDFs."),
LLAP_EXECUTION_MODE("hive.llap.execution.mode", "none",
new StringSet("auto", "none", "all", "map", "only"),
"Chooses whether query fragments will run in container or in llap"),
LLAP_IO_ETL_SKIP_FORMAT("hive.llap.io.etl.skip.format", "encode", new StringSet("none", "encode", "all"),
"For ETL queries, determines whether to skip llap io cache. By default, hive.llap.io.encode.enabled " +
"will be set to false which disables LLAP IO for text formats. Setting it to 'all' will disable LLAP IO for all" +
" formats. 'none' will not disable LLAP IO for any formats."),
LLAP_OBJECT_CACHE_ENABLED("hive.llap.object.cache.enabled", true,
"Cache objects (plans, hashtables, etc) in llap"),
LLAP_IO_DECODING_METRICS_PERCENTILE_INTERVALS("hive.llap.io.decoding.metrics.percentiles.intervals", "30",
"Comma-delimited set of integers denoting the desired rollover intervals (in seconds)\n" +
"for percentile latency metrics on the LLAP daemon IO decoding time.\n" +
"hive.llap.queue.metrics.percentiles.intervals"),
LLAP_IO_THREADPOOL_SIZE("hive.llap.io.threadpool.size", 10,
"Specify the number of threads to use for low-level IO thread pool."),
LLAP_USE_KERBEROS("hive.llap.kerberos.enabled", true,
"If LLAP is configured for Kerberos authentication. This could be useful when cluster\n" +
"is kerberized, but LLAP is not."),
LLAP_KERBEROS_PRINCIPAL(HIVE_LLAP_DAEMON_SERVICE_PRINCIPAL_NAME, "",
"The name of the LLAP daemon's service principal."),
LLAP_KERBEROS_KEYTAB_FILE("hive.llap.daemon.keytab.file", "",
"The path to the Kerberos Keytab file containing the LLAP daemon's service principal."),
LLAP_WEBUI_SPNEGO_KEYTAB_FILE("hive.llap.webui.spnego.keytab", "",
"The path to the Kerberos Keytab file containing the LLAP WebUI SPNEGO principal.\n" +
"Typical value would look like /etc/security/keytabs/spnego.service.keytab."),
LLAP_WEBUI_SPNEGO_PRINCIPAL("hive.llap.webui.spnego.principal", "",
"The LLAP WebUI SPNEGO service principal. Configured similarly to\n" +
"hive.server2.webui.spnego.principal"),
LLAP_FS_KERBEROS_PRINCIPAL("hive.llap.task.principal", "",
"The name of the principal to use to run tasks. By default, the clients are required\n" +
"to provide tokens to access HDFS/etc."),
LLAP_FS_KERBEROS_KEYTAB_FILE("hive.llap.task.keytab.file", "",
"The path to the Kerberos Keytab file containing the principal to use to run tasks.\n" +
"By default, the clients are required to provide tokens to access HDFS/etc."),
LLAP_ZKSM_ZK_CONNECTION_STRING("hive.llap.zk.sm.connectionString", "",
"ZooKeeper connection string for ZooKeeper SecretManager."),
LLAP_ZKSM_ZK_SESSION_TIMEOUT("hive.llap.zk.sm.session.timeout", "40s", new TimeValidator(
TimeUnit.MILLISECONDS), "ZooKeeper session timeout for ZK SecretManager."),
LLAP_ZK_REGISTRY_USER("hive.llap.zk.registry.user", "",
"In the LLAP ZooKeeper-based registry, specifies the username in the Zookeeper path.\n" +
"This should be the hive user or whichever user is running the LLAP daemon."),
LLAP_ZK_REGISTRY_NAMESPACE("hive.llap.zk.registry.namespace", null,
"In the LLAP ZooKeeper-based registry, overrides the ZK path namespace. Note that\n" +
"using this makes the path management (e.g. setting correct ACLs) your responsibility."),
// Note: do not rename to ..service.acl; Hadoop generates .hosts setting name from this,
// resulting in a collision with existing hive.llap.daemon.service.hosts and bizarre errors.
// These are read by Hadoop IPC, so you should check the usage and naming conventions (e.g.
// ".blocked" is a string hardcoded by Hadoop, and defaults are enforced elsewhere in Hive)
// before making changes or copy-pasting these.
LLAP_SECURITY_ACL("hive.llap.daemon.acl", "*", "The ACL for LLAP daemon."),
LLAP_SECURITY_ACL_DENY("hive.llap.daemon.acl.blocked", "", "The deny ACL for LLAP daemon."),
LLAP_MANAGEMENT_ACL("hive.llap.management.acl", "*", "The ACL for LLAP daemon management."),
LLAP_MANAGEMENT_ACL_DENY("hive.llap.management.acl.blocked", "",
"The deny ACL for LLAP daemon management."),
LLAP_PLUGIN_ACL("hive.llap.plugin.acl", "*", "The ACL for LLAP plugin AM endpoint."),
LLAP_PLUGIN_ACL_DENY("hive.llap.plugin.acl.blocked", "",
"The deny ACL for LLAP plugin AM endpoint."),
LLAP_REMOTE_TOKEN_REQUIRES_SIGNING("hive.llap.remote.token.requires.signing", "true",
new StringSet("false", "except_llap_owner", "true"),
"Whether the token returned from LLAP management API should require fragment signing.\n" +
"True by default; can be disabled to allow CLI to get tokens from LLAP in a secure\n" +
"cluster by setting it to true or 'except_llap_owner' (the latter returns such tokens\n" +
"to everyone except the user LLAP cluster is authenticating under)."),
// Hadoop DelegationTokenManager default is 1 week.
LLAP_DELEGATION_TOKEN_LIFETIME("hive.llap.daemon.delegation.token.lifetime", "14d",
new TimeValidator(TimeUnit.SECONDS),
"LLAP delegation token lifetime, in seconds if specified without a unit."),
LLAP_MANAGEMENT_RPC_PORT("hive.llap.management.rpc.port", 15004,
"RPC port for LLAP daemon management service."),
LLAP_WEB_AUTO_AUTH("hive.llap.auto.auth", false,
"Whether or not to set Hadoop configs to enable auth in LLAP web app."),
LLAP_DAEMON_RPC_NUM_HANDLERS("hive.llap.daemon.rpc.num.handlers", 5,
"Number of RPC handlers for LLAP daemon.", "llap.daemon.rpc.num.handlers"),
LLAP_PLUGIN_RPC_PORT("hive.llap.plugin.rpc.port", 0,
"Port to use for LLAP plugin rpc server"),
LLAP_PLUGIN_RPC_NUM_HANDLERS("hive.llap.plugin.rpc.num.handlers", 1,
"Number of RPC handlers for AM LLAP plugin endpoint."),
LLAP_HDFS_PACKAGE_DIR("hive.llap.hdfs.package.dir", ".yarn",
"Package directory on HDFS used for holding collected configuration and libraries" +
" required for YARN launch. Note: this should be set to the same as yarn.service.base.path"),
LLAP_DAEMON_WORK_DIRS("hive.llap.daemon.work.dirs", "",
"Working directories for the daemon. This should not be set if running as a YARN\n" +
"Service. It must be set when not running on YARN. If the value is set when\n" +
"running as a YARN Service, the specified value will be used.",
"llap.daemon.work.dirs"),
LLAP_DAEMON_YARN_SHUFFLE_PORT("hive.llap.daemon.yarn.shuffle.port", 15551,
"YARN shuffle port for LLAP-daemon-hosted shuffle.", "llap.daemon.yarn.shuffle.port"),
LLAP_DAEMON_YARN_CONTAINER_MB("hive.llap.daemon.yarn.container.mb", -1,
"llap server yarn container size in MB. Used in LlapServiceDriver and package.py", "llap.daemon.yarn.container.mb"),
LLAP_DAEMON_QUEUE_NAME("hive.llap.daemon.queue.name", null,
"Queue name within which the llap application will run." +
" Used in LlapServiceDriver and package.py"),
// TODO Move the following 2 properties out of Configuration to a constant.
LLAP_DAEMON_CONTAINER_ID("hive.llap.daemon.container.id", null,
"ContainerId of a running LlapDaemon. Used to publish to the registry"),
LLAP_DAEMON_NM_ADDRESS("hive.llap.daemon.nm.address", null,
"NM Address host:rpcPort for the NodeManager on which the instance of the daemon is running.\n" +
"Published to the llap registry. Should never be set by users"),
LLAP_DAEMON_SHUFFLE_DIR_WATCHER_ENABLED("hive.llap.daemon.shuffle.dir.watcher.enabled", false,
"TODO doc", "llap.daemon.shuffle.dir-watcher.enabled"),
LLAP_DAEMON_AM_LIVENESS_HEARTBEAT_INTERVAL_MS(
"hive.llap.daemon.am.liveness.heartbeat.interval.ms", "10000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Tez AM-LLAP heartbeat interval (milliseconds). This needs to be below the task timeout\n" +
"interval, but otherwise as high as possible to avoid unnecessary traffic.",
"llap.daemon.am.liveness.heartbeat.interval-ms"),
LLAP_DAEMON_AM_LIVENESS_CONNECTION_TIMEOUT_MS(
"hive.llap.am.liveness.connection.timeout.ms", "10000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Amount of time to wait on connection failures to the AM from an LLAP daemon before\n" +
"considering the AM to be dead.", "llap.am.liveness.connection.timeout-millis"),
LLAP_DAEMON_AM_USE_FQDN("hive.llap.am.use.fqdn", true,
"Whether to use FQDN of the AM machine when submitting work to LLAP."),
LLAP_DAEMON_EXEC_USE_FQDN("hive.llap.exec.use.fqdn", true,
"On non-kerberized clusters, where the hostnames are stable but ip address changes, setting this config\n" +
" to false will use ip address of llap daemon in execution context instead of FQDN"),
// Not used yet - since the Writable RPC engine does not support this policy.
LLAP_DAEMON_AM_LIVENESS_CONNECTION_SLEEP_BETWEEN_RETRIES_MS(
"hive.llap.am.liveness.connection.sleep.between.retries.ms", "2000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Sleep duration while waiting to retry connection failures to the AM from the daemon for\n" +
"the general keep-alive thread (milliseconds).",
"llap.am.liveness.connection.sleep-between-retries-millis"),
LLAP_DAEMON_TASK_SCHEDULER_TIMEOUT_SECONDS(
"hive.llap.task.scheduler.timeout.seconds", "60s",
new TimeValidator(TimeUnit.SECONDS),
"Amount of time to wait before failing the query when there are no llap daemons running\n" +
"(alive) in the cluster.", "llap.daemon.scheduler.timeout.seconds"),
LLAP_DAEMON_NUM_EXECUTORS("hive.llap.daemon.num.executors", 4,
"Number of executors to use in LLAP daemon; essentially, the number of tasks that can be\n" +
"executed in parallel.", "llap.daemon.num.executors"),
LLAP_MAPJOIN_MEMORY_OVERSUBSCRIBE_FACTOR("hive.llap.mapjoin.memory.oversubscribe.factor", 0.2f,
"Fraction of memory from hive.auto.convert.join.noconditionaltask.size that can be over subscribed\n" +
"by queries running in LLAP mode. This factor has to be from 0.0 to 1.0. Default is 20% over subscription.\n"),
LLAP_MEMORY_OVERSUBSCRIPTION_MAX_EXECUTORS_PER_QUERY("hive.llap.memory.oversubscription.max.executors.per.query",
-1,
"Used along with hive.llap.mapjoin.memory.oversubscribe.factor to limit the number of executors from\n" +
"which memory for mapjoin can be borrowed. Default 3 (from 3 other executors\n" +
"hive.llap.mapjoin.memory.oversubscribe.factor amount of memory can be borrowed based on which mapjoin\n" +
"conversion decision will be made). This is only an upper bound. Lower bound is determined by number of\n" +
"executors and configured max concurrency."),
LLAP_MAPJOIN_MEMORY_MONITOR_CHECK_INTERVAL("hive.llap.mapjoin.memory.monitor.check.interval", 100000L,
"Check memory usage of mapjoin hash tables after every interval of this many rows. If map join hash table\n" +
"memory usage exceeds (hive.auto.convert.join.noconditionaltask.size * hive.hash.table.inflation.factor)\n" +
"when running in LLAP, tasks will get killed and not retried. Set the value to 0 to disable this feature."),
LLAP_DAEMON_AM_REPORTER_MAX_THREADS("hive.llap.daemon.am-reporter.max.threads", 4,
"Maximum number of threads to be used for AM reporter. If this is lower than number of\n" +
"executors in llap daemon, it would be set to number of executors at runtime.",
"llap.daemon.am-reporter.max.threads"),
LLAP_DAEMON_RPC_PORT("hive.llap.daemon.rpc.port", 0, "The LLAP daemon RPC port.",
"llap.daemon.rpc.port. A value of 0 indicates a dynamic port"),
LLAP_DAEMON_MEMORY_PER_INSTANCE_MB("hive.llap.daemon.memory.per.instance.mb", 4096,
"The total amount of memory to use for the executors inside LLAP (in megabytes).",
"llap.daemon.memory.per.instance.mb"),
LLAP_DAEMON_XMX_HEADROOM("hive.llap.daemon.xmx.headroom", "5%",
"The total amount of heap memory set aside by LLAP and not used by the executors. Can\n" +
"be specified as size (e.g. '512Mb'), or percentage (e.g. '5%'). Note that the latter is\n" +
"derived from the total daemon XMX, which can be different from the total executor\n" +
"memory if the cache is on-heap; although that's not the default configuration."),
LLAP_DAEMON_VCPUS_PER_INSTANCE("hive.llap.daemon.vcpus.per.instance", 4,
"The total number of vcpus to use for the executors inside LLAP.",
"llap.daemon.vcpus.per.instance"),
LLAP_DAEMON_NUM_FILE_CLEANER_THREADS("hive.llap.daemon.num.file.cleaner.threads", 1,
"Number of file cleaner threads in LLAP.", "llap.daemon.num.file.cleaner.threads"),
LLAP_FILE_CLEANUP_DELAY_SECONDS("hive.llap.file.cleanup.delay.seconds", "0s",
new TimeValidator(TimeUnit.SECONDS),
"How long to delay before cleaning up query files in LLAP (in seconds, for debugging).",
"llap.file.cleanup.delay-seconds"),
LLAP_DAEMON_SERVICE_HOSTS("hive.llap.daemon.service.hosts", null,
"Explicitly specified hosts to use for LLAP scheduling. Useful for testing. By default,\n" +
"YARN registry is used.", "llap.daemon.service.hosts"),
LLAP_DAEMON_SERVICE_REFRESH_INTERVAL("hive.llap.daemon.service.refresh.interval.sec", "60s",
new TimeValidator(TimeUnit.SECONDS),
"LLAP YARN registry service list refresh delay, in seconds.",
"llap.daemon.service.refresh.interval"),
LLAP_DAEMON_COMMUNICATOR_NUM_THREADS("hive.llap.daemon.communicator.num.threads", 10,
"Number of threads to use in LLAP task communicator in Tez AM.",
"llap.daemon.communicator.num.threads"),
LLAP_PLUGIN_CLIENT_NUM_THREADS("hive.llap.plugin.client.num.threads", 10,
"Number of threads to use in LLAP task plugin client."),
LLAP_DAEMON_DOWNLOAD_PERMANENT_FNS("hive.llap.daemon.download.permanent.fns", false,
"Whether LLAP daemon should localize the resources for permanent UDFs."),
LLAP_TASK_SCHEDULER_AM_COLLECT_DAEMON_METRICS_MS("hive.llap.task.scheduler.am.collect.daemon.metrics.ms", "0ms",
new TimeValidator(TimeUnit.MILLISECONDS), "Collect llap daemon metrics in the AM every given milliseconds,\n" +
"so that the AM can use this information, to make better scheduling decisions.\n" +
"If it's set to 0, then the feature is disabled."),
LLAP_TASK_SCHEDULER_AM_COLLECT_DAEMON_METRICS_LISTENER(
"hive.llap.task.scheduler.am.collect.daemon.metrics.listener", "",
"The listener which is called when new Llap Daemon statistics is received on AM side.\n" +
"The listener should implement the " +
"org.apache.hadoop.hive.llap.tezplugins.metrics.LlapMetricsListener interface."),
LLAP_NODEHEALTHCHECKS_MINTASKS(
"hive.llap.nodehealthchecks.mintasks", 2000,
"Specifies the minimum amount of tasks, executed by a particular LLAP daemon, before the health\n" +
"status of the node is examined."),
LLAP_NODEHEALTHCHECKS_MININTERVALDURATION(
"hive.llap.nodehealthckecks.minintervalduration", "300s",
new TimeValidator(TimeUnit.SECONDS),
"The minimum time that needs to elapse between two actions that are the correcting results of identifying\n" +
"an unhealthy node. Even if additional nodes are considered to be unhealthy, no action is performed until\n" +
"this time interval has passed since the last corrective action."),
LLAP_NODEHEALTHCHECKS_TASKTIMERATIO(
"hive.llap.nodehealthckecks.tasktimeratio", 1.5f,
"LLAP daemons are considered unhealthy, if their average (Map-) task execution time is significantly larger\n" +
"than the average task execution time of other nodes. This value specifies the ratio of a node to other\n" +
"nodes, which is considered as threshold for unhealthy. A value of 1.5 for example considers a node to be\n" +
"unhealthy if its average task execution time is 50% larger than the average of other nodes."),
LLAP_NODEHEALTHCHECKS_EXECUTORRATIO(
"hive.llap.nodehealthckecks.executorratio", 2.0f,
"If an unhealthy node is identified, it is blacklisted only where there is enough free executors to execute\n" +
"the tasks. This value specifies the ratio of the free executors compared to the blacklisted ones.\n" +
"A value of 2.0 for example defines that we blacklist an unhealthy node only if we have 2 times more\n" +
"free executors on the remaining nodes than the unhealthy node."),
LLAP_NODEHEALTHCHECKS_MAXNODES(
"hive.llap.nodehealthckecks.maxnodes", 1,
"The maximum number of blacklisted nodes. If there are at least this number of blacklisted nodes\n" +
"the listener will not blacklist further nodes even if all the conditions are met."),
LLAP_TASK_SCHEDULER_AM_REGISTRY_NAME("hive.llap.task.scheduler.am.registry", "llap",
"AM registry name for LLAP task scheduler plugin to register with."),
LLAP_TASK_SCHEDULER_AM_REGISTRY_PRINCIPAL("hive.llap.task.scheduler.am.registry.principal", "",
"The name of the principal used to access ZK AM registry securely."),
LLAP_TASK_SCHEDULER_AM_REGISTRY_KEYTAB_FILE("hive.llap.task.scheduler.am.registry.keytab.file", "",
"The path to the Kerberos keytab file used to access ZK AM registry securely."),
LLAP_TASK_SCHEDULER_NODE_REENABLE_MIN_TIMEOUT_MS(
"hive.llap.task.scheduler.node.reenable.min.timeout.ms", "200ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Minimum time after which a previously disabled node will be re-enabled for scheduling,\n" +
"in milliseconds. This may be modified by an exponential back-off if failures persist.",
"llap.task.scheduler.node.re-enable.min.timeout.ms"),
LLAP_TASK_SCHEDULER_NODE_REENABLE_MAX_TIMEOUT_MS(
"hive.llap.task.scheduler.node.reenable.max.timeout.ms", "10000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Maximum time after which a previously disabled node will be re-enabled for scheduling,\n" +
"in milliseconds. This may be modified by an exponential back-off if failures persist.",
"llap.task.scheduler.node.re-enable.max.timeout.ms"),
LLAP_TASK_SCHEDULER_NODE_DISABLE_BACK_OFF_FACTOR(
"hive.llap.task.scheduler.node.disable.backoff.factor", 1.5f,
"Backoff factor on successive blacklists of a node due to some failures. Blacklist times\n" +
"start at the min timeout and go up to the max timeout based on this backoff factor.",
"llap.task.scheduler.node.disable.backoff.factor"),
LLAP_TASK_SCHEDULER_PREEMPT_INDEPENDENT("hive.llap.task.scheduler.preempt.independent", false,
"Whether the AM LLAP scheduler should preempt a lower priority task for a higher pri one\n" +
"even if the former doesn't depend on the latter (e.g. for two parallel sides of a union)."),
LLAP_TASK_SCHEDULER_NUM_SCHEDULABLE_TASKS_PER_NODE(
"hive.llap.task.scheduler.num.schedulable.tasks.per.node", 0,
"The number of tasks the AM TaskScheduler will try allocating per node. 0 indicates that\n" +
"this should be picked up from the Registry. -1 indicates unlimited capacity; positive\n" +
"values indicate a specific bound.", "llap.task.scheduler.num.schedulable.tasks.per.node"),
LLAP_TASK_SCHEDULER_LOCALITY_DELAY(
"hive.llap.task.scheduler.locality.delay", "0ms",
new TimeValidator(TimeUnit.MILLISECONDS, -1l, true, Long.MAX_VALUE, true),
"Amount of time to wait before allocating a request which contains location information," +
" to a location other than the ones requested. Set to -1 for an infinite delay, 0" +
"for no delay."
),
LLAP_DAEMON_TASK_PREEMPTION_METRICS_INTERVALS(
"hive.llap.daemon.task.preemption.metrics.intervals", "30,60,300",
"Comma-delimited set of integers denoting the desired rollover intervals (in seconds)\n" +
" for percentile latency metrics. Used by LLAP daemon task scheduler metrics for\n" +
" time taken to kill task (due to pre-emption) and useful time wasted by the task that\n" +
" is about to be preempted."
),
LLAP_DAEMON_TASK_SCHEDULER_WAIT_QUEUE_SIZE("hive.llap.daemon.task.scheduler.wait.queue.size",
10, "LLAP scheduler maximum queue size.", "llap.daemon.task.scheduler.wait.queue.size"),
LLAP_DAEMON_WAIT_QUEUE_COMPARATOR_CLASS_NAME(
"hive.llap.daemon.wait.queue.comparator.class.name",
"org.apache.hadoop.hive.llap.daemon.impl.comparator.ShortestJobFirstComparator",
"The priority comparator to use for LLAP scheduler priority queue. The built-in options\n" +
"are org.apache.hadoop.hive.llap.daemon.impl.comparator.ShortestJobFirstComparator and\n" +
".....FirstInFirstOutComparator", "llap.daemon.wait.queue.comparator.class.name"),
LLAP_DAEMON_TASK_SCHEDULER_ENABLE_PREEMPTION(
"hive.llap.daemon.task.scheduler.enable.preemption", true,
"Whether non-finishable running tasks (e.g. a reducer waiting for inputs) should be\n" +
"preempted by finishable tasks inside LLAP scheduler.",
"llap.daemon.task.scheduler.enable.preemption"),
LLAP_DAEMON_METRICS_TIMED_WINDOW_AVERAGE_DATA_POINTS(
"hive.llap.daemon.metrics.timed.window.average.data.points", 0,
"The number of data points stored for calculating executor metrics timed averages.\n" +
"Currently used for ExecutorNumExecutorsAvailableAverage and ExecutorNumQueuedRequestsAverage\n" +
"0 means that average calculation is turned off"),
LLAP_DAEMON_METRICS_TIMED_WINDOW_AVERAGE_WINDOW_LENGTH(
"hive.llap.daemon.metrics.timed.window.average.window.length", "1m",
new TimeValidator(TimeUnit.NANOSECONDS),
"The length of the time window used for calculating executor metrics timed averages.\n" +
"Currently used for ExecutorNumExecutorsAvailableAverage and ExecutorNumQueuedRequestsAverage\n"),
LLAP_DAEMON_METRICS_SIMPLE_AVERAGE_DATA_POINTS(
"hive.llap.daemon.metrics.simple.average.data.points", 0,
"The number of data points stored for calculating executor metrics simple averages.\n" +
"Currently used for AverageQueueTime and AverageResponseTime\n" +
"0 means that average calculation is turned off"),
LLAP_TASK_COMMUNICATOR_CONNECTION_TIMEOUT_MS(
"hive.llap.task.communicator.connection.timeout.ms", "16000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Connection timeout (in milliseconds) before a failure to an LLAP daemon from Tez AM.",
"llap.task.communicator.connection.timeout-millis"),
LLAP_TASK_COMMUNICATOR_LISTENER_THREAD_COUNT(
"hive.llap.task.communicator.listener.thread-count", 30,
"The number of task communicator listener threads."),
LLAP_MAX_CONCURRENT_REQUESTS_PER_NODE("hive.llap.max.concurrent.requests.per.daemon", 12,
"Maximum number of concurrent requests to one daemon from Tez AM"),
LLAP_TASK_COMMUNICATOR_CONNECTION_SLEEP_BETWEEN_RETRIES_MS(
"hive.llap.task.communicator.connection.sleep.between.retries.ms", "2000ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Sleep duration (in milliseconds) to wait before retrying on error when obtaining a\n" +
"connection to LLAP daemon from Tez AM.",
"llap.task.communicator.connection.sleep-between-retries-millis"),
LLAP_TASK_UMBILICAL_SERVER_PORT("hive.llap.daemon.umbilical.port", "0",
"LLAP task umbilical server RPC port or range of ports to try in case "
+ "the first port is occupied"),
LLAP_DAEMON_WEB_PORT("hive.llap.daemon.web.port", 15002, "LLAP daemon web UI port.",
"llap.daemon.service.port"),
LLAP_DAEMON_WEB_SSL("hive.llap.daemon.web.ssl", false,
"Whether LLAP daemon web UI should use SSL.", "llap.daemon.service.ssl"),
LLAP_DAEMON_WEB_XFRAME_ENABLED("hive.llap.daemon.web.xframe.enabled", true,
"Whether to enable xframe on LLAP daemon webUI\n"),
LLAP_DAEMON_WEB_XFRAME_VALUE("hive.llap.daemon.web.xframe.value", "SAMEORIGIN",
"Configuration to allow the user to set the x_frame-options value\n"),
LLAP_CLIENT_CONSISTENT_SPLITS("hive.llap.client.consistent.splits", true,
"Whether to setup split locations to match nodes on which llap daemons are running, " +
"instead of using the locations provided by the split itself. If there is no llap daemon " +
"running, fall back to locations provided by the split. This is effective only if " +
"hive.execution.mode is llap"),
LLAP_SPLIT_LOCATION_PROVIDER_CLASS("hive.llap.split.location.provider.class",
"org.apache.hadoop.hive.ql.exec.tez.HostAffinitySplitLocationProvider",
"Split location provider class to use during split generation for LLAP. This class should implement\n" +
"org.apache.hadoop.mapred.split.SplitLocationProvider interface"),
LLAP_VALIDATE_ACLS("hive.llap.validate.acls", true,
"Whether LLAP should reject permissive ACLs in some cases (e.g. its own management\n" +
"protocol or ZK paths), similar to how ssh refuses a key with bad access permissions."),
LLAP_DAEMON_OUTPUT_SERVICE_PORT("hive.llap.daemon.output.service.port", 15003,
"LLAP daemon output service port"),
LLAP_DAEMON_OUTPUT_STREAM_TIMEOUT("hive.llap.daemon.output.stream.timeout", "120s",
new TimeValidator(TimeUnit.SECONDS),
"The timeout for the client to connect to LLAP output service and start the fragment\n" +
"output after sending the fragment. The fragment will fail if its output is not claimed."),
LLAP_DAEMON_OUTPUT_SERVICE_SEND_BUFFER_SIZE("hive.llap.daemon.output.service.send.buffer.size",
128 * 1024, "Send buffer size to be used by LLAP daemon output service"),
LLAP_DAEMON_OUTPUT_SERVICE_MAX_PENDING_WRITES("hive.llap.daemon.output.service.max.pending.writes",
8, "Maximum number of queued writes allowed per connection when sending data\n" +
" via the LLAP output service to external clients."),
LLAP_EXTERNAL_SPLITS_TEMP_TABLE_STORAGE_FORMAT("hive.llap.external.splits.temp.table.storage.format",
"orc", new StringSet("default", "text", "orc"),
"Storage format for temp tables created using LLAP external client"),
LLAP_EXTERNAL_SPLITS_ORDER_BY_FORCE_SINGLE_SPLIT("hive.llap.external.splits.order.by.force.single.split",
true,
"If LLAP external clients submits ORDER BY queries, force return a single split to guarantee reading\n" +
"data out in ordered way. Setting this to false will let external clients read data out in parallel\n" +
"losing the ordering (external clients are responsible for guaranteeing the ordering)"),
LLAP_EXTERNAL_CLIENT_USE_HYBRID_CALENDAR("hive.llap.external.client.use.hybrid.calendar",
false,
"Whether to use hybrid calendar for parsing of data/timestamps."),
// ====== confs for llap-external-client cloud deployment ======
LLAP_EXTERNAL_CLIENT_CLOUD_DEPLOYMENT_SETUP_ENABLED(
"hive.llap.external.client.cloud.deployment.setup.enabled", false,
"Tells whether to enable additional RPC port, auth mechanism for llap external clients. This is meant"
+ "for cloud based deployments. When true, it has following effects - \n"
+ "1. Enables an extra RPC port on LLAP daemon to accept fragments from external clients. See"
+ "hive.llap.external.client.cloud.rpc.port\n"
+ "2. Uses external hostnames of LLAP in splits, so that clients can submit from outside of cloud. "
+ "Env variable PUBLIC_HOSTNAME should be available on LLAP machines.\n"
+ "3. Uses JWT based authentication for splits to be validated at LLAP. See "
+ "hive.llap.external.client.cloud.jwt.shared.secret.provider"),
LLAP_EXTERNAL_CLIENT_CLOUD_RPC_PORT("hive.llap.external.client.cloud.rpc.port", 30004,
"The LLAP daemon RPC port for external clients when llap is running in cloud environment."),
LLAP_EXTERNAL_CLIENT_CLOUD_OUTPUT_SERVICE_PORT("hive.llap.external.client.cloud.output.service.port", 30005,
"LLAP output service port when llap is running in cloud environment"),
LLAP_EXTERNAL_CLIENT_CLOUD_JWT_SHARED_SECRET_PROVIDER(
"hive.llap.external.client.cloud.jwt.shared.secret.provider",
"org.apache.hadoop.hive.llap.security.DefaultJwtSharedSecretProvider",
"Shared secret provider to be used to sign JWT"),
LLAP_EXTERNAL_CLIENT_CLOUD_JWT_SHARED_SECRET("hive.llap.external.client.cloud.jwt.shared.secret",
"",
"The LLAP daemon RPC port for external clients when llap is running in cloud environment. "
+ "Length of the secret should be >= 32 bytes"),
// ====== confs for llap-external-client cloud deployment ======
LLAP_ENABLE_GRACE_JOIN_IN_LLAP("hive.llap.enable.grace.join.in.llap", false,
"Override if grace join should be allowed to run in llap."),
LLAP_HS2_ENABLE_COORDINATOR("hive.llap.hs2.coordinator.enabled", true,
"Whether to create the LLAP coordinator; since execution engine and container vs llap\n" +
"settings are both coming from job configs, we don't know at start whether this should\n" +
"be created. Default true."),
LLAP_DAEMON_LOGGER("hive.llap.daemon.logger", Constants.LLAP_LOGGER_NAME_QUERY_ROUTING,
new StringSet(Constants.LLAP_LOGGER_NAME_QUERY_ROUTING,
Constants.LLAP_LOGGER_NAME_RFA,
Constants.LLAP_LOGGER_NAME_CONSOLE),
"logger used for llap-daemons."),
LLAP_OUTPUT_FORMAT_ARROW("hive.llap.output.format.arrow", true,
"Whether LLapOutputFormatService should output arrow batches"),
LLAP_COLLECT_LOCK_METRICS("hive.llap.lockmetrics.collect", false,
"Whether lock metrics (wait times, counts) are collected for LLAP "
+ "related locks"),
LLAP_TASK_TIME_SUMMARY(
"hive.llap.task.time.print.summary", false,
"Display queue and runtime of tasks by host for every query executed by the shell."),
HIVE_TRIGGER_VALIDATION_INTERVAL("hive.trigger.validation.interval", "500ms",
new TimeValidator(TimeUnit.MILLISECONDS),
"Interval for validating triggers during execution of a query. Triggers defined in resource plan will get\n" +
"validated for all SQL operations after every defined interval (default: 500ms) and corresponding action\n" +
"defined in the trigger will be taken"),
SPARK_USE_OP_STATS("hive.spark.use.op.stats", true,
"Whether to use operator stats to determine reducer parallelism for Hive on Spark.\n" +
"If this is false, Hive will use source table stats to determine reducer\n" +
"parallelism for all first level reduce tasks, and the maximum reducer parallelism\n" +
"from all parents for all the rest (second level and onward) reducer tasks."),
SPARK_USE_TS_STATS_FOR_MAPJOIN("hive.spark.use.ts.stats.for.mapjoin", false,
"If this is set to true, mapjoin optimization in Hive/Spark will use statistics from\n" +
"TableScan operators at the root of operator tree, instead of parent ReduceSink\n" +
"operators of the Join operator."),
SPARK_OPTIMIZE_SHUFFLE_SERDE("hive.spark.optimize.shuffle.serde", true,
"If this is set to true, Hive on Spark will register custom serializers for data types\n" +
"in shuffle. This should result in less shuffled data."),
SPARK_CLIENT_FUTURE_TIMEOUT("hive.spark.client.future.timeout",
"60s", new TimeValidator(TimeUnit.SECONDS),
"Timeout for requests between Hive client and remote Spark driver."),
SPARK_JOB_MONITOR_TIMEOUT("hive.spark.job.monitor.timeout",
"60s", new TimeValidator(TimeUnit.SECONDS),
"Timeout for job monitor to get Spark job state."),
SPARK_RPC_CLIENT_CONNECT_TIMEOUT("hive.spark.client.connect.timeout",
"1000ms", new TimeValidator(TimeUnit.MILLISECONDS),
"Timeout for remote Spark driver in connecting back to Hive client."),
SPARK_RPC_CLIENT_HANDSHAKE_TIMEOUT("hive.spark.client.server.connect.timeout",
"90000ms", new TimeValidator(TimeUnit.MILLISECONDS),
"Timeout for handshake between Hive client and remote Spark driver. Checked by both processes."),
SPARK_RPC_SECRET_RANDOM_BITS("hive.spark.client.secret.bits", "256",
"Number of bits of randomness in the generated secret for communication between Hive client and remote Spark driver. " +
"Rounded down to the nearest multiple of 8."),
SPARK_RPC_MAX_THREADS("hive.spark.client.rpc.threads", 8,
"Maximum number of threads for remote Spark driver's RPC event loop."),
SPARK_RPC_MAX_MESSAGE_SIZE("hive.spark.client.rpc.max.size", 50 * 1024 * 1024,
"Maximum message size in bytes for communication between Hive client and remote Spark driver. Default is 50MB."),
SPARK_RPC_CHANNEL_LOG_LEVEL("hive.spark.client.channel.log.level", null,
"Channel logging level for remote Spark driver. One of {DEBUG, ERROR, INFO, TRACE, WARN}."),
SPARK_RPC_SASL_MECHANISM("hive.spark.client.rpc.sasl.mechanisms", "DIGEST-MD5",
"Name of the SASL mechanism to use for authentication."),
SPARK_RPC_SERVER_ADDRESS("hive.spark.client.rpc.server.address", "",
"The server address of HiverServer2 host to be used for communication between Hive client and remote Spark driver. " +
"Default is empty, which means the address will be determined in the same way as for hive.server2.thrift.bind.host." +
"This is only necessary if the host has multiple network addresses and if a different network address other than " +
"hive.server2.thrift.bind.host is to be used."),
SPARK_RPC_SERVER_PORT("hive.spark.client.rpc.server.port", "", "A list of port ranges which can be used by RPC server " +
"with the format of 49152-49222,49228 and a random one is selected from the list. Default is empty, which randomly " +
"selects one port from all available ones."),
SPARK_DYNAMIC_PARTITION_PRUNING(
"hive.spark.dynamic.partition.pruning", false,
"When dynamic pruning is enabled, joins on partition keys will be processed by writing\n" +
"to a temporary HDFS file, and read later for removing unnecessary partitions."),
SPARK_DYNAMIC_PARTITION_PRUNING_MAX_DATA_SIZE(
"hive.spark.dynamic.partition.pruning.max.data.size", 100*1024*1024L,
"Maximum total data size in dynamic pruning."),
SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY(
"hive.spark.dynamic.partition.pruning.map.join.only", false,
"Turn on dynamic partition pruning only for map joins.\n" +
"If hive.spark.dynamic.partition.pruning is set to true, this parameter value is ignored."),
SPARK_USE_GROUPBY_SHUFFLE(
"hive.spark.use.groupby.shuffle", true,
"Spark groupByKey transformation has better performance but uses unbounded memory." +
"Turn this off when there is a memory issue."),
SPARK_JOB_MAX_TASKS("hive.spark.job.max.tasks", -1, "The maximum number of tasks a Spark job may have.\n" +
"If a Spark job contains more tasks than the maximum, it will be cancelled. A value of -1 means no limit."),
SPARK_STAGE_MAX_TASKS("hive.spark.stage.max.tasks", -1, "The maximum number of tasks a stage in a Spark job may have.\n" +
"If a Spark job stage contains more tasks than the maximum, the job will be cancelled. A value of -1 means no limit."),
SPARK_CLIENT_TYPE("hive.spark.client.type", HIVE_SPARK_SUBMIT_CLIENT,
"Controls how the Spark application is launched. If " + HIVE_SPARK_SUBMIT_CLIENT + " is " +
"specified (default) then the spark-submit shell script is used to launch the Spark " +
"app. If " + HIVE_SPARK_LAUNCHER_CLIENT + " is specified then Spark's " +
"InProcessLauncher is used to programmatically launch the app."),
SPARK_SESSION_TIMEOUT("hive.spark.session.timeout", "30m", new TimeValidator(TimeUnit.MINUTES,
30L, true, null, true), "Amount of time the Spark Remote Driver should wait for " +
" a Spark job to be submitted before shutting down. Minimum value is 30 minutes"),
SPARK_SESSION_TIMEOUT_PERIOD("hive.spark.session.timeout.period", "60s",
new TimeValidator(TimeUnit.SECONDS, 60L, true, null, true),
"How frequently to check for idle Spark sessions. Minimum value is 60 seconds."),
NWAYJOINREORDER("hive.reorder.nway.joins", true,
"Runs reordering of tables within single n-way join (i.e.: picks streamtable)"),
HIVE_MERGE_NWAY_JOINS("hive.merge.nway.joins", false,
"Merge adjacent joins into a single n-way join"),
HIVE_LOG_N_RECORDS("hive.log.every.n.records", 0L, new RangeValidator(0L, null),
"If value is greater than 0 logs in fixed intervals of size n rather than exponentially."),
/**
* @deprecated Use MetastoreConf.MSCK_PATH_VALIDATION
*/
@Deprecated
HIVE_MSCK_PATH_VALIDATION("hive.msck.path.validation", "throw",
new StringSet("throw", "skip", "ignore"), "The approach msck should take with HDFS " +
"directories that are partition-like but contain unsupported characters. 'throw' (an " +
"exception) is the default; 'skip' will skip the invalid directories and still repair the" +
" others; 'ignore' will skip the validation (legacy behavior, causes bugs in many cases)"),
/**
* @deprecated Use MetastoreConf.MSCK_REPAIR_BATCH_SIZE
*/
@Deprecated
HIVE_MSCK_REPAIR_BATCH_SIZE(
"hive.msck.repair.batch.size", 3000,
"Batch size for the msck repair command. If the value is greater than zero,\n "
+ "it will execute batch wise with the configured batch size. In case of errors while\n"
+ "adding unknown partitions the batch size is automatically reduced by half in the subsequent\n"
+ "retry attempt. The default value is 3000 which means it will execute in the batches of 3000."),
/**
* @deprecated Use MetastoreConf.MSCK_REPAIR_BATCH_MAX_RETRIES
*/
@Deprecated
HIVE_MSCK_REPAIR_BATCH_MAX_RETRIES("hive.msck.repair.batch.max.retries", 4,
"Maximum number of retries for the msck repair command when adding unknown partitions.\n "
+ "If the value is greater than zero it will retry adding unknown partitions until the maximum\n"
+ "number of attempts is reached or batch size is reduced to 0, whichever is earlier.\n"
+ "In each retry attempt it will reduce the batch size by a factor of 2 until it reaches zero.\n"
+ "If the value is set to zero it will retry until the batch size becomes zero as described above."),
HIVE_SERVER2_LLAP_CONCURRENT_QUERIES("hive.server2.llap.concurrent.queries", -1,
"The number of queries allowed in parallel via llap. Negative number implies 'infinite'."),
HIVE_TEZ_ENABLE_MEMORY_MANAGER("hive.tez.enable.memory.manager", true,
"Enable memory manager for tez"),
HIVE_HASH_TABLE_INFLATION_FACTOR("hive.hash.table.inflation.factor", (float) 2.0,
"Expected inflation factor between disk/in memory representation of hash tables"),
HIVE_LOG_TRACE_ID("hive.log.trace.id", "",
"Log tracing id that can be used by upstream clients for tracking respective logs. " +
"Truncated to " + LOG_PREFIX_LENGTH + " characters. Defaults to use auto-generated session id."),
HIVE_MM_AVOID_GLOBSTATUS_ON_S3("hive.mm.avoid.s3.globstatus", true,
"Whether to use listFiles (optimized on S3) instead of globStatus when on S3."),
// If a parameter is added to the restricted list, add a test in TestRestrictedList.Java
HIVE_CONF_RESTRICTED_LIST("hive.conf.restricted.list",
"hive.security.authenticator.manager,hive.security.authorization.manager," +
"hive.security.metastore.authorization.manager,hive.security.metastore.authenticator.manager," +
"hive.users.in.admin.role,hive.server2.xsrf.filter.enabled,hive.security.authorization.enabled," +
"hive.distcp.privileged.doAs," +
"hive.server2.authentication.ldap.baseDN," +
"hive.server2.authentication.ldap.url," +
"hive.server2.authentication.ldap.Domain," +
"hive.server2.authentication.ldap.groupDNPattern," +
"hive.server2.authentication.ldap.groupFilter," +
"hive.server2.authentication.ldap.userDNPattern," +
"hive.server2.authentication.ldap.userFilter," +
"hive.server2.authentication.ldap.groupMembershipKey," +
"hive.server2.authentication.ldap.userMembershipKey," +
"hive.server2.authentication.ldap.groupClassKey," +
"hive.server2.authentication.ldap.customLDAPQuery," +
"hive.privilege.synchronizer," +
"hive.privilege.synchronizer.interval," +
"hive.spark.client.connect.timeout," +
"hive.spark.client.server.connect.timeout," +
"hive.spark.client.channel.log.level," +
"hive.spark.client.rpc.max.size," +
"hive.spark.client.rpc.threads," +
"hive.spark.client.secret.bits," +
"hive.query.max.length," +
"hive.spark.client.rpc.server.address," +
"hive.spark.client.rpc.server.port," +
"hive.spark.client.rpc.sasl.mechanisms," +
"hive.druid.broker.address.default," +
"hive.druid.coordinator.address.default," +
"hikaricp.," +
"hadoop.bin.path," +
"yarn.bin.path," +
"spark.home," +
"hive.driver.parallel.compilation.global.limit," +
"hive.zookeeper.ssl.keystore.location," +
"hive.zookeeper.ssl.keystore.password," +
"hive.zookeeper.ssl.truststore.location," +
"hive.zookeeper.ssl.truststore.password",
"Comma separated list of configuration options which are immutable at runtime"),
HIVE_CONF_HIDDEN_LIST("hive.conf.hidden.list",
METASTOREPWD.varname + "," + HIVE_SERVER2_SSL_KEYSTORE_PASSWORD.varname
+ "," + DRUID_METADATA_DB_PASSWORD.varname
// Adding the S3 credentials from Hadoop config to be hidden
+ ",fs.s3.awsAccessKeyId"
+ ",fs.s3.awsSecretAccessKey"
+ ",fs.s3n.awsAccessKeyId"
+ ",fs.s3n.awsSecretAccessKey"
+ ",fs.s3a.access.key"
+ ",fs.s3a.secret.key"
+ ",fs.s3a.proxy.password"
+ ",dfs.adls.oauth2.credential"
+ ",fs.adl.oauth2.credential"
+ ",fs.azure.account.oauth2.client.secret"
+ ",hive.zookeeper.ssl.keystore.location"
+ ",hive.zookeeper.ssl.keystore.password"
+ ",hive.zookeeper.ssl.truststore.location"
+ ",hive.zookeeper.ssl.truststore.password",
"Comma separated list of configuration options which should not be read by normal user like passwords"),
HIVE_CONF_INTERNAL_VARIABLE_LIST("hive.conf.internal.variable.list",
"hive.added.files.path,hive.added.jars.path,hive.added.archives.path",
"Comma separated list of variables which are used internally and should not be configurable."),
HIVE_SPARK_RSC_CONF_LIST("hive.spark.rsc.conf.list",
SPARK_OPTIMIZE_SHUFFLE_SERDE.varname + "," +
SPARK_CLIENT_FUTURE_TIMEOUT.varname + "," +
SPARK_CLIENT_TYPE.varname,
"Comma separated list of variables which are related to remote spark context.\n" +
"Changing these variables will result in re-creating the spark session."),
HIVE_QUERY_MAX_LENGTH("hive.query.max.length", "10Mb", new SizeValidator(), "The maximum" +
" size of a query string. Enforced after variable substitutions."),
HIVE_QUERY_TIMEOUT_SECONDS("hive.query.timeout.seconds", "0s",
new TimeValidator(TimeUnit.SECONDS),
"Timeout for Running Query in seconds. A nonpositive value means infinite. " +
"If the query timeout is also set by thrift API call, the smaller one will be taken."),
HIVE_COMPUTE_SPLITS_NUM_THREADS("hive.compute.splits.num.threads", 10,
"How many threads Input Format should use to create splits in parallel.",
HIVE_ORC_COMPUTE_SPLITS_NUM_THREADS.varname),
HIVE_EXEC_INPUT_LISTING_MAX_THREADS("hive.exec.input.listing.max.threads", 0, new SizeValidator(0L, true, 1024L, true),
"Maximum number of threads that Hive uses to list file information from file systems (recommended > 1 for blobstore)."),
HIVE_QUERY_REEXECUTION_ENABLED("hive.query.reexecution.enabled", true,
"Enable query reexecutions"),
HIVE_QUERY_REEXECUTION_STRATEGIES("hive.query.reexecution.strategies", "overlay,reoptimize,reexecute_lost_am,dagsubmit",
"comma separated list of plugin can be used:\n"
+ " overlay: hiveconf subtree 'reexec.overlay' is used as an overlay in case of an execution errors out\n"
+ " reoptimize: collects operator statistics during execution and recompile the query after a failure\n"
+ " reexecute_lost_am: reexecutes query if it failed due to tez am node gets decommissioned"),
HIVE_QUERY_REEXECUTION_STATS_PERSISTENCE("hive.query.reexecution.stats.persist.scope", "metastore",
new StringSet("query", "hiveserver", "metastore"),
"Sets the persistence scope of runtime statistics\n"
+ " query: runtime statistics are only used during re-execution\n"
+ " hiveserver: runtime statistics are persisted in the hiveserver - all sessions share it\n"
+ " metastore: runtime statistics are persisted in the metastore as well"),
HIVE_TXN_MAX_RETRYSNAPSHOT_COUNT("hive.txn.retrysnapshot.max.count", 5, new RangeValidator(1, 20),
"Maximum number of snapshot invalidate attempts per request."),
HIVE_QUERY_MAX_REEXECUTION_COUNT("hive.query.reexecution.max.count", 1,
"Maximum number of re-executions for a single query."),
HIVE_QUERY_REEXECUTION_ALWAYS_COLLECT_OPERATOR_STATS("hive.query.reexecution.always.collect.operator.stats", false,
"If sessionstats are enabled; this option can be used to collect statistics all the time"),
HIVE_QUERY_REEXECUTION_STATS_CACHE_BATCH_SIZE("hive.query.reexecution.stats.cache.batch.size", -1,
"If runtime stats are stored in metastore; the maximal batch size per round during load."),
HIVE_QUERY_REEXECUTION_STATS_CACHE_SIZE("hive.query.reexecution.stats.cache.size", 100_000,
"Size of the runtime statistics cache. Unit is: OperatorStat entry; a query plan consist ~100."),
HIVE_QUERY_PLANMAPPER_LINK_RELNODES("hive.query.planmapper.link.relnodes", true,
"Whether to link Calcite nodes to runtime statistics."),
HIVE_SCHEDULED_QUERIES_EXECUTOR_ENABLED("hive.scheduled.queries.executor.enabled", true,
"Controls whether HS2 will run scheduled query executor."),
HIVE_SCHEDULED_QUERIES_NAMESPACE("hive.scheduled.queries.namespace", "hive",
"Sets the scheduled query namespace to be used. New scheduled queries are created in this namespace;"
+ "and execution is also bound to the namespace"),
HIVE_SCHEDULED_QUERIES_EXECUTOR_IDLE_SLEEP_TIME("hive.scheduled.queries.executor.idle.sleep.time", "60s",
new TimeValidator(TimeUnit.SECONDS),
"Time to sleep between quering for the presence of a scheduled query."),
HIVE_SCHEDULED_QUERIES_EXECUTOR_PROGRESS_REPORT_INTERVAL("hive.scheduled.queries.executor.progress.report.interval",
"60s",
new TimeValidator(TimeUnit.SECONDS),
"While scheduled queries are in flight; "
+ "a background update happens periodically to report the actual state of the query"),
HIVE_SCHEDULED_QUERIES_CREATE_AS_ENABLED("hive.scheduled.queries.create.as.enabled", true,
"This option sets the default behaviour of newly created scheduled queries."),
HIVE_SECURITY_AUTHORIZATION_SCHEDULED_QUERIES_SUPPORTED("hive.security.authorization.scheduled.queries.supported",
false,
"Enable this if the configured authorizer is able to handle scheduled query related calls."),
HIVE_SCHEDULED_QUERIES_MAX_EXECUTORS("hive.scheduled.queries.max.executors", 4, new RangeValidator(1, null),
"Maximal number of scheduled query executors to allow."),
HIVE_ASYNC_CLEANUP_SERVICE_THREAD_COUNT("hive.async.cleanup.service.thread.count", 10, new RangeValidator(0, null),
"Number of threads that run some eventual cleanup operations after queries/sessions close. 0 means cleanup is sync."),
HIVE_ASYNC_CLEANUP_SERVICE_QUEUE_SIZE("hive.async.cleanup.service.queue.size", 10000, new RangeValidator(10, Integer.MAX_VALUE),
"Size of the async cleanup queue. If cleanup queue is full, cleanup operations become synchronous. " +
"Applicable only when number of async cleanup is turned on."),
HIVE_QUERY_RESULTS_CACHE_ENABLED("hive.query.results.cache.enabled", true,
"If the query results cache is enabled. This will keep results of previously executed queries " +
"to be reused if the same query is executed again."),
HIVE_QUERY_RESULTS_CACHE_NONTRANSACTIONAL_TABLES_ENABLED("hive.query.results.cache.nontransactional.tables.enabled", false,
"If the query results cache is enabled for queries involving non-transactional tables." +
"Users who enable this setting should be willing to tolerate some amount of stale results in the cache."),
HIVE_QUERY_RESULTS_CACHE_WAIT_FOR_PENDING_RESULTS("hive.query.results.cache.wait.for.pending.results", true,
"Should a query wait for the pending results of an already running query, " +
"in order to use the cached result when it becomes ready"),
HIVE_QUERY_RESULTS_CACHE_DIRECTORY("hive.query.results.cache.directory",
"/tmp/hive/_resultscache_",
"Location of the query results cache directory. Temporary results from queries " +
"will be moved to this location."),
HIVE_QUERY_RESULTS_CACHE_MAX_ENTRY_LIFETIME("hive.query.results.cache.max.entry.lifetime", "3600s",
new TimeValidator(TimeUnit.SECONDS),
"Maximum lifetime in seconds for an entry in the query results cache. A nonpositive value means infinite."),
HIVE_QUERY_RESULTS_CACHE_MAX_SIZE("hive.query.results.cache.max.size",
(long) 2 * 1024 * 1024 * 1024,
"Maximum total size in bytes that the query results cache directory is allowed to use on the filesystem."),
HIVE_QUERY_RESULTS_CACHE_MAX_ENTRY_SIZE("hive.query.results.cache.max.entry.size",
(long) 10 * 1024 * 1024,
"Maximum size in bytes that a single query result is allowed to use in the results cache directory"),
HIVE_NOTFICATION_EVENT_POLL_INTERVAL("hive.notification.event.poll.interval", "60s",
new TimeValidator(TimeUnit.SECONDS),
"How often the notification log is polled for new NotificationEvents from the metastore." +
"A nonpositive value means the notification log is never polled."),
HIVE_NOTFICATION_EVENT_CONSUMERS("hive.notification.event.consumers",
"org.apache.hadoop.hive.ql.cache.results.QueryResultsCache$InvalidationEventConsumer",
"Comma-separated list of class names extending EventConsumer," +
"to handle the NotificationEvents retreived by the notification event poll."),
/* BLOBSTORE section */
HIVE_BLOBSTORE_SUPPORTED_SCHEMES("hive.blobstore.supported.schemes", "s3,s3a,s3n",
"Comma-separated list of supported blobstore schemes."),
HIVE_BLOBSTORE_USE_BLOBSTORE_AS_SCRATCHDIR("hive.blobstore.use.blobstore.as.scratchdir", false,
"Enable the use of scratch directories directly on blob storage systems (it may cause performance penalties)."),
HIVE_BLOBSTORE_OPTIMIZATIONS_ENABLED("hive.blobstore.optimizations.enabled", true,
"This parameter enables a number of optimizations when running on blobstores:\n" +
"(1) If hive.blobstore.use.blobstore.as.scratchdir is false, force the last Hive job to write to the blobstore.\n" +
"This is a performance optimization that forces the final FileSinkOperator to write to the blobstore.\n" +
"See HIVE-15121 for details."),
HIVE_ADDITIONAL_CONFIG_FILES("hive.additional.config.files", "",
"The names of additional config files, such as ldap-site.xml," +
"spark-site.xml, etc in comma separated list.");
public final String varname;
public final String altName;
private final String defaultExpr;
public final String defaultStrVal;
public final int defaultIntVal;
public final long defaultLongVal;
public final float defaultFloatVal;
public final boolean defaultBoolVal;
private final Class<?> valClass;
private final VarType valType;
private final Validator validator;
private final String description;
private final boolean excluded;
private final boolean caseSensitive;
ConfVars(String varname, Object defaultVal, String description) {
this(varname, defaultVal, null, description, true, false, null);
}
ConfVars(String varname, Object defaultVal, String description, String altName) {
this(varname, defaultVal, null, description, true, false, altName);
}
ConfVars(String varname, Object defaultVal, Validator validator, String description,
String altName) {
this(varname, defaultVal, validator, description, true, false, altName);
}
ConfVars(String varname, Object defaultVal, String description, boolean excluded) {
this(varname, defaultVal, null, description, true, excluded, null);
}
ConfVars(String varname, String defaultVal, boolean caseSensitive, String description) {
this(varname, defaultVal, null, description, caseSensitive, false, null);
}
ConfVars(String varname, Object defaultVal, Validator validator, String description) {
this(varname, defaultVal, validator, description, true, false, null);
}
ConfVars(String varname, Object defaultVal, Validator validator, String description, boolean excluded) {
this(varname, defaultVal, validator, description, true, excluded, null);
}
ConfVars(String varname, Object defaultVal, Validator validator, String description,
boolean caseSensitive, boolean excluded, String altName) {
this.varname = varname;
this.validator = validator;
this.description = description;
this.defaultExpr = defaultVal == null ? null : String.valueOf(defaultVal);
this.excluded = excluded;
this.caseSensitive = caseSensitive;
this.altName = altName;
if (defaultVal == null || defaultVal instanceof String) {
this.valClass = String.class;
this.valType = VarType.STRING;
this.defaultStrVal = SystemVariables.substitute((String)defaultVal);
this.defaultIntVal = -1;
this.defaultLongVal = -1;
this.defaultFloatVal = -1;
this.defaultBoolVal = false;
} else if (defaultVal instanceof Integer) {
this.valClass = Integer.class;
this.valType = VarType.INT;
this.defaultStrVal = null;
this.defaultIntVal = (Integer)defaultVal;
this.defaultLongVal = -1;
this.defaultFloatVal = -1;
this.defaultBoolVal = false;
} else if (defaultVal instanceof Long) {
this.valClass = Long.class;
this.valType = VarType.LONG;
this.defaultStrVal = null;
this.defaultIntVal = -1;
this.defaultLongVal = (Long)defaultVal;
this.defaultFloatVal = -1;
this.defaultBoolVal = false;
} else if (defaultVal instanceof Float) {
this.valClass = Float.class;
this.valType = VarType.FLOAT;
this.defaultStrVal = null;
this.defaultIntVal = -1;
this.defaultLongVal = -1;
this.defaultFloatVal = (Float)defaultVal;
this.defaultBoolVal = false;
} else if (defaultVal instanceof Boolean) {
this.valClass = Boolean.class;
this.valType = VarType.BOOLEAN;
this.defaultStrVal = null;
this.defaultIntVal = -1;
this.defaultLongVal = -1;
this.defaultFloatVal = -1;
this.defaultBoolVal = (Boolean)defaultVal;
} else {
throw new IllegalArgumentException("Not supported type value " + defaultVal.getClass() +
" for name " + varname);
}
}
public boolean isType(String value) {
return valType.isType(value);
}
public Validator getValidator() {
return validator;
}
public String validate(String value) {
return validator == null ? null : validator.validate(value);
}
public String validatorDescription() {
return validator == null ? null : validator.toDescription();
}
public String typeString() {
String type = valType.typeString();
if (valType == VarType.STRING && validator != null) {
if (validator instanceof TimeValidator) {
type += "(TIME)";
}
}
return type;
}
public String getRawDescription() {
return description;
}
public String getDescription() {
String validator = validatorDescription();
if (validator != null) {
return validator + ".\n" + description;
}
return description;
}
public boolean isExcluded() {
return excluded;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
@Override
public String toString() {
return varname;
}
private static String findHadoopBinary() {
String val = findHadoopHome();
// if can't find hadoop home we can at least try /usr/bin/hadoop
val = (val == null ? File.separator + "usr" : val)
+ File.separator + "bin" + File.separator + "hadoop";
// Launch hadoop command file on windows.
return val;
}
private static String findYarnBinary() {
String val = findHadoopHome();
val = (val == null ? "yarn" : val + File.separator + "bin" + File.separator + "yarn");
return val;
}
private static String findMapRedBinary() {
String val = findHadoopHome();
val = (val == null ? "mapred" : val + File.separator + "bin" + File.separator + "mapred");
return val;
}
private static String findHadoopHome() {
String val = System.getenv("HADOOP_HOME");
// In Hadoop 1.X and Hadoop 2.X HADOOP_HOME is gone and replaced with HADOOP_PREFIX
if (val == null) {
val = System.getenv("HADOOP_PREFIX");
}
return val;
}
public String getDefaultValue() {
return valType.defaultValueString(this);
}
public String getDefaultExpr() {
return defaultExpr;
}
private Set<String> getValidStringValues() {
if (validator == null || !(validator instanceof StringSet)) {
throw new RuntimeException(varname + " does not specify a list of valid values");
}
return ((StringSet)validator).getExpected();
}
enum VarType {
STRING {
@Override
void checkType(String value) throws Exception { }
@Override
String defaultValueString(ConfVars confVar) { return confVar.defaultStrVal; }
},
INT {
@Override
void checkType(String value) throws Exception { Integer.valueOf(value); }
},
LONG {
@Override
void checkType(String value) throws Exception { Long.valueOf(value); }
},
FLOAT {
@Override
void checkType(String value) throws Exception { Float.valueOf(value); }
},
BOOLEAN {
@Override
void checkType(String value) throws Exception { Boolean.valueOf(value); }
};
boolean isType(String value) {
try { checkType(value); } catch (Exception e) { return false; }
return true;
}
String typeString() { return name().toUpperCase();}
String defaultValueString(ConfVars confVar) { return confVar.defaultExpr; }
abstract void checkType(String value) throws Exception;
}
}
/**
* Writes the default ConfVars out to a byte array and returns an input
* stream wrapping that byte array.
*
* We need this in order to initialize the ConfVar properties
* in the underling Configuration object using the addResource(InputStream)
* method.
*
* It is important to use a LoopingByteArrayInputStream because it turns out
* addResource(InputStream) is broken since Configuration tries to read the
* entire contents of the same InputStream repeatedly without resetting it.
* LoopingByteArrayInputStream has special logic to handle this.
*/
private static synchronized InputStream getConfVarInputStream() {
if (confVarByteArray == null) {
try {
// Create a Hadoop configuration without inheriting default settings.
Configuration conf = new Configuration(false);
applyDefaultNonNullConfVars(conf);
ByteArrayOutputStream confVarBaos = new ByteArrayOutputStream();
conf.writeXml(confVarBaos);
confVarByteArray = confVarBaos.toByteArray();
} catch (Exception e) {
// We're pretty screwed if we can't load the default conf vars
throw new RuntimeException("Failed to initialize default Hive configuration variables!", e);
}
}
return new LoopingByteArrayInputStream(confVarByteArray);
}
@SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Exception before reaching NP")
public void verifyAndSet(String name, String value) throws IllegalArgumentException {
if (modWhiteListPattern != null) {
Matcher wlMatcher = modWhiteListPattern.matcher(name);
if (!wlMatcher.matches()) {
throw new IllegalArgumentException("Cannot modify " + name + " at runtime. "
+ "It is not in list of params that are allowed to be modified at runtime");
}
}
if (Iterables.any(restrictList,
restrictedVar -> name != null && name.startsWith(restrictedVar))) {
throw new IllegalArgumentException("Cannot modify " + name + " at runtime. It is in the list"
+ " of parameters that can't be modified at runtime or is prefixed by a restricted variable");
}
String oldValue = name != null ? get(name) : null;
if (name == null || value == null || !value.equals(oldValue)) {
// When either name or value is null, the set method below will fail,
// and throw IllegalArgumentException
set(name, value);
if (isSparkRelatedConfig(name)) {
isSparkConfigUpdated = true;
}
}
}
public boolean isHiddenConfig(String name) {
return Iterables.any(hiddenSet, hiddenVar -> name.startsWith(hiddenVar));
}
public static boolean isEncodedPar(String name) {
for (ConfVars confVar : HiveConf.ENCODED_CONF) {
ConfVars confVar1 = confVar;
if (confVar1.varname.equals(name)) {
return true;
}
}
return false;
}
/**
* check whether spark related property is updated, which includes spark configurations,
* RSC configurations and yarn configuration in Spark on YARN mode.
* @param name
* @return
*/
private boolean isSparkRelatedConfig(String name) {
boolean result = false;
if (name.startsWith("spark")) { // Spark property.
// for now we don't support changing spark app name on the fly
result = !name.equals("spark.app.name");
} else if (name.startsWith("yarn")) { // YARN property in Spark on YARN mode.
String sparkMaster = get("spark.master");
if (sparkMaster != null && sparkMaster.startsWith("yarn")) {
result = true;
}
} else if (rscList.stream().anyMatch(rscVar -> rscVar.equals(name))) { // Remote Spark Context property.
result = true;
} else if (name.equals("mapreduce.job.queuename")) {
// a special property starting with mapreduce that we would also like to effect if it changes
result = true;
}
return result;
}
public static int getIntVar(Configuration conf, ConfVars var) {
assert (var.valClass == Integer.class) : var.varname;
if (var.altName != null) {
return conf.getInt(var.varname, conf.getInt(var.altName, var.defaultIntVal));
}
return conf.getInt(var.varname, var.defaultIntVal);
}
public static void setIntVar(Configuration conf, ConfVars var, int val) {
assert (var.valClass == Integer.class) : var.varname;
conf.setInt(var.varname, val);
}
public int getIntVar(ConfVars var) {
return getIntVar(this, var);
}
public void setIntVar(ConfVars var, int val) {
setIntVar(this, var, val);
}
public static long getTimeVar(Configuration conf, ConfVars var, TimeUnit outUnit) {
return toTime(getVar(conf, var), getDefaultTimeUnit(var), outUnit);
}
public static void setTimeVar(Configuration conf, ConfVars var, long time, TimeUnit timeunit) {
assert (var.valClass == String.class) : var.varname;
conf.set(var.varname, time + stringFor(timeunit));
}
public long getTimeVar(ConfVars var, TimeUnit outUnit) {
return getTimeVar(this, var, outUnit);
}
public void setTimeVar(ConfVars var, long time, TimeUnit outUnit) {
setTimeVar(this, var, time, outUnit);
}
public static long getSizeVar(Configuration conf, ConfVars var) {
return toSizeBytes(getVar(conf, var));
}
public long getSizeVar(ConfVars var) {
return getSizeVar(this, var);
}
public static TimeUnit getDefaultTimeUnit(ConfVars var) {
TimeUnit inputUnit = null;
if (var.validator instanceof TimeValidator) {
inputUnit = ((TimeValidator)var.validator).getTimeUnit();
}
return inputUnit;
}
public static long toTime(String value, TimeUnit inputUnit, TimeUnit outUnit) {
String[] parsed = parseNumberFollowedByUnit(value.trim());
return outUnit.convert(Long.parseLong(parsed[0].trim()), unitFor(parsed[1].trim(), inputUnit));
}
public static long toSizeBytes(String value) {
String[] parsed = parseNumberFollowedByUnit(value.trim());
return Long.parseLong(parsed[0].trim()) * multiplierFor(parsed[1].trim());
}
private static String[] parseNumberFollowedByUnit(String value) {
char[] chars = value.toCharArray();
int i = 0;
for (; i < chars.length && (chars[i] == '-' || Character.isDigit(chars[i])); i++) {
}
return new String[] {value.substring(0, i), value.substring(i)};
}
private static Set<String> daysSet = ImmutableSet.of("d", "D", "day", "DAY", "days", "DAYS");
private static Set<String> hoursSet = ImmutableSet.of("h", "H", "hour", "HOUR", "hours", "HOURS");
private static Set<String> minutesSet = ImmutableSet.of("m", "M", "min", "MIN", "mins", "MINS",
"minute", "MINUTE", "minutes", "MINUTES");
private static Set<String> secondsSet = ImmutableSet.of("s", "S", "sec", "SEC", "secs", "SECS",
"second", "SECOND", "seconds", "SECONDS");
private static Set<String> millisSet = ImmutableSet.of("ms", "MS", "msec", "MSEC", "msecs", "MSECS",
"millisecond", "MILLISECOND", "milliseconds", "MILLISECONDS");
private static Set<String> microsSet = ImmutableSet.of("us", "US", "usec", "USEC", "usecs", "USECS",
"microsecond", "MICROSECOND", "microseconds", "MICROSECONDS");
private static Set<String> nanosSet = ImmutableSet.of("ns", "NS", "nsec", "NSEC", "nsecs", "NSECS",
"nanosecond", "NANOSECOND", "nanoseconds", "NANOSECONDS");
public static TimeUnit unitFor(String unit, TimeUnit defaultUnit) {
unit = unit.trim().toLowerCase();
if (unit.isEmpty() || unit.equals("l")) {
if (defaultUnit == null) {
throw new IllegalArgumentException("Time unit is not specified");
}
return defaultUnit;
} else if (daysSet.contains(unit)) {
return TimeUnit.DAYS;
} else if (hoursSet.contains(unit)) {
return TimeUnit.HOURS;
} else if (minutesSet.contains(unit)) {
return TimeUnit.MINUTES;
} else if (secondsSet.contains(unit)) {
return TimeUnit.SECONDS;
} else if (millisSet.contains(unit)) {
return TimeUnit.MILLISECONDS;
} else if (microsSet.contains(unit)) {
return TimeUnit.MICROSECONDS;
} else if (nanosSet.contains(unit)) {
return TimeUnit.NANOSECONDS;
}
throw new IllegalArgumentException("Invalid time unit " + unit);
}
public static long multiplierFor(String unit) {
unit = unit.trim().toLowerCase();
if (unit.isEmpty() || unit.equals("b") || unit.equals("bytes")) {
return 1;
} else if (unit.equals("kb")) {
return 1024;
} else if (unit.equals("mb")) {
return 1024*1024;
} else if (unit.equals("gb")) {
return 1024*1024*1024;
} else if (unit.equals("tb")) {
return 1024L*1024*1024*1024;
} else if (unit.equals("pb")) {
return 1024L*1024*1024*1024*1024;
}
throw new IllegalArgumentException("Invalid size unit " + unit);
}
public static String stringFor(TimeUnit timeunit) {
switch (timeunit) {
case DAYS: return "day";
case HOURS: return "hour";
case MINUTES: return "min";
case SECONDS: return "sec";
case MILLISECONDS: return "msec";
case MICROSECONDS: return "usec";
case NANOSECONDS: return "nsec";
}
throw new IllegalArgumentException("Invalid timeunit " + timeunit);
}
public static long getLongVar(Configuration conf, ConfVars var) {
assert (var.valClass == Long.class) : var.varname;
if (var.altName != null) {
return conf.getLong(var.varname, conf.getLong(var.altName, var.defaultLongVal));
}
return conf.getLong(var.varname, var.defaultLongVal);
}
public static long getLongVar(Configuration conf, ConfVars var, long defaultVal) {
if (var.altName != null) {
return conf.getLong(var.varname, conf.getLong(var.altName, defaultVal));
}
return conf.getLong(var.varname, defaultVal);
}
public static void setLongVar(Configuration conf, ConfVars var, long val) {
assert (var.valClass == Long.class) : var.varname;
conf.setLong(var.varname, val);
}
public long getLongVar(ConfVars var) {
return getLongVar(this, var);
}
public void setLongVar(ConfVars var, long val) {
setLongVar(this, var, val);
}
public static float getFloatVar(Configuration conf, ConfVars var) {
assert (var.valClass == Float.class) : var.varname;
if (var.altName != null) {
return conf.getFloat(var.varname, conf.getFloat(var.altName, var.defaultFloatVal));
}
return conf.getFloat(var.varname, var.defaultFloatVal);
}
public static float getFloatVar(Configuration conf, ConfVars var, float defaultVal) {
if (var.altName != null) {
return conf.getFloat(var.varname, conf.getFloat(var.altName, defaultVal));
}
return conf.getFloat(var.varname, defaultVal);
}
public static void setFloatVar(Configuration conf, ConfVars var, float val) {
assert (var.valClass == Float.class) : var.varname;
conf.setFloat(var.varname, val);
}
public float getFloatVar(ConfVars var) {
return getFloatVar(this, var);
}
public void setFloatVar(ConfVars var, float val) {
setFloatVar(this, var, val);
}
public static boolean getBoolVar(Configuration conf, ConfVars var) {
assert (var.valClass == Boolean.class) : var.varname;
if (var.altName != null) {
return conf.getBoolean(var.varname, conf.getBoolean(var.altName, var.defaultBoolVal));
}
return conf.getBoolean(var.varname, var.defaultBoolVal);
}
public static boolean getBoolVar(Configuration conf, ConfVars var, boolean defaultVal) {
if (var.altName != null) {
return conf.getBoolean(var.varname, conf.getBoolean(var.altName, defaultVal));
}
return conf.getBoolean(var.varname, defaultVal);
}
public static void setBoolVar(Configuration conf, ConfVars var, boolean val) {
assert (var.valClass == Boolean.class) : var.varname;
conf.setBoolean(var.varname, val);
}
/* Dynamic partition pruning is enabled in some or all cases if either
* hive.spark.dynamic.partition.pruning is true or
* hive.spark.dynamic.partition.pruning.map.join.only is true
*/
public static boolean isSparkDPPAny(Configuration conf) {
return (conf.getBoolean(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING.varname,
ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING.defaultBoolVal) ||
conf.getBoolean(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY.varname,
ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY.defaultBoolVal));
}
public boolean getBoolVar(ConfVars var) {
return getBoolVar(this, var);
}
public void setBoolVar(ConfVars var, boolean val) {
setBoolVar(this, var, val);
}
public static String getVar(Configuration conf, ConfVars var) {
assert (var.valClass == String.class) : var.varname;
return var.altName != null ? conf.get(var.varname, conf.get(var.altName, var.defaultStrVal))
: conf.get(var.varname, var.defaultStrVal);
}
public static String getVarWithoutType(Configuration conf, ConfVars var) {
return var.altName != null ? conf.get(var.varname, conf.get(var.altName, var.defaultExpr))
: conf.get(var.varname, var.defaultExpr);
}
public static String getTrimmedVar(Configuration conf, ConfVars var) {
assert (var.valClass == String.class) : var.varname;
if (var.altName != null) {
return conf.getTrimmed(var.varname, conf.getTrimmed(var.altName, var.defaultStrVal));
}
return conf.getTrimmed(var.varname, var.defaultStrVal);
}
public static String[] getTrimmedStringsVar(Configuration conf, ConfVars var) {
assert (var.valClass == String.class) : var.varname;
String[] result = conf.getTrimmedStrings(var.varname, (String[])null);
if (result != null) {
return result;
}
if (var.altName != null) {
result = conf.getTrimmedStrings(var.altName, (String[])null);
if (result != null) {
return result;
}
}
return org.apache.hadoop.util.StringUtils.getTrimmedStrings(var.defaultStrVal);
}
public static String getVar(Configuration conf, ConfVars var, String defaultVal) {
String ret = var.altName != null ? conf.get(var.varname, conf.get(var.altName, defaultVal))
: conf.get(var.varname, defaultVal);
return ret;
}
public static String getVar(Configuration conf, ConfVars var, EncoderDecoder<String, String> encoderDecoder) {
return encoderDecoder.decode(getVar(conf, var));
}
public String getLogIdVar(String defaultValue) {
String retval = getVar(ConfVars.HIVE_LOG_TRACE_ID);
if (StringUtils.EMPTY.equals(retval)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Using the default value passed in for log id: {}", defaultValue);
}
retval = defaultValue;
}
if (retval.length() > LOG_PREFIX_LENGTH) {
LOG.warn("The original log id prefix is {} has been truncated to {}", retval,
retval.substring(0, LOG_PREFIX_LENGTH - 1));
retval = retval.substring(0, LOG_PREFIX_LENGTH - 1);
}
return retval;
}
public static void setVar(Configuration conf, ConfVars var, String val) {
assert (var.valClass == String.class) : var.varname;
conf.set(var.varname, val, "setVar");
}
public static void setVar(Configuration conf, ConfVars var, String val,
EncoderDecoder<String, String> encoderDecoder) {
setVar(conf, var, encoderDecoder.encode(val));
}
public static ConfVars getConfVars(String name) {
return vars.get(name);
}
public static ConfVars getMetaConf(String name) {
return metaConfs.get(name);
}
public String getVar(ConfVars var) {
return getVar(this, var);
}
public void setVar(ConfVars var, String val) {
setVar(this, var, val);
}
public String getQueryString() {
return getQueryString(this);
}
public static String getQueryString(Configuration conf) {
return getVar(conf, ConfVars.HIVEQUERYSTRING, EncoderDecoderFactory.URL_ENCODER_DECODER);
}
public void setQueryString(String query) {
setQueryString(this, query);
}
public static void setQueryString(Configuration conf, String query) {
setVar(conf, ConfVars.HIVEQUERYSTRING, query, EncoderDecoderFactory.URL_ENCODER_DECODER);
}
public void logVars(PrintStream ps) {
for (ConfVars one : ConfVars.values()) {
ps.println(one.varname + "=" + ((get(one.varname) != null) ? get(one.varname) : ""));
}
}
/**
* @return a ZooKeeperHiveHelper instance containing the ZooKeeper specifications from the
* given HiveConf.
*/
public ZooKeeperHiveHelper getZKConfig() {
String keyStorePassword = "";
String trustStorePassword = "";
if (getBoolVar(ConfVars.HIVE_ZOOKEEPER_SSL_ENABLE)) {
try {
keyStorePassword =
ShimLoader.getHadoopShims().getPassword(this, ConfVars.HIVE_ZOOKEEPER_SSL_KEYSTORE_PASSWORD.varname);
trustStorePassword =
ShimLoader.getHadoopShims().getPassword(this, ConfVars.HIVE_ZOOKEEPER_SSL_TRUSTSTORE_PASSWORD.varname);
} catch (IOException ex) {
throw new RuntimeException("Failed to read zookeeper configuration passwords", ex);
}
}
return ZooKeeperHiveHelper.builder()
.quorum(getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_QUORUM))
.clientPort(getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CLIENT_PORT))
.serverRegistryNameSpace(getVar(HiveConf.ConfVars.HIVE_SERVER2_ZOOKEEPER_NAMESPACE))
.connectionTimeout((int) getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CONNECTION_TIMEOUT,
TimeUnit.MILLISECONDS))
.sessionTimeout((int) getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT,
TimeUnit.MILLISECONDS))
.baseSleepTime((int) getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CONNECTION_BASESLEEPTIME,
TimeUnit.MILLISECONDS))
.maxRetries(getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CONNECTION_MAX_RETRIES))
.sslEnabled(getBoolVar(ConfVars.HIVE_ZOOKEEPER_SSL_ENABLE))
.keyStoreLocation(getVar(ConfVars.HIVE_ZOOKEEPER_SSL_KEYSTORE_LOCATION))
.keyStorePassword(keyStorePassword)
.trustStoreLocation(getVar(ConfVars.HIVE_ZOOKEEPER_SSL_TRUSTSTORE_LOCATION))
.trustStorePassword(trustStorePassword).build();
}
public HiveConf() {
super();
initialize(this.getClass());
}
public HiveConf(Class<?> cls) {
super();
initialize(cls);
}
public HiveConf(Configuration other, Class<?> cls) {
super(other);
initialize(cls);
}
/**
* Copy constructor
*/
public HiveConf(HiveConf other) {
super(other);
hiveJar = other.hiveJar;
auxJars = other.auxJars;
isSparkConfigUpdated = other.isSparkConfigUpdated;
origProp = (Properties)other.origProp.clone();
restrictList.addAll(other.restrictList);
hiddenSet.addAll(other.hiddenSet);
modWhiteListPattern = other.modWhiteListPattern;
}
public Properties getAllProperties() {
return getProperties(this);
}
public static Properties getProperties(Configuration conf) {
Iterator<Map.Entry<String, String>> iter = conf.iterator();
Properties p = new Properties();
while (iter.hasNext()) {
Map.Entry<String, String> e = iter.next();
p.setProperty(e.getKey(), e.getValue());
}
return p;
}
private void initialize(Class<?> cls) {
hiveJar = (new JobConf(cls)).getJar();
// preserve the original configuration
origProp = getAllProperties();
// Overlay the ConfVars. Note that this ignores ConfVars with null values
addResource(getConfVarInputStream(), "HiveConf.java");
// Overlay hive-site.xml if it exists
if (hiveSiteURL != null) {
addResource(hiveSiteURL);
}
// if embedded metastore is to be used as per config so far
// then this is considered like the metastore server case
String msUri = this.getVar(HiveConf.ConfVars.METASTOREURIS);
// This is hackery, but having hive-common depend on standalone-metastore is really bad
// because it will pull all of the metastore code into every module. We need to check that
// we aren't using the standalone metastore. If we are, we should treat it the same as a
// remote metastore situation.
if (msUri == null || msUri.isEmpty()) {
msUri = this.get("metastore.thrift.uris");
}
LOG.debug("Found metastore URI of " + msUri);
if(HiveConfUtil.isEmbeddedMetaStore(msUri)){
setLoadMetastoreConfig(true);
}
// load hivemetastore-site.xml if this is metastore and file exists
if (isLoadMetastoreConfig() && hivemetastoreSiteUrl != null) {
addResource(hivemetastoreSiteUrl);
}
// load hiveserver2-site.xml if this is hiveserver2 and file exists
// metastore can be embedded within hiveserver2, in such cases
// the conf params in hiveserver2-site.xml will override whats defined
// in hivemetastore-site.xml
if (isLoadHiveServer2Config()) {
// set the hardcoded value first, so anything in hiveserver2-site.xml can override it
set(ConfVars.METASTORE_CLIENT_CAPABILITIES.varname, "EXTWRITE,EXTREAD,HIVEBUCKET2,HIVEFULLACIDREAD,"
+ "HIVEFULLACIDWRITE,HIVECACHEINVALIDATE,HIVEMANAGESTATS,HIVEMANAGEDINSERTWRITE,HIVEMANAGEDINSERTREAD,"
+ "HIVESQL,HIVEMQT,HIVEONLYMQTWRITE,ACCEPTS_UNMODIFIED_METADATA");
if (hiveServer2SiteUrl != null) {
addResource(hiveServer2SiteUrl);
}
}
String val = this.getVar(HiveConf.ConfVars.HIVE_ADDITIONAL_CONFIG_FILES);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (val != null && !val.isEmpty()) {
String[] configFiles = val.split(",");
for (String config : configFiles) {
URL configURL = findConfigFile(classLoader, config, true);
if (configURL != null) {
addResource(configURL);
}
}
}
// Overlay the values of any system properties and manual overrides
applySystemProperties();
if ((this.get("hive.metastore.ds.retry.attempts") != null) ||
this.get("hive.metastore.ds.retry.interval") != null) {
LOG.warn("DEPRECATED: hive.metastore.ds.retry.* no longer has any effect. " +
"Use hive.hmshandler.retry.* instead");
}
// if the running class was loaded directly (through eclipse) rather than through a
// jar then this would be needed
if (hiveJar == null) {
hiveJar = this.get(ConfVars.HIVEJAR.varname);
}
if (auxJars == null) {
auxJars = StringUtils.join(FileUtils.getJarFilesByPath(this.get(ConfVars.HIVEAUXJARS.varname), this), ',');
}
if (getBoolVar(ConfVars.METASTORE_SCHEMA_VERIFICATION)) {
setBoolVar(ConfVars.METASTORE_AUTO_CREATE_ALL, false);
}
if (getBoolVar(HiveConf.ConfVars.HIVECONFVALIDATION)) {
List<String> trimmed = new ArrayList<String>();
for (Map.Entry<String,String> entry : this) {
String key = entry.getKey();
if (key == null || !key.startsWith("hive.")) {
continue;
}
ConfVars var = HiveConf.getConfVars(key);
if (var == null) {
var = HiveConf.getConfVars(key.trim());
if (var != null) {
trimmed.add(key);
}
}
if (var == null) {
LOG.warn("HiveConf of name {} does not exist", key);
} else if (!var.isType(entry.getValue())) {
LOG.warn("HiveConf {} expects {} type value", var.varname, var.typeString());
}
}
for (String key : trimmed) {
set(key.trim(), getRaw(key));
unset(key);
}
}
setupSQLStdAuthWhiteList();
// setup list of conf vars that are not allowed to change runtime
setupRestrictList();
hiddenSet.clear();
hiddenSet.addAll(HiveConfUtil.getHiddenSet(this));
setupRSCList();
}
/**
* If the config whitelist param for sql standard authorization is not set, set it up here.
*/
private void setupSQLStdAuthWhiteList() {
String whiteListParamsStr = getVar(ConfVars.HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST);
if (whiteListParamsStr == null || whiteListParamsStr.trim().isEmpty()) {
// set the default configs in whitelist
whiteListParamsStr = getSQLStdAuthDefaultWhiteListPattern();
setVar(ConfVars.HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST, whiteListParamsStr);
}
}
private static String getSQLStdAuthDefaultWhiteListPattern() {
// create the default white list from list of safe config params
// and regex list
String confVarPatternStr = Joiner.on("|").join(convertVarsToRegex(SQL_STD_AUTH_SAFE_VAR_NAMES));
String regexPatternStr = Joiner.on("|").join(sqlStdAuthSafeVarNameRegexes);
return regexPatternStr + "|" + confVarPatternStr;
}
/**
* Obtains the local time-zone ID.
*/
public ZoneId getLocalTimeZone() {
String timeZoneStr = getVar(ConfVars.HIVE_LOCAL_TIME_ZONE);
return TimestampTZUtil.parseTimeZone(timeZoneStr);
}
/**
* @param paramList list of parameter strings
* @return list of parameter strings with "." replaced by "\."
*/
private static String[] convertVarsToRegex(String[] paramList) {
String[] regexes = new String[paramList.length];
for(int i=0; i<paramList.length; i++) {
regexes[i] = paramList[i].replace(".", "\\." );
}
return regexes;
}
/**
* Default list of modifiable config parameters for sql standard authorization
* For internal use only.
*/
private static final String[] SQL_STD_AUTH_SAFE_VAR_NAMES = new String[] {
ConfVars.AGGR_JOIN_TRANSPOSE.varname,
ConfVars.BYTESPERREDUCER.varname,
ConfVars.CLIENT_STATS_COUNTERS.varname,
ConfVars.CREATE_TABLES_AS_ACID.varname,
ConfVars.CREATE_TABLE_AS_EXTERNAL.varname,
ConfVars.DEFAULTPARTITIONNAME.varname,
ConfVars.DROP_IGNORES_NON_EXISTENT.varname,
ConfVars.HIVECOUNTERGROUP.varname,
ConfVars.HIVEDEFAULTMANAGEDFILEFORMAT.varname,
ConfVars.HIVEENFORCEBUCKETMAPJOIN.varname,
ConfVars.HIVEENFORCESORTMERGEBUCKETMAPJOIN.varname,
ConfVars.HIVEEXPREVALUATIONCACHE.varname,
ConfVars.HIVEQUERYRESULTFILEFORMAT.varname,
ConfVars.HIVEHASHTABLELOADFACTOR.varname,
ConfVars.HIVEHASHTABLETHRESHOLD.varname,
ConfVars.HIVEIGNOREMAPJOINHINT.varname,
ConfVars.HIVELIMITMAXROWSIZE.varname,
ConfVars.HIVEMAPREDMODE.varname,
ConfVars.HIVEMAPSIDEAGGREGATE.varname,
ConfVars.HIVEOPTIMIZEMETADATAQUERIES.varname,
ConfVars.HIVEROWOFFSET.varname,
ConfVars.HIVEVARIABLESUBSTITUTE.varname,
ConfVars.HIVEVARIABLESUBSTITUTEDEPTH.varname,
ConfVars.HIVE_AUTOGEN_COLUMNALIAS_PREFIX_INCLUDEFUNCNAME.varname,
ConfVars.HIVE_AUTOGEN_COLUMNALIAS_PREFIX_LABEL.varname,
ConfVars.HIVE_CHECK_CROSS_PRODUCT.varname,
ConfVars.HIVE_CLI_TEZ_SESSION_ASYNC.varname,
ConfVars.HIVE_COMPAT.varname,
ConfVars.HIVE_CREATE_TABLES_AS_INSERT_ONLY.varname,
ConfVars.HIVE_DISPLAY_PARTITION_COLUMNS_SEPARATELY.varname,
ConfVars.HIVE_ERROR_ON_EMPTY_PARTITION.varname,
ConfVars.HIVE_EXECUTION_ENGINE.varname,
ConfVars.HIVE_EXEC_COPYFILE_MAXSIZE.varname,
ConfVars.HIVE_EXIM_URI_SCHEME_WL.varname,
ConfVars.HIVE_FILE_MAX_FOOTER.varname,
ConfVars.HIVE_INSERT_INTO_MULTILEVEL_DIRS.varname,
ConfVars.HIVE_LOCALIZE_RESOURCE_NUM_WAIT_ATTEMPTS.varname,
ConfVars.HIVE_MULTI_INSERT_MOVE_TASKS_SHARE_DEPENDENCIES.varname,
ConfVars.HIVE_QUERY_RESULTS_CACHE_ENABLED.varname,
ConfVars.HIVE_QUERY_RESULTS_CACHE_WAIT_FOR_PENDING_RESULTS.varname,
ConfVars.HIVE_QUOTEDID_SUPPORT.varname,
ConfVars.HIVE_RESULTSET_USE_UNIQUE_COLUMN_NAMES.varname,
ConfVars.HIVE_STATS_COLLECT_PART_LEVEL_STATS.varname,
ConfVars.HIVE_SCHEMA_EVOLUTION.varname,
ConfVars.HIVE_SERVER2_LOGGING_OPERATION_LEVEL.varname,
ConfVars.HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS.varname,
ConfVars.HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES.varname,
ConfVars.JOB_DEBUG_CAPTURE_STACKTRACES.varname,
ConfVars.JOB_DEBUG_TIMEOUT.varname,
ConfVars.LLAP_IO_ENABLED.varname,
ConfVars.LLAP_IO_USE_FILEID_PATH.varname,
ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname,
ConfVars.LLAP_EXECUTION_MODE.varname,
ConfVars.LLAP_AUTO_ALLOW_UBER.varname,
ConfVars.LLAP_AUTO_ENFORCE_TREE.varname,
ConfVars.LLAP_AUTO_ENFORCE_VECTORIZED.varname,
ConfVars.LLAP_AUTO_ENFORCE_STATS.varname,
ConfVars.LLAP_AUTO_MAX_INPUT.varname,
ConfVars.LLAP_AUTO_MAX_OUTPUT.varname,
ConfVars.LLAP_SKIP_COMPILE_UDF_CHECK.varname,
ConfVars.LLAP_CLIENT_CONSISTENT_SPLITS.varname,
ConfVars.LLAP_ENABLE_GRACE_JOIN_IN_LLAP.varname,
ConfVars.LLAP_ALLOW_PERMANENT_FNS.varname,
ConfVars.MAXCREATEDFILES.varname,
ConfVars.MAXREDUCERS.varname,
ConfVars.NWAYJOINREORDER.varname,
ConfVars.OUTPUT_FILE_EXTENSION.varname,
ConfVars.SHOW_JOB_FAIL_DEBUG_INFO.varname,
ConfVars.TASKLOG_DEBUG_TIMEOUT.varname,
ConfVars.HIVEQUERYID.varname,
ConfVars.HIVEQUERYTAG.varname,
};
/**
* Default list of regexes for config parameters that are modifiable with
* sql standard authorization enabled
*/
static final String [] sqlStdAuthSafeVarNameRegexes = new String [] {
"hive\\.auto\\..*",
"hive\\.cbo\\..*",
"hive\\.convert\\..*",
"hive\\.druid\\..*",
"hive\\.exec\\.dynamic\\.partition.*",
"hive\\.exec\\.max\\.dynamic\\.partitions.*",
"hive\\.exec\\.compress\\..*",
"hive\\.exec\\.infer\\..*",
"hive\\.exec\\.mode.local\\..*",
"hive\\.exec\\.orc\\..*",
"hive\\.exec\\.parallel.*",
"hive\\.explain\\..*",
"hive\\.fetch.task\\..*",
"hive\\.groupby\\..*",
"hive\\.hbase\\..*",
"hive\\.index\\..*",
"hive\\.index\\..*",
"hive\\.intermediate\\..*",
"hive\\.jdbc\\..*",
"hive\\.join\\..*",
"hive\\.limit\\..*",
"hive\\.log\\..*",
"hive\\.mapjoin\\..*",
"hive\\.merge\\..*",
"hive\\.optimize\\..*",
"hive\\.materializedview\\..*",
"hive\\.orc\\..*",
"hive\\.outerjoin\\..*",
"hive\\.parquet\\..*",
"hive\\.ppd\\..*",
"hive\\.prewarm\\..*",
"hive\\.query\\.name",
"hive\\.server2\\.thrift\\.resultset\\.default\\.fetch\\.size",
"hive\\.server2\\.proxy\\.user",
"hive\\.skewjoin\\..*",
"hive\\.smbjoin\\..*",
"hive\\.stats\\..*",
"hive\\.strict\\..*",
"hive\\.tez\\..*",
"hive\\.vectorized\\..*",
"hive\\.query\\.reexecution\\..*",
"hive\\.query\\.exclusive\\.lock",
"reexec\\.overlay\\..*",
"fs\\.defaultFS",
"ssl\\.client\\.truststore\\.location",
"distcp\\.atomic",
"distcp\\.ignore\\.failures",
"distcp\\.preserve\\.status",
"distcp\\.preserve\\.rawxattrs",
"distcp\\.sync\\.folders",
"distcp\\.delete\\.missing\\.source",
"distcp\\.keystore\\.resource",
"distcp\\.liststatus\\.threads",
"distcp\\.max\\.maps",
"distcp\\.copy\\.strategy",
"distcp\\.skip\\.crc",
"distcp\\.copy\\.overwrite",
"distcp\\.copy\\.append",
"distcp\\.map\\.bandwidth\\.mb",
"distcp\\.dynamic\\..*",
"distcp\\.meta\\.folder",
"distcp\\.copy\\.listing\\.class",
"distcp\\.filters\\.class",
"distcp\\.options\\.skipcrccheck",
"distcp\\.options\\.m",
"distcp\\.options\\.numListstatusThreads",
"distcp\\.options\\.mapredSslConf",
"distcp\\.options\\.bandwidth",
"distcp\\.options\\.overwrite",
"distcp\\.options\\.strategy",
"distcp\\.options\\.i",
"distcp\\.options\\.p.*",
"distcp\\.options\\.update",
"distcp\\.options\\.delete",
"mapred\\.map\\..*",
"mapred\\.reduce\\..*",
"mapred\\.output\\.compression\\.codec",
"mapred\\.job\\.queue\\.name",
"mapred\\.output\\.compression\\.type",
"mapred\\.min\\.split\\.size",
"mapreduce\\.job\\.reduce\\.slowstart\\.completedmaps",
"mapreduce\\.job\\.queuename",
"mapreduce\\.job\\.tags",
"mapreduce\\.input\\.fileinputformat\\.split\\.minsize",
"mapreduce\\.map\\..*",
"mapreduce\\.reduce\\..*",
"mapreduce\\.output\\.fileoutputformat\\.compress\\.codec",
"mapreduce\\.output\\.fileoutputformat\\.compress\\.type",
"oozie\\..*",
"tez\\.am\\..*",
"tez\\.task\\..*",
"tez\\.runtime\\..*",
"tez\\.queue\\.name",
};
//Take care of conf overrides.
//Includes values in ConfVars as well as underlying configuration properties (ie, hadoop)
@SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION_PKGPROTECT", justification = "Intended exposure")
public static final Map<String, String> overrides = new HashMap<String, String>();
/**
* Apply system properties to this object if the property name is defined in ConfVars
* and the value is non-null and not an empty string.
*/
private void applySystemProperties() {
Map<String, String> systemProperties = getConfSystemProperties();
for (Entry<String, String> systemProperty : systemProperties.entrySet()) {
this.set(systemProperty.getKey(), systemProperty.getValue());
}
}
/**
* This method returns a mapping from config variable name to its value for all config variables
* which have been set using System properties
*/
public static Map<String, String> getConfSystemProperties() {
Map<String, String> systemProperties = new HashMap<String, String>();
for (ConfVars oneVar : ConfVars.values()) {
if (System.getProperty(oneVar.varname) != null) {
if (System.getProperty(oneVar.varname).length() > 0) {
systemProperties.put(oneVar.varname, System.getProperty(oneVar.varname));
}
}
}
for (Map.Entry<String, String> oneVar : overrides.entrySet()) {
if (overrides.get(oneVar.getKey()) != null) {
if (overrides.get(oneVar.getKey()).length() > 0) {
systemProperties.put(oneVar.getKey(), oneVar.getValue());
}
}
}
return systemProperties;
}
/**
* Overlays ConfVar properties with non-null values
*/
private static void applyDefaultNonNullConfVars(Configuration conf) {
for (ConfVars var : ConfVars.values()) {
String defaultValue = var.getDefaultValue();
if (defaultValue == null) {
// Don't override ConfVars with null values
continue;
}
conf.set(var.varname, defaultValue);
}
}
public Properties getChangedProperties() {
Properties ret = new Properties();
Properties newProp = getAllProperties();
for (Object one : newProp.keySet()) {
String oneProp = (String) one;
String oldValue = origProp.getProperty(oneProp);
if (!StringUtils.equals(oldValue, newProp.getProperty(oneProp))) {
ret.setProperty(oneProp, newProp.getProperty(oneProp));
}
}
return (ret);
}
public String getJar() {
return hiveJar;
}
/**
* @return the auxJars
*/
public String getAuxJars() {
return auxJars;
}
/**
* Set the auxiliary jars. Used for unit tests only.
* @param auxJars the auxJars to set.
*/
public void setAuxJars(String auxJars) {
this.auxJars = auxJars;
setVar(this, ConfVars.HIVEAUXJARS, auxJars);
}
public URL getHiveDefaultLocation() {
return hiveDefaultURL;
}
public static void setHiveSiteLocation(URL location) {
hiveSiteURL = location;
}
public static void setHivemetastoreSiteUrl(URL location) {
hivemetastoreSiteUrl = location;
}
public static URL getHiveSiteLocation() {
return hiveSiteURL;
}
public static URL getMetastoreSiteLocation() {
return hivemetastoreSiteUrl;
}
public static URL getHiveServer2SiteLocation() {
return hiveServer2SiteUrl;
}
/**
* @return the user name set in hadoop.job.ugi param or the current user from System
* @throws IOException
*/
public String getUser() throws IOException {
try {
UserGroupInformation ugi = Utils.getUGI();
return ugi.getUserName();
} catch (LoginException le) {
throw new IOException(le);
}
}
public static String getColumnInternalName(int pos) {
return "_col" + pos;
}
public static int getPositionFromInternalName(String internalName) {
Pattern internalPattern = Pattern.compile("_col([0-9]+)");
Matcher m = internalPattern.matcher(internalName);
if (!m.matches()){
return -1;
} else {
return Integer.parseInt(m.group(1));
}
}
/**
* Append comma separated list of config vars to the restrict List
* @param restrictListStr
*/
public void addToRestrictList(String restrictListStr) {
if (restrictListStr == null) {
return;
}
String oldList = this.getVar(ConfVars.HIVE_CONF_RESTRICTED_LIST);
if (oldList == null || oldList.isEmpty()) {
this.setVar(ConfVars.HIVE_CONF_RESTRICTED_LIST, restrictListStr);
} else {
this.setVar(ConfVars.HIVE_CONF_RESTRICTED_LIST, oldList + "," + restrictListStr);
}
setupRestrictList();
}
/**
* Set white list of parameters that are allowed to be modified
*
* @param paramNameRegex
*/
@LimitedPrivate(value = { "Currently only for use by HiveAuthorizer" })
public void setModifiableWhiteListRegex(String paramNameRegex) {
if (paramNameRegex == null) {
return;
}
modWhiteListPattern = Pattern.compile(paramNameRegex);
}
/**
* Add the HIVE_CONF_RESTRICTED_LIST values to restrictList,
* including HIVE_CONF_RESTRICTED_LIST itself
*/
private void setupRestrictList() {
String restrictListStr = this.getVar(ConfVars.HIVE_CONF_RESTRICTED_LIST);
restrictList.clear();
if (restrictListStr != null) {
for (String entry : restrictListStr.split(",")) {
restrictList.add(entry.trim());
}
}
String internalVariableListStr = this.getVar(ConfVars.HIVE_CONF_INTERNAL_VARIABLE_LIST);
if (internalVariableListStr != null) {
for (String entry : internalVariableListStr.split(",")) {
restrictList.add(entry.trim());
}
}
restrictList.add(ConfVars.HIVE_IN_TEST.varname);
restrictList.add(ConfVars.HIVE_CONF_RESTRICTED_LIST.varname);
restrictList.add(ConfVars.HIVE_CONF_HIDDEN_LIST.varname);
restrictList.add(ConfVars.HIVE_CONF_INTERNAL_VARIABLE_LIST.varname);
restrictList.add(ConfVars.HIVE_SPARK_RSC_CONF_LIST.varname);
}
private void setupRSCList() {
rscList.clear();
String vars = this.getVar(ConfVars.HIVE_SPARK_RSC_CONF_LIST);
if (vars != null) {
for (String var : vars.split(",")) {
rscList.add(var.trim());
}
}
}
/**
* Strips hidden config entries from configuration
*/
public void stripHiddenConfigurations(Configuration conf) {
HiveConfUtil.stripConfigurations(conf, hiddenSet);
}
/**
* @return true if HS2 webui is enabled
*/
public boolean isWebUiEnabled() {
return this.getIntVar(ConfVars.HIVE_SERVER2_WEBUI_PORT) != 0;
}
/**
* @return true if HS2 webui query-info cache is enabled
*/
public boolean isWebUiQueryInfoCacheEnabled() {
return isWebUiEnabled() && this.getIntVar(ConfVars.HIVE_SERVER2_WEBUI_MAX_HISTORIC_QUERIES) > 0;
}
/* Dynamic partition pruning is enabled in some or all cases
*/
public boolean isSparkDPPAny() {
return isSparkDPPAny(this);
}
/* Dynamic partition pruning is enabled only for map join
* hive.spark.dynamic.partition.pruning is false and
* hive.spark.dynamic.partition.pruning.map.join.only is true
*/
public boolean isSparkDPPOnlyMapjoin() {
return (!this.getBoolVar(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING) &&
this.getBoolVar(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY));
}
public static boolean isLoadMetastoreConfig() {
return loadMetastoreConfig;
}
public static void setLoadMetastoreConfig(boolean loadMetastoreConfig) {
HiveConf.loadMetastoreConfig = loadMetastoreConfig;
}
public static boolean isLoadHiveServer2Config() {
return loadHiveServer2Config;
}
public static void setLoadHiveServer2Config(boolean loadHiveServer2Config) {
HiveConf.loadHiveServer2Config = loadHiveServer2Config;
}
public static class StrictChecks {
private static final String NO_LIMIT_MSG = makeMessage(
"Order by-s without limit", ConfVars.HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT);
public static final String NO_PARTITIONLESS_MSG = makeMessage(
"Queries against partitioned tables without a partition filter",
ConfVars.HIVE_STRICT_CHECKS_NO_PARTITION_FILTER);
private static final String NO_COMPARES_MSG = makeMessage(
"Unsafe compares between different types", ConfVars.HIVE_STRICT_CHECKS_TYPE_SAFETY);
private static final String NO_CARTESIAN_MSG = makeMessage(
"Cartesian products", ConfVars.HIVE_STRICT_CHECKS_CARTESIAN);
private static final String NO_BUCKETING_MSG = makeMessage(
"Load into bucketed tables", ConfVars.HIVE_STRICT_CHECKS_BUCKETING);
private static String makeMessage(String what, ConfVars setting) {
return what + " are disabled for safety reasons. If you know what you are doing, please set "
+ setting.varname + " to false and make sure that " + ConfVars.HIVEMAPREDMODE.varname +
" is not set to 'strict' to proceed. Note that you may get errors or incorrect " +
"results if you make a mistake while using some of the unsafe features.";
}
public static String checkNoLimit(Configuration conf) {
return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT) ? null : NO_LIMIT_MSG;
}
public static String checkNoPartitionFilter(Configuration conf) {
return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_NO_PARTITION_FILTER)
? null : NO_PARTITIONLESS_MSG;
}
public static String checkTypeSafety(Configuration conf) {
return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_TYPE_SAFETY) ? null : NO_COMPARES_MSG;
}
public static String checkCartesian(Configuration conf) {
return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_CARTESIAN) ? null : NO_CARTESIAN_MSG;
}
public static String checkBucketing(Configuration conf) {
return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_BUCKETING) ? null : NO_BUCKETING_MSG;
}
private static boolean isAllowed(Configuration conf, ConfVars setting) {
String mode = HiveConf.getVar(conf, ConfVars.HIVEMAPREDMODE, (String)null);
return (mode != null) ? !"strict".equals(mode) : !HiveConf.getBoolVar(conf, setting);
}
}
public static String getNonMrEngines() {
Set<String> engines = new HashSet<>(ConfVars.HIVE_EXECUTION_ENGINE.getValidStringValues());
engines.remove("mr");
String validNonMrEngines = String.join(", ", engines);
LOG.debug("Valid non-MapReduce execution engines: {}", validNonMrEngines);
return validNonMrEngines;
}
public static String generateMrDeprecationWarning() {
return "Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. "
+ "Consider using a different execution engine (i.e. " + HiveConf.getNonMrEngines()
+ ") or using Hive 1.X releases.";
}
public static String generateDeprecationWarning() {
return "This config will be deprecated and may not be available in the future "
+ "versions. Please adjust DDL towards the new semantics.";
}
private static final Object reverseMapLock = new Object();
private static HashMap<String, ConfVars> reverseMap = null;
public static HashMap<String, ConfVars> getOrCreateReverseMap() {
// This should be called rarely enough; for now it's ok to just lock every time.
synchronized (reverseMapLock) {
if (reverseMap != null) {
return reverseMap;
}
}
HashMap<String, ConfVars> vars = new HashMap<>();
for (ConfVars val : ConfVars.values()) {
vars.put(val.varname.toLowerCase(), val);
if (val.altName != null && !val.altName.isEmpty()) {
vars.put(val.altName.toLowerCase(), val);
}
}
synchronized (reverseMapLock) {
if (reverseMap != null) {
return reverseMap;
}
reverseMap = vars;
return reverseMap;
}
}
public void verifyAndSetAll(Map<String, String> overlay) {
for (Entry<String, String> entry : overlay.entrySet()) {
verifyAndSet(entry.getKey(), entry.getValue());
}
}
public Map<String, String> subtree(String string) {
Map<String, String> ret = new HashMap<>();
for (Entry<Object, Object> entry : getProps().entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (key.startsWith(string)) {
ret.put(key.substring(string.length() + 1), value);
}
}
return ret;
}
// sync all configs from given conf
public void syncFromConf(HiveConf conf) {
Iterator<Map.Entry<String, String>> iter = conf.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> e = iter.next();
set(e.getKey(), e.getValue());
}
}
}
|
[
"\"HIVE_CONF_DIR\"",
"\"HIVE_HOME\"",
"\"HADOOP_HOME\"",
"\"HADOOP_PREFIX\""
] |
[] |
[
"HADOOP_PREFIX",
"HADOOP_HOME",
"HIVE_CONF_DIR",
"HIVE_HOME"
] |
[]
|
["HADOOP_PREFIX", "HADOOP_HOME", "HIVE_CONF_DIR", "HIVE_HOME"]
|
java
| 4 | 0 | |
openstack/port-status/port-status.go
|
package main
import (
"fmt"
"os"
"time"
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/openstack"
"github.com/rackspace/gophercloud/openstack/networking/v2/ports"
"github.com/rackspace/gophercloud/pagination"
)
const (
portID = "888c106c-dbd2-46de-89c8-24c9e5dc2729"
)
func main() {
auth_opts, err := openstack.AuthOptionsFromEnv()
provider, err := openstack.AuthenticatedClient(auth_opts)
if err != nil {
fmt.Println("Authentication error: ", err)
os.Exit(1)
}
client, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
if err != nil {
fmt.Println("Get neutron client error:", err)
os.Exit(1)
}
for i := 0; i < 100; i++ {
p, err := ports.Get(client, portID).Extract()
if err != nil {
fmt.Println("Get neutron port error:", err)
os.Exit(1)
}
fmt.Printf("Port %q status %q\n", p.ID, p.Status)
time.Sleep(100 * time.Millisecond)
}
var results []ports.Port
listOpts := ports.ListOpts{ID: portID}
portPager := ports.List(client, listOpts)
err = portPager.EachPage(func(page pagination.Page) (bool, error) {
portList, err := ports.ExtractPorts(page)
if err != nil {
fmt.Println("Get openstack ports error: %v", err)
return false, err
}
for _, port := range portList {
results = append(results, port)
}
return true, err
})
if err != nil {
fmt.Printf("Get ports error: %s", err)
os.Exit(1)
}
for _, p := range results {
fmt.Println(p.ID, p.Status)
}
}
|
[
"\"OS_REGION_NAME\""
] |
[] |
[
"OS_REGION_NAME"
] |
[]
|
["OS_REGION_NAME"]
|
go
| 1 | 0 | |
platform/util/testSrc/com/intellij/util/EnvironmentUtilTest.java
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import org.junit.Test;
import java.io.File;
import java.util.Collections;
import java.util.Map;
import static com.intellij.openapi.util.io.IoTestUtil.assumeUnix;
import static com.intellij.openapi.util.io.IoTestUtil.assumeWindows;
import static org.junit.Assert.*;
public class EnvironmentUtilTest {
@Test(timeout = 30000)
public void map() {
assertNotNull(EnvironmentUtil.getEnvironmentMap());
}
@Test
public void path() {
assertNotNull(EnvironmentUtil.getValue("PATH"));
if (SystemInfo.isWindows) {
assertNotNull(EnvironmentUtil.getValue("Path"));
}
}
@Test
public void parse() {
String text = "V1=single line\0V2=multiple\nlines\0V3=single line\0PWD=?\0";
Map<String, String> map = EnvironmentUtil.testParser(text);
assertEquals("single line", map.get("V1"));
assertEquals("multiple\nlines", map.get("V2"));
assertEquals("single line", map.get("V3"));
if (System.getenv().containsKey("PWD")) {
assertEquals(System.getenv("PWD"), map.get("PWD"));
assertEquals(4, map.size());
}
else {
assertEquals(3, map.size());
}
}
@Test(timeout = 30000)
public void load() {
assumeUnix();
Map<String, String> env = EnvironmentUtil.testLoader();
assertTrue(env.size() >= System.getenv().size() / 2);
}
@Test(timeout = 30000)
public void loadingBatEnv() throws Exception {
assumeWindows();
File file = FileUtil.createTempFile("test", ".bat", true);
FileUtil.writeToFile(file, "set FOO_TEST_1=123\r\nset FOO_TEST_2=%1");
Map<String, String> result = new EnvironmentUtil.ShellEnvReader().readBatEnv(file.toPath(), Collections.singletonList("arg_value"));
assertEquals("123", result.get("FOO_TEST_1"));
assertEquals("arg_value", result.get("FOO_TEST_2"));
}
@Test(timeout = 30000)
public void loadingBatEnv_ErrorHandling() throws Exception {
assumeWindows();
File file = FileUtil.createTempFile("test", ".bat", true);
FileUtil.writeToFile(file, "echo some error\r\nexit /B 1");
try {
new EnvironmentUtil.ShellEnvReader().readBatEnv(file.toPath(), Collections.emptyList());
fail("error should be reported");
}
catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("some error"));
}
}
}
|
[
"\"PWD\""
] |
[] |
[
"PWD"
] |
[]
|
["PWD"]
|
java
| 1 | 0 | |
tests/performance/test_bigquery_benchmarks.py
|
#!/usr/bin/env python3
"""
Test performance using bigquery.
"""
import cProfile
import os
import sys
from collections.abc import Mapping
from pathlib import Path
import _pytest.config
import py.path
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
from great_expectations.checkpoint.types.checkpoint_result import CheckpointResult
from great_expectations.core.async_executor import patch_https_connection_pool
from tests.performance import taxi_benchmark_util
patch_https_connection_pool(taxi_benchmark_util.concurrency_config())
@pytest.mark.parametrize(
"backend_api",
[
"V2", # Batch Kwargs API
"V3", # Batch Request API
],
)
@pytest.mark.parametrize("write_data_docs", [False, True])
@pytest.mark.parametrize("number_of_tables", [1, 2, 4, 8, 16, 100])
def test_taxi_trips_benchmark(
benchmark: BenchmarkFixture,
tmpdir: py.path.local,
pytestconfig: _pytest.config.Config,
number_of_tables: int,
write_data_docs: bool,
backend_api: str,
):
"""Benchmark performance with a variety of expectations using NYC Taxi data (yellow_tripdata_sample_2019-01.csv)
found in the tests/test_sets/taxi_yellow_tripdata_samples directory, and used extensively in unittest and
integration tests for Great Expectations.
To simulate a more realistic usage of Great Expectations with several tables, this benchmark is run with 1 or more
copies of the table, and each table has multiple expectations run on them. For simplicity, the expectations run on
each table are identical. The specific expectations are somewhat arbitrary but were chosen to be representative of
a (non-public) real use case of Great Expectations.
Note: This data being tested in this benchmark generally shouldn't be changed over time, because consistent
benchmarks are more useful to compare trends over time. Please do not change the tables being tested with nor change
the expectations being used by this benchmark. Instead of changing this benchmark's data/expectations, please
consider adding a new benchmark (or at least rename this benchmark to provide clarity that results are not directly
comparable because of the data change).
"""
_skip_if_bigquery_performance_tests_not_enabled(pytestconfig)
html_dir = (
os.environ.get("GE_BENCHMARK_HTML_DIRECTORY", tmpdir.strpath)
if write_data_docs
else None
)
checkpoint = taxi_benchmark_util.create_checkpoint(
number_of_tables=number_of_tables,
html_dir=html_dir,
backend_api=backend_api,
)
if os.environ.get("GE_PROFILE_FILE_PATH"):
cProfile.runctx(
"checkpoint.run()",
None,
locals(),
filename=os.environ["GE_PROFILE_FILE_PATH"],
)
return
else:
result: CheckpointResult = benchmark.pedantic(
checkpoint.run,
iterations=1,
rounds=1,
)
# Do some basic sanity checks.
assert result.success, result
assert len(result.run_results) == number_of_tables
if write_data_docs:
html_file_paths = list(Path(html_dir).glob("validations/**/*.html"))
assert len(html_file_paths) == number_of_tables
# Check that run results contain the right number of suites, assets, and table names.
assert (
len(
{
run_result["validation_result"]["meta"]["expectation_suite_name"]
for run_result in result.run_results.values()
}
)
== number_of_tables
)
batch_key = "batch_spec" if backend_api == "V3" else "batch_kwargs"
for field in ["data_asset_name", "table_name" if backend_api == "V3" else "table"]:
assert (
len(
{
run_result["validation_result"]["meta"][batch_key][field]
for run_result in result.run_results.values()
}
)
== number_of_tables
)
# Check that every expectation result was correct.
expected_results = taxi_benchmark_util.expected_validation_results()
for run_result in result.run_results.values():
actual_results = [
result.to_json_dict()
for result in run_result["validation_result"]["results"]
]
assert len(expected_results) == len(actual_results)
for expected_result, actual_result in zip(expected_results, actual_results):
description_for_error_reporting = (
f'{expected_result["expectation_config"]["expectation_type"]} result'
)
_recursively_assert_actual_result_matches_expected_result_keys(
expected_result, actual_result, description_for_error_reporting
)
def _recursively_assert_actual_result_matches_expected_result_keys(
expected, actual, description_for_error_reporting
):
"""Assert that actual equals expected while ignoring key order and extra keys not present in expected.
Expected mappings may be a subset of actual mappings -- this can be useful to make tests less fragile so that they
don't incorrectly fail when new keys are added.
Args:
expected: The expected result. For mappings, every key in expected must be present in actual with the same value
(while recursively ignoring nested key order and extra nested keys in any nested values).
actual: The actual result for comparison with expected result.
description_for_error_reporting: Description to provide context during error reporting. For each recursive call,
the description is updated to also include the key. For example, if the initial description is
"expect_table_columns_to_match_set result" and the assertion fails with the "raised_exception" key nested in
the "exception_info" key then pytest will report with a description as shown in the following:
> assert expected == actual, description_for_error_reporting
E AssertionError: expect_table_columns_to_match_set result["exception_info"]["raised_exception"]
E assert True == False
E +True
E -False
"""
if isinstance(expected, Mapping):
for expected_key in expected.keys():
assert expected_key in actual.keys(), description_for_error_reporting
_recursively_assert_actual_result_matches_expected_result_keys(
expected[expected_key],
actual[expected_key],
description_for_error_reporting + f'["{expected_key}"]',
)
else:
assert expected == actual, description_for_error_reporting
def _skip_if_bigquery_performance_tests_not_enabled(
pytestconfig: _pytest.config.Config,
):
if not pytestconfig.getoption("bigquery") or not pytestconfig.getoption(
"performance_tests"
):
pytest.skip(
"This test requires --bigquery and --performance-tests flags to run."
)
if __name__ == "__main__":
# For profiling, it can be useful to support running this script directly instead of using pytest to run.
sys.exit(pytest.main(sys.argv))
|
[] |
[] |
[
"GE_BENCHMARK_HTML_DIRECTORY",
"GE_PROFILE_FILE_PATH"
] |
[]
|
["GE_BENCHMARK_HTML_DIRECTORY", "GE_PROFILE_FILE_PATH"]
|
python
| 2 | 0 | |
go/trace/plugin_jaeger.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 trace
import (
"flag"
"io"
"os"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"vitess.io/vitess/go/flagutil"
"vitess.io/vitess/go/vt/log"
)
/*
This file makes it easy to build Vitess without including the Jaeger binaries.
All that is needed is to delete this file. OpenTracing binaries will still be
included but nothing Jaeger specific.
*/
var (
agentHost = flag.String("jaeger-agent-host", "", "host and port to send spans to. if empty, no tracing will be done")
samplingType = flagutil.NewOptionalString("const")
samplingRate = flagutil.NewOptionalFloat64(0.1)
)
func init() {
flag.Var(samplingType, "tracing-sampling-type", "sampling strategy to use for jaeger. possible values are 'const', 'probabilistic', 'rateLimiting', or 'remote'")
flag.Var(samplingRate, "tracing-sampling-rate", "sampling rate for the probabilistic jaeger sampler")
}
// newJagerTracerFromEnv will instantiate a tracingService implemented by Jaeger,
// taking configuration from environment variables. Available properties are:
// JAEGER_SERVICE_NAME -- If this is set, the service name used in code will be ignored and this value used instead
// JAEGER_RPC_METRICS
// JAEGER_TAGS
// JAEGER_SAMPLER_TYPE
// JAEGER_SAMPLER_PARAM
// JAEGER_SAMPLER_MANAGER_HOST_PORT
// JAEGER_SAMPLER_MAX_OPERATIONS
// JAEGER_SAMPLER_REFRESH_INTERVAL
// JAEGER_REPORTER_MAX_QUEUE_SIZE
// JAEGER_REPORTER_FLUSH_INTERVAL
// JAEGER_REPORTER_LOG_SPANS
// JAEGER_ENDPOINT
// JAEGER_USER
// JAEGER_PASSWORD
// JAEGER_AGENT_HOST
// JAEGER_AGENT_PORT
func newJagerTracerFromEnv(serviceName string) (tracingService, io.Closer, error) {
cfg, err := config.FromEnv()
if err != nil {
return nil, nil, err
}
if cfg.ServiceName == "" {
cfg.ServiceName = serviceName
}
// Allow command line args to override environment variables.
if *agentHost != "" {
cfg.Reporter.LocalAgentHostPort = *agentHost
}
log.Infof("Tracing to: %v as %v", cfg.Reporter.LocalAgentHostPort, cfg.ServiceName)
if os.Getenv("JAEGER_SAMPLER_PARAM") == "" {
// If the environment variable was not set, we take the flag regardless
// of whether it was explicitly set on the command line.
cfg.Sampler.Param = samplingRate.Get()
} else if samplingRate.IsSet() {
// If the environment variable was set, but the user also explicitly
// passed the command line flag, the flag takes precedence.
cfg.Sampler.Param = samplingRate.Get()
}
if samplingType.IsSet() {
cfg.Sampler.Type = samplingType.Get()
} else if cfg.Sampler.Type == "" {
log.Infof("-tracing-sampler-type was not set, and JAEGER_SAMPLER_TYPE was not set, defaulting to const sampler")
cfg.Sampler.Type = jaeger.SamplerTypeConst
}
log.Infof("Tracing sampler type %v (param: %v)", cfg.Sampler.Type, cfg.Sampler.Param)
var opts []config.Option
if *enableLogging {
opts = append(opts, config.Logger(&traceLogger{}))
} else if cfg.Reporter.LogSpans {
log.Warningf("JAEGER_REPORTER_LOG_SPANS was set, but -tracing-enable-logging was not; spans will not be logged")
}
tracer, closer, err := cfg.NewTracer(opts...)
if err != nil {
return nil, &nilCloser{}, err
}
opentracing.SetGlobalTracer(tracer)
return openTracingService{Tracer: &jaegerTracer{actual: tracer}}, closer, nil
}
func init() {
tracingBackendFactories["opentracing-jaeger"] = newJagerTracerFromEnv
}
var _ tracer = (*jaegerTracer)(nil)
type jaegerTracer struct {
actual opentracing.Tracer
}
func (jt *jaegerTracer) GetOpenTracingTracer() opentracing.Tracer {
return jt.actual
}
|
[
"\"JAEGER_SAMPLER_PARAM\""
] |
[] |
[
"JAEGER_SAMPLER_PARAM"
] |
[]
|
["JAEGER_SAMPLER_PARAM"]
|
go
| 1 | 0 | |
pkg/monitors/statuscake/statuscake-monitor_test.go
|
package statuscake
import (
"os"
"testing"
"time"
endpointmonitorv1alpha1 "github.com/stakater/IngressMonitorController/pkg/apis/endpointmonitor/v1alpha1"
"github.com/stakater/IngressMonitorController/pkg/config"
"github.com/stakater/IngressMonitorController/pkg/models"
"github.com/stakater/IngressMonitorController/pkg/util"
"gotest.tools/assert"
)
func TestAddMonitorWithCorrectValues(t *testing.T) {
config := config.GetControllerConfigTest()
service := StatusCakeMonitorService{}
provider := util.GetProviderWithName(config, "StatusCake")
if provider == nil {
return
}
service.Setup(*provider)
m := models.Monitor{Name: "google-test", URL: "https://google1.com"}
service.Add(m)
mRes, err := service.GetByName("google-test")
if err != nil {
t.Error("Error: " + err.Error())
}
if mRes.Name != m.Name || mRes.URL != m.URL {
t.Error("URL and name should be the same")
}
service.Remove(*mRes)
time.Sleep(5 * time.Second)
monitor, err := service.GetByName(mRes.Name)
if monitor != nil {
t.Error("Monitor should've been deleted ", monitor, err)
}
}
func TestUpdateMonitorWithCorrectValues(t *testing.T) {
config := config.GetControllerConfigTest()
service := StatusCakeMonitorService{}
provider := util.GetProviderWithName(config, "StatusCake")
if provider == nil {
return
}
service.Setup(*provider)
m := models.Monitor{Name: "google-test", URL: "https://google.com"}
service.Add(m)
mRes, err := service.GetByName("google-test")
if err != nil {
t.Error("Error: " + err.Error())
}
if mRes.Name != m.Name || mRes.URL != m.URL {
t.Error("URL and name should be the same")
}
mRes.URL = "https://facebook.com"
service.Update(*mRes)
mRes, err = service.GetByName("google-test")
if err != nil {
t.Error("Error: " + err.Error())
}
if mRes.URL != "https://facebook.com" {
t.Error("URL and name should be the same")
}
time.Sleep(5 * time.Second)
service.Remove(*mRes)
monitor, err := service.GetByName(mRes.Name)
if monitor != nil {
t.Error("Monitor should've been deleted ", monitor, err)
}
}
func TestBuildUpsertForm(t *testing.T) {
m := models.Monitor{Name: "google-test", URL: "https://google.com"}
monitorConfig := &endpointmonitorv1alpha1.StatusCakeConfig{
CheckRate: 60,
TestType: "TCP",
Paused: true,
PingURL: "",
FollowRedirect: true,
Port: 7070,
TriggerRate: 1,
ContactGroup: "123456,654321",
BasicAuthUser: "testuser",
NodeLocations: "",
StatusCodes: "500,501,502,503,504,505",
Confirmation: 2,
EnableSSLAlert: true,
RealBrowser: true,
TestTags: "test,testrun,uptime",
}
m.Config = monitorConfig
oldEnv := os.Getenv("testuser")
os.Setenv("testuser", "testpass")
defer os.Setenv("testuser", oldEnv)
vals := buildUpsertForm(m, "")
assert.Equal(t, "testuser", vals.Get("BasicUser"))
assert.Equal(t, "testpass", vals.Get("BasicPass"))
assert.Equal(t, "60", vals.Get("CheckRate"))
assert.Equal(t, "2", vals.Get("Confirmation"))
assert.Equal(t, "123456,654321", vals.Get("ContactGroup"))
assert.Equal(t, "1", vals.Get("EnableSSLAlert"))
assert.Equal(t, "1", vals.Get("FollowRedirect"))
assert.Equal(t, "", vals.Get("NodeLocations"))
assert.Equal(t, "1", vals.Get("Paused"))
assert.Equal(t, "", vals.Get("PingURL"))
assert.Equal(t, "7070", vals.Get("Port"))
assert.Equal(t, "1", vals.Get("RealBrowser"))
// TODO: Fix implementation first and then uncomment this assertion
// assert.Equal(t, "500,501,502,503,504,505", vals.Get("StatusCodes"))
assert.Equal(t, "test,testrun,uptime", vals.Get("TestTags"))
assert.Equal(t, "TCP", vals.Get("TestType"))
assert.Equal(t, "1", vals.Get("TriggerRate"))
}
|
[
"\"testuser\""
] |
[] |
[
"testuser"
] |
[]
|
["testuser"]
|
go
| 1 | 0 | |
util/kustomize/kustomize_test.go
|
package kustomize
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
"github.com/argoproj/pkg/exec"
"github.com/stretchr/testify/assert"
"github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
)
// TODO: move this into shared test package after resolving import cycle
const (
// This is a throwaway gitlab test account/repo with a read-only personal access token for the
// purposes of testing private git repos
PrivateGitRepo = "https://gitlab.com/argo-cd-test/test-apps.git"
PrivateGitUsername = "blah"
PrivateGitPassword = "B5sBDeoqAVUouoHkrovy"
)
const kustomization1 = "kustomization_yaml"
const kustomization2a = "kustomization_yml"
const kustomization2b = "Kustomization"
func testDataDir() (string, error) {
res, err := ioutil.TempDir("", "kustomize-test")
if err != nil {
return "", err
}
_, err = exec.RunCommand("cp", "-r", "./testdata/"+kustomization1, filepath.Join(res, "testdata"))
if err != nil {
return "", err
}
return path.Join(res, "testdata"), nil
}
func TestKustomizeBuild(t *testing.T) {
appPath, err := testDataDir()
assert.Nil(t, err)
namePrefix := "namePrefix-"
kustomize := NewKustomizeApp(appPath, nil)
kustomizeSource := v1alpha1.ApplicationSourceKustomize{
NamePrefix: namePrefix,
ImageTags: []v1alpha1.KustomizeImageTag{
{
Name: "k8s.gcr.io/nginx-slim",
Value: "latest",
},
},
}
objs, params, err := kustomize.Build(&kustomizeSource)
assert.Nil(t, err)
if err != nil {
assert.Equal(t, len(objs), 2)
assert.Equal(t, len(params), 2)
}
for _, obj := range objs {
switch obj.GetKind() {
case "StatefulSet":
assert.Equal(t, namePrefix+"web", obj.GetName())
case "Deployment":
assert.Equal(t, namePrefix+"nginx-deployment", obj.GetName())
}
}
for _, param := range params {
switch param.Value {
case "nginx":
assert.Equal(t, "1.15.4", param.Value)
case "k8s.gcr.io/nginx-slim":
assert.Equal(t, "latest", param.Value)
}
}
}
func TestFindKustomization(t *testing.T) {
testFindKustomization(t, kustomization1, "kustomization.yaml")
testFindKustomization(t, kustomization2a, "kustomization.yml")
testFindKustomization(t, kustomization2b, "Kustomization")
}
func testFindKustomization(t *testing.T, set string, expected string) {
kustomization, err := (&kustomize{path: "testdata/" + set}).findKustomization()
assert.Nil(t, err)
assert.Equal(t, "testdata/"+set+"/"+expected, kustomization)
}
func TestGetKustomizationVersion(t *testing.T) {
testGetKustomizationVersion(t, kustomization1, 1)
testGetKustomizationVersion(t, kustomization2a, 2)
testGetKustomizationVersion(t, kustomization2b, 2)
}
func testGetKustomizationVersion(t *testing.T, set string, expected int) {
version, err := (&kustomize{path: "testdata/" + set}).getKustomizationVersion()
assert.Nil(t, err)
assert.Equal(t, expected, version)
}
func TestGetCommandName(t *testing.T) {
assert.Equal(t, "kustomize1", GetCommandName(1))
assert.Equal(t, "kustomize", GetCommandName(2))
}
func TestIsKustomization(t *testing.T) {
assert.True(t, IsKustomization("kustomization.yaml"))
assert.True(t, IsKustomization("kustomization.yml"))
assert.True(t, IsKustomization("Kustomization"))
assert.False(t, IsKustomization("rubbish.yml"))
}
// TestPrivateRemoteBase verifies we can supply git credentials to a private remote base
func TestPrivateRemoteBase(t *testing.T) {
os.Setenv("GIT_CONFIG_NOSYSTEM", "true")
defer os.Unsetenv("GIT_CONFIG_NOSYSTEM")
// add the hack path which has the git-ask-pass.sh shell script
osPath := os.Getenv("PATH")
hackPath, err := filepath.Abs("../../hack")
assert.NoError(t, err)
err = os.Setenv("PATH", fmt.Sprintf("%s:%s", osPath, hackPath))
assert.NoError(t, err)
defer func() { _ = os.Setenv("PATH", osPath) }()
kust := NewKustomizeApp("./testdata/private-remote-base", &GitCredentials{Username: PrivateGitUsername, Password: PrivateGitPassword})
objs, _, err := kust.Build(nil)
assert.NoError(t, err)
assert.Len(t, objs, 2)
}
|
[
"\"PATH\""
] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
go
| 1 | 0 | |
bridgedb/test/test_smtp.py
|
"""integration tests for BridgeDB ."""
from __future__ import print_function
import smtplib
import asyncore
import threading
import queue
import random
import os
from smtpd import SMTPServer
from twisted.trial import unittest
from twisted.trial.unittest import FailTest
from twisted.trial.unittest import SkipTest
from bridgedb.test.util import processExists
from bridgedb.test.util import getBridgeDBPID
# ------------- SMTP Client Config
SMTP_DEBUG_LEVEL = 0 # set to 1 to see SMTP message exchange
BRIDGEDB_SMTP_SERVER_ADDRESS = "localhost"
BRIDGEDB_SMTP_SERVER_PORT = 6725
# %d is parameterised with a random integer to make the sender unique
FROM_ADDRESS_TEMPLATE = "test%[email protected]"
# Minimum value used to parameterise FROM_ADDRESS_TEMPLATE
MIN_FROM_ADDRESS = 1
# Max value used to parameterise FROM_ADDRESS_TEMPLATE. Needs to be pretty big
# to reduce the chance of collisions
MAX_FROM_ADDRESS = 10**8
TO_ADDRESS = "[email protected]"
MESSAGE_TEMPLATE = """From: %s
To: %s
Subject: testing
get bridges"""
# ------------- SMTP Server Setup
# Setup an SMTP server which we use to check for responses
# from bridgedb. This needs to be done before sending the actual mail
LOCAL_SMTP_SERVER_ADDRESS = 'localhost'
LOCAL_SMTP_SERVER_PORT = 2525 # Must be the same as bridgedb's EMAIL_SMTP_PORT
class EmailServer(SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
''' Overridden from SMTP server, called whenever a message is received'''
self.message_queue.put(data)
def thread_proc(self):
''' This function runs in thread, and will continue looping
until the _stop Event object is set by the stop() function'''
while self._stop.is_set() == False:
asyncore.loop(timeout=0.0, count=1)
# Must close, or asyncore will hold on to the socket and subsequent
# tests will fail with 'Address not in use'.
self.close()
def start(self):
self.message_queue = queue.Queue()
self._stop = threading.Event()
self._thread = threading.Thread(target=self.thread_proc)
# Ensures that if any tests do fail, then threads will exit when the
# parent exits.
self._thread.setDaemon(True)
self._thread.start()
@classmethod
def startServer(cls):
#print("Starting SMTP server on %s:%s"
# % (LOCAL_SMTP_SERVER_ADDRESS, LOCAL_SMTP_SERVER_PORT))
server = EmailServer((LOCAL_SMTP_SERVER_ADDRESS,
LOCAL_SMTP_SERVER_PORT),
None)
server.start()
return server
def stop(self):
# Signal thread_proc to stop:
self._stop.set()
# Wait for thread_proc to return (shouldn't take long)
self._thread.join()
assert self._thread.is_alive() == False, "Thread is alive and kicking"
def getAndCheckMessageContains(self, text, timeoutInSecs=2.0):
try:
message = self.message_queue.get(block=True, timeout=timeoutInSecs)
# Queue.Empty, according to its documentation, is only supposed to be
# raised when Queue.get(block=False) or Queue.get_nowait() are called.
# I've no idea why it's getting raised here, when we're blocking for
# it, but nonetheless it causes occasional, non-deterministic CI
# failures:
#
# https://travis-ci.org/isislovecruft/bridgedb/jobs/58996136#L3281
except queue.Empty:
pass
else:
assert message.find(text) != -1, ("Message did not contain text '%s'."
"Full message is:\n %s"
% (text, message))
def checkNoMessageReceived(self, timeoutInSecs=2.0):
try:
self.message_queue.get(block=True, timeout=timeoutInSecs)
except queue.Empty:
return True
assert False, "Found a message in the queue, but expected none"
def sendMail(fromAddress):
#print("Connecting to %s:%d"
# % (BRIDGEDB_SMTP_SERVER_ADDRESS, BRIDGEDB_SMTP_SERVER_PORT))
client = smtplib.SMTP(BRIDGEDB_SMTP_SERVER_ADDRESS,
BRIDGEDB_SMTP_SERVER_PORT)
client.set_debuglevel(SMTP_DEBUG_LEVEL)
#print("Sending mail TO:%s, FROM:%s"
# % (TO_ADDRESS, fromAddress))
result = client.sendmail(fromAddress, TO_ADDRESS,
MESSAGE_TEMPLATE % (fromAddress, TO_ADDRESS))
assert result == {}, "Failed to send mail"
client.quit()
class SMTPTests(unittest.TestCase):
def setUp(self):
'''Called at the start of each test, ensures that the SMTP server is
running.
'''
here = os.getcwd()
topdir = here.rstrip('_trial_temp')
self.rundir = os.path.join(topdir, 'run')
self.pidfile = os.path.join(self.rundir, 'bridgedb.pid')
self.pid = getBridgeDBPID(self.pidfile)
self.server = EmailServer.startServer()
def tearDown(self):
'''Called after each test, ensures that the SMTP server is cleaned up.
'''
self.server.stop()
def test_getBridges(self):
if os.environ.get("CI"):
if not self.pid or not processExists(self.pid):
raise FailTest("Could not start BridgeDB process on CI server!")
if not self.pid or not processExists(self.pid):
raise SkipTest("Can't run test: no BridgeDB process running.")
# send the mail to bridgedb, choosing a random email address
sendMail(fromAddress=FROM_ADDRESS_TEMPLATE
% random.randint(MIN_FROM_ADDRESS, MAX_FROM_ADDRESS))
# then check that our local SMTP server received a response
# and that response contained some bridges
self.server.getAndCheckMessageContains(b"Here are your bridges")
def test_getBridges_rateLimitExceeded(self):
if os.environ.get("CI"):
if not self.pid or not processExists(self.pid):
raise FailTest("Could not start BridgeDB process on CI server!")
if not self.pid or not processExists(self.pid):
raise SkipTest("Can't run test: no BridgeDB process running.")
# send the mail to bridgedb, choosing a random email address
FROM_ADDRESS = FROM_ADDRESS_TEMPLATE % random.randint(
MIN_FROM_ADDRESS, MAX_FROM_ADDRESS)
sendMail(FROM_ADDRESS)
# then check that our local SMTP server received a response
# and that response contained some bridges
self.server.getAndCheckMessageContains(b"Here are your bridges")
# send another request from the same email address
sendMail(FROM_ADDRESS)
# this time, the email response should not contain any bridges
self.server.getAndCheckMessageContains(
b"You have exceeded the rate limit. Please slow down!")
# then we send another request from the same email address
sendMail(FROM_ADDRESS)
# now there should be no response at all (wait 1 second to make sure)
self.server.checkNoMessageReceived(timeoutInSecs=1.0)
def test_getBridges_stressTest(self):
'''Sends a large number of emails in a short period of time, and checks
that a response is received for each message.
'''
if os.environ.get("CI"):
if not self.pid or not processExists(self.pid):
raise FailTest("Could not start BridgeDB process on CI server!")
if not self.pid or not processExists(self.pid):
raise SkipTest("Can't run test: no BridgeDB process running.")
NUM_MAILS = 100
for i in range(NUM_MAILS):
# Note: if by chance two emails with the same FROM_ADDRESS are
# generated, this test will fail Setting 'MAX_FROM_ADDRESS' to be
# a high value reduces the probability of this occuring, but does
# not rule it out
sendMail(fromAddress=FROM_ADDRESS_TEMPLATE
% random.randint(MIN_FROM_ADDRESS, MAX_FROM_ADDRESS))
for i in range(NUM_MAILS):
self.server.getAndCheckMessageContains(b"Here are your bridges")
|
[] |
[] |
[
"CI"
] |
[]
|
["CI"]
|
python
| 1 | 0 | |
response_examples/update_response_examples.py
|
import json
import os
import re
from typing import Any
from ikea_api.endpoints import Cart, OrderCapture
token = os.environ["TOKEN"]
payloads = {
"add_items": {"90428328": 1},
"update_items": {"90428328": 5},
"remove_items": ["90428328"],
}
class_args = {"OrderCapture": ("101000")}
functions_to_skip = ["_error_handler", "copy_items", "set_coupon"]
def save_json(r: Any, *args: Any, **kwargs: Any):
directory = "response_examples"
try:
os.mkdir(directory)
except FileExistsError:
pass
module = re.findall(r".([^.]+$)", r.__module__)[0]
try:
os.mkdir(os.path.join(directory, module))
except FileExistsError:
pass
path = os.path.join(directory, module, r.__name__ + ".json")
res: Any = r(*args, **kwargs)
with open(path, "a+") as f:
f.seek(0)
f.truncate()
j = json.dumps(res).encode().decode("unicode-escape")
f.write(j)
def save_responses_for_class(cl: Any, token: str):
for s in cl.__dict__:
if cl.__name__ in class_args:
cur_cl = cl(token, class_args[cl.__name__])
else:
cur_cl = cl(token)
if not re.match(r"_", s) and s not in functions_to_skip:
f = getattr(cur_cl, s)
if s in payloads:
save_json(f, payloads[s])
else:
save_json(f)
def main():
Cart(token).add_items(payloads["add_items"])
for cl in OrderCapture, Cart:
save_responses_for_class(cl, token)
if __name__ == "__main__":
main()
|
[] |
[] |
[
"TOKEN"
] |
[]
|
["TOKEN"]
|
python
| 1 | 0 | |
tests/conftest.py
|
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
str = type('')
import os
os.environ['GPIOZERO_PIN_FACTORY'] = 'mock'
|
[] |
[] |
[
"GPIOZERO_PIN_FACTORY"
] |
[]
|
["GPIOZERO_PIN_FACTORY"]
|
python
| 1 | 0 | |
api/bitflyer/v1/client_test.go
|
package v1_test
import (
"encoding/json"
"fmt"
"math"
"os"
"strings"
"testing"
"time"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/cancels"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/list"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/orders"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/address"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/banks"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/coins"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/collateral"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/commission"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/private/balance"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/public/chat"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/public/execution"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/public/health"
v1 "github.com/go-numb/go-exchanges/api/bitflyer/v1"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/public/board"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/public/ticker"
"github.com/go-numb/go-exchanges/api/bitflyer/v1/types"
"github.com/stretchr/testify/assert"
)
func TestLimit(t *testing.T) {
client := v1.New(nil)
assert.Equal(t, client.Limit.Remain(false), v1.NewLimit(1).Remain(false))
assert.Equal(t, client.Limit.Remain(true), v1.NewLimit(1).Remain(true))
}
func TestTicker(t *testing.T) {
client := v1.New(nil)
tick, err := client.Ticker(ticker.New(types.FXBTCJPY))
assert.NoError(t, err)
assert.Equal(t, client.Limit.Remain(false), 499)
fmt.Printf("%+v\n", tick)
}
func TestBoard(t *testing.T) {
client := v1.New(nil)
b, err := client.Board(board.New(types.FXBTCJPY))
assert.NoError(t, err)
fmt.Printf("%+v\n", b)
ask, bid := b.Best()
low := math.Min(ask, bid)
assert.Equal(t, bid, low)
high := math.Max(ask, bid)
assert.Equal(t, ask, high)
fmt.Printf("%+v %+v\n", bid, ask)
ask, bid = b.Depth(500)
assert.NotEmpty(t, ask)
assert.NotEmpty(t, bid)
fmt.Printf("500depth: %+vBTC %+vBTC\n", ask, bid)
}
func TestExecutions(t *testing.T) {
n := 100
count := 499
client := v1.New(nil)
var ex []execution.Execution
var agg []execution.Execution
var lastid int
for i := 0; i < n; i++ {
exec, err := client.Executions(execution.New(types.FXBTCJPY).SetPagination(count, lastid, 0))
fmt.Printf("%+v\n", err)
assert.NoError(t, err)
// assert.Equal(t, count, len(*exec))
ex = append(ex, *exec...)
agg = append(agg, exec.Aggregate()...)
lastid = ex[len(ex)-1].ID
}
var (
eSize, aggSize float64
)
for i := range ex {
if 1 < ex[i].Size {
fmt.Printf("単約定: %s %.f %.4f\n", ex[i].Side, ex[i].Price, ex[i].Size)
}
eSize += ex[i].Size
}
for i := range agg {
if 1 < agg[i].Size {
fmt.Printf("分割約定: %s %.f %.4f\n", agg[i].Side, agg[i].Price, agg[i].Size)
}
aggSize += agg[i].Size
}
// 生データと集計データの約定枚数をチェック
assert.Equal(t, math.RoundToEven(eSize/types.SATOSHI)*types.SATOSHI, math.RoundToEven(aggSize/types.SATOSHI)*types.SATOSHI)
}
func TestBoardHealth(t *testing.T) {
client := v1.New(nil)
b, err := client.BoardHealth(health.NewForBoard(types.FXBTCJPY))
assert.NoError(t, err)
fmt.Printf("%+v\n", b)
}
func TestExchangeHealth(t *testing.T) {
client := v1.New(nil)
e, err := client.ExchangeHealth(health.NewForExchange(types.FXBTCJPY))
assert.NoError(t, err)
fmt.Printf("%+v\n", e)
}
func TestChats(t *testing.T) {
client := v1.New(nil)
chats, err := client.Chats(chat.New(time.Now().Add(-24 * time.Hour)))
assert.NoError(t, err)
fmt.Printf("%+v\n", strings.Join(chats.List(), "\n"))
}
/*
# Private API
*/
func TestBalance(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
balance, err := client.Balance(balance.New())
assert.NoError(t, err)
fmt.Printf("%+v\n", strings.Join(balance.List(), "\n"))
}
func TestCollateral(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
col, err := client.Collateral(collateral.New())
assert.NoError(t, err)
fmt.Printf("%+v\n", col)
}
func TestAddresses(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
addr, err := client.Addresses(address.New())
assert.NoError(t, err)
fmt.Printf("%+v\n", addr)
}
func TestCoinin(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
coin, err := client.Coinin(coins.NewForIn().SetPagination(10, 0, 0))
assert.NoError(t, err)
for i, v := range *coin {
fmt.Printf("%d: %+v\n", i, v)
}
}
func TestCoinout(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
coin, err := client.Coinout(coins.NewForOut().SetPagination(10, 0, 0))
assert.NoError(t, err)
for i, v := range *coin {
fmt.Printf("%d: %+v\n", i, v)
}
}
func TestBanks(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
bank, err := client.Banks(banks.NewForBanks())
assert.NoError(t, err)
for i, v := range *bank {
fmt.Printf("%d: %+v\n", i, v)
}
}
func TestWithdraw(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
bank, err := client.Withdraw(banks.NewForWithdraw("twofactor", 11111, 22222))
assert.NoError(t, err, "error is ok")
fmt.Printf("%+v\n", bank)
}
func TestBankin(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
bank, err := client.Bankin(banks.NewForIn().SetPagination(10, 0, 0))
assert.NoError(t, err)
for i, v := range *bank {
fmt.Printf("%d: %+v\n", i, v)
}
}
func TestBankout(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
bank, err := client.Bankout(banks.NewForOut("").SetPagination(10, 0, 0))
assert.NoError(t, err)
for i, v := range *bank {
fmt.Printf("%d: %+v\n", i, v)
}
}
func TestChildOrder(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
o, err := client.ChildOrder(orders.NewForChildOrder(
types.FXBTCJPY,
types.LIMIT,
types.BUY,
types.GTC,
350000,
types.ToSize(0.03),
1,
))
assert.NoError(t, err)
fmt.Printf("%+v\n", o)
}
func TestParentOrder(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
o, err := client.ParentOrder(orders.NewForParentOrder(
types.ORDERMETHOD_IFDOCO,
types.GTC,
1,
[]orders.Param{
orders.Param{
ProductCode: types.FXBTCJPY,
ConditionType: types.CONDITION_LIMIT,
Side: types.BUY,
Size: 0.01,
Price: 350000,
// Trigger不要
TriggerPrice: 0,
},
orders.Param{
ProductCode: types.FXBTCJPY,
ConditionType: types.CONDITION_STOP,
Side: types.SELL,
Size: 0.01,
Price: 250000,
// Trigger不要
TriggerPrice: 0,
},
orders.Param{
ProductCode: types.FXBTCJPY,
ConditionType: types.CONDITION_LIMIT,
Side: types.SELL,
Size: 0.01,
Price: 750000,
// Trigger不要
TriggerPrice: 0,
},
},
))
assert.NoError(t, err)
fmt.Printf("%+v\n", o)
}
func TestCancelByID(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
err := client.CancelByID(cancels.NewByID(
types.FXBTCJPY,
"JRF20200314-044600-538282",
))
assert.NoError(t, err)
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestCancelByIDForParent(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
err := client.CancelByIDForParent(cancels.NewByIDForParent(
types.FXBTCJPY,
"JRF20200314-044600-538282",
))
assert.NoError(t, err)
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestCancelAll(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
err := client.CancelAll(cancels.New(
types.FXBTCJPY,
))
assert.NoError(t, err)
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestChildOrders(t *testing.T) {
// var m map[string]interface{}
// toml.DecodeFile("xxx.toml", &m)
// fmt.Printf("%+v\n", m)
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
// Key: fmt.Sprintf("%s", m["KEY"]),
// Secret: fmt.Sprintf("%s", m["SECRET"]),
})
res, err := client.ChildOrders(list.NewForChildOrders(
types.FXBTCJPY,
types.COMPLETED,
"", "", "",
500, 0, 0,
))
assert.NoError(t, err)
for i, v := range *res {
fmt.Printf("%d %+v\n", i, v)
}
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestParentOrders(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
res, err := client.ParentOrders(list.NewForParentOrders(
types.FXBTCJPY,
types.COMPLETED,
500, 0, 0,
))
assert.NoError(t, err)
for i, v := range *res {
fmt.Printf("%d %+v\n", i, v)
}
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestMyExecutions(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
res, err := client.MyExecutions(list.NewForExecutions(
types.BTCJPY,
"",
"",
500, 0, 0,
))
assert.NoError(t, err)
for i, v := range *res {
fmt.Printf("%d %+v\n", i, v)
}
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestAccountInfo(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
start := time.Now()
col, err := client.Collateral(collateral.New())
assert.NoError(t, err)
res, err := client.Positions(list.NewForPositions(
types.FXBTCJPY,
))
assert.NoError(t, err)
avg, size, sfd, pnl := res.Aggregate()
fmt.Printf("証拠金: %.1f, 損益: %.1f, 証拠金維持率: %.1f%, 必要保証金: %.1f\n", col.Collateral, col.OpenPositionPNL, col.KeepRate*100, col.RequireCollateral)
fmt.Printf("平均単価: %.1f, %.4fBTC, sfd:%.1f, pnl:%.1f, %v\n", avg, size, sfd, pnl, time.Now().Sub(start))
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestPositions(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
start := time.Now()
res, err := client.Positions(list.NewForPositions(
types.FXBTCJPY,
))
assert.NoError(t, err)
avg, size, sfd, pnl := res.Aggregate()
fmt.Printf("%.1f %+v sfd:%.1f pnl:%.1f %v\n", avg, size, sfd, pnl, time.Now().Sub(start))
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestCollaterals(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
res, err := client.Collaterals(list.NewForCollaterals(
500, 0, 0,
))
assert.NoError(t, err)
for i, v := range *res {
fmt.Printf("%d %+v\n", i, v)
}
s := new(list.SFDFactors)
s.Set(res)
fmt.Printf("CUL SFD FACTOR: %+v\n", s)
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestBalances(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
res, err := client.Balances(list.NewForBalances(
"JPY",
500, 0, 0,
))
assert.NoError(t, err)
for i, v := range *res {
fmt.Printf("%d %+v\n", i, v)
}
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
func TestCommission(t *testing.T) {
client := v1.New(&v1.Config{
Key: os.Getenv("BFKEY"),
Secret: os.Getenv("BFSECRET"),
})
res, err := client.Commission(commission.New(types.BTCJPY))
assert.NoError(t, err)
fmt.Printf("%+v\n", res)
fmt.Printf("%+v %+v\n", client.Limit.Remain(true), client.Limit.Remain(false))
}
const (
SERVERLOG = ""
)
func TestReadJSON(t *testing.T) {
f, _ := os.Open(SERVERLOG)
defer f.Close()
var s []map[string]interface{}
json.NewDecoder(f).Decode(&s)
for i := range s {
fmt.Printf("%s %+v\n", s[i]["time"], s[i]["message"])
}
}
|
[
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\"",
"\"BFKEY\"",
"\"BFSECRET\""
] |
[] |
[
"BFSECRET",
"BFKEY"
] |
[]
|
["BFSECRET", "BFKEY"]
|
go
| 2 | 0 | |
app.py
|
import os
from flask import Flask, flash, render_template, request
from helpers import *
app = Flask(__name__)
app.secret_key = os.environ["SECRET_KEY"]
@app.route('/', methods=["GET", "POST"])
def index():
"""Index page"""
if request.method == "POST":
msg = request.form.get("textarea")
if msg:
fbpost(msg)
flash('Successfully posted!')
return render_template('index.html', name=os.environ["NAME"])
@app.errorhandler(404)
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, unexpected error: {}'.format(e), 404
@app.errorhandler(500)
def application_error(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(e), 500
if __name__ == '__main__':
app.run()
|
[] |
[] |
[
"SECRET_KEY",
"NAME"
] |
[]
|
["SECRET_KEY", "NAME"]
|
python
| 2 | 0 | |
graphsage/unsupervised_train.py
|
from __future__ import division
from __future__ import print_function
import os
import time
import tensorflow as tf
import numpy as np
from graphsage.models import SampleAndAggregate, SAGEInfo, Node2VecModel
from graphsage.minibatch import EdgeMinibatchIterator
from graphsage.neigh_samplers import UniformNeighborSampler
from graphsage.utils import load_data
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
# Set random seed
seed = 123
np.random.seed(seed)
tf.set_random_seed(seed)
# Settings
flags = tf.app.flags
FLAGS = flags.FLAGS
tf.app.flags.DEFINE_boolean('log_device_placement', False,
"""Whether to log device placement.""")
#core params..
flags.DEFINE_string('model', 'graphsage', 'model names. See README for possible values.')
flags.DEFINE_float('learning_rate', 0.00001, 'initial learning rate.')
flags.DEFINE_string("model_size", "small", "Can be big or small; model specific def'ns")
flags.DEFINE_string('train_prefix', '', 'name of the object file that stores the training data. must be specified.')
# left to default values in main experiments
flags.DEFINE_integer('epochs', 1, 'number of epochs to train.')
flags.DEFINE_float('dropout', 0.0, 'dropout rate (1 - keep probability).')
flags.DEFINE_float('weight_decay', 0.0, 'weight for l2 loss on embedding matrix.')
flags.DEFINE_integer('max_degree', 100, 'maximum node degree.')
flags.DEFINE_integer('samples_1', 25, 'number of samples in layer 1')
flags.DEFINE_integer('samples_2', 10, 'number of users samples in layer 2')
flags.DEFINE_integer('dim_1', 128, 'Size of output dim (final is 2x this, if using concat)')
flags.DEFINE_integer('dim_2', 128, 'Size of output dim (final is 2x this, if using concat)')
flags.DEFINE_boolean('random_context', True, 'Whether to use random context or direct edges')
flags.DEFINE_integer('neg_sample_size', 20, 'number of negative samples')
flags.DEFINE_integer('batch_size', 512, 'minibatch size.')
flags.DEFINE_integer('n2v_test_epochs', 1, 'Number of new SGD epochs for n2v.')
flags.DEFINE_integer('identity_dim', 0, 'Set to positive value to use identity embedding features of that dimension. Default 0.')
#logging, saving, validation settings etc.
flags.DEFINE_boolean('save_embeddings', True, 'whether to save embeddings for all nodes after training')
flags.DEFINE_string('base_log_dir', '.', 'base directory for logging and saving embeddings')
flags.DEFINE_integer('validate_iter', 5000, "how often to run a validation minibatch.")
flags.DEFINE_integer('validate_batch_size', 256, "how many nodes per validation sample.")
flags.DEFINE_integer('gpu', 1, "which gpu to use.")
flags.DEFINE_integer('print_every', 50, "How often to print training info.")
flags.DEFINE_integer('max_total_steps', 10**10, "Maximum total number of iterations")
os.environ["CUDA_VISIBLE_DEVICES"]=str(FLAGS.gpu)
GPU_MEM_FRACTION = 0.8
def log_dir():
log_dir = FLAGS.base_log_dir + "/unsup-" + FLAGS.train_prefix.split("/")[-2]
log_dir += "/{model:s}_{model_size:s}_{lr:0.6f}/".format(
model=FLAGS.model,
model_size=FLAGS.model_size,
lr=FLAGS.learning_rate)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
return log_dir
# Define model evaluation function
def evaluate(sess, model, minibatch_iter, size=None):
t_test = time.time()
feed_dict_val = minibatch_iter.val_feed_dict(size)
outs_val = sess.run([model.loss, model.ranks, model.mrr],
feed_dict=feed_dict_val)
return outs_val[0], outs_val[1], outs_val[2], (time.time() - t_test)
def incremental_evaluate(sess, model, minibatch_iter, size):
t_test = time.time()
finished = False
val_losses = []
val_mrrs = []
iter_num = 0
while not finished:
feed_dict_val, finished, _ = minibatch_iter.incremental_val_feed_dict(size, iter_num)
iter_num += 1
outs_val = sess.run([model.loss, model.ranks, model.mrr],
feed_dict=feed_dict_val)
val_losses.append(outs_val[0])
val_mrrs.append(outs_val[2])
return np.mean(val_losses), np.mean(val_mrrs), (time.time() - t_test)
def save_val_embeddings(sess, model, minibatch_iter, size, out_dir, mod=""):
val_embeddings = []
finished = False
seen = set([])
nodes = []
iter_num = 0
name = "val"
while not finished:
feed_dict_val, finished, edges = minibatch_iter.incremental_embed_feed_dict(size, iter_num)
iter_num += 1
outs_val = sess.run([model.loss, model.mrr, model.outputs1],
feed_dict=feed_dict_val)
#ONLY SAVE FOR embeds1 because of planetoid
for i, edge in enumerate(edges):
if not edge[0] in seen:
val_embeddings.append(outs_val[-1][i,:])
nodes.append(edge[0])
seen.add(edge[0])
if not os.path.exists(out_dir):
os.makedirs(out_dir)
val_embeddings = np.vstack(val_embeddings)
np.save(out_dir + name + mod + ".npy", val_embeddings)
with open(out_dir + name + mod + ".txt", "w") as fp:
fp.write("\n".join(map(str,nodes)))
def construct_placeholders():
# Define placeholders
placeholders = {
'batch1' : tf.placeholder(tf.int32, shape=(None), name='batch1'),
'batch2' : tf.placeholder(tf.int32, shape=(None), name='batch2'),
# negative samples for all nodes in the batch
'neg_samples': tf.placeholder(tf.int32, shape=(None,),
name='neg_sample_size'),
'dropout': tf.placeholder_with_default(0., shape=(), name='dropout'),
'batch_size' : tf.placeholder(tf.int32, name='batch_size'),
}
return placeholders
def train(train_data, test_data=None):
G = train_data[0]
features = train_data[1]
id_map = train_data[2]
if not features is None:
# pad with dummy zero vector
features = np.vstack([features, np.zeros((features.shape[1],))])
context_pairs = train_data[3] if FLAGS.random_context else None
placeholders = construct_placeholders()
minibatch = EdgeMinibatchIterator(G,
id_map,
placeholders, batch_size=FLAGS.batch_size,
max_degree=FLAGS.max_degree,
num_neg_samples=FLAGS.neg_sample_size,
context_pairs = context_pairs)
adj_info_ph = tf.placeholder(tf.int32, shape=minibatch.adj.shape)
adj_info = tf.Variable(adj_info_ph, trainable=False, name="adj_info")
if FLAGS.model == 'graphsage_mean':
# Create model
sampler = UniformNeighborSampler(adj_info)
layer_infos = [SAGEInfo("node", sampler, FLAGS.samples_1, FLAGS.dim_1),
SAGEInfo("node", sampler, FLAGS.samples_2, FLAGS.dim_2)]
model = SampleAndAggregate(placeholders,
features,
adj_info,
minibatch.deg,
layer_infos=layer_infos,
model_size=FLAGS.model_size,
identity_dim = FLAGS.identity_dim,
logging=True)
elif FLAGS.model == 'gcn':
# Create model
sampler = UniformNeighborSampler(adj_info)
layer_infos = [SAGEInfo("node", sampler, FLAGS.samples_1, 2*FLAGS.dim_1),
SAGEInfo("node", sampler, FLAGS.samples_2, 2*FLAGS.dim_2)]
model = SampleAndAggregate(placeholders,
features,
adj_info,
minibatch.deg,
layer_infos=layer_infos,
aggregator_type="gcn",
model_size=FLAGS.model_size,
identity_dim = FLAGS.identity_dim,
concat=False,
logging=True)
elif FLAGS.model == 'graphsage_seq':
sampler = UniformNeighborSampler(adj_info)
layer_infos = [SAGEInfo("node", sampler, FLAGS.samples_1, FLAGS.dim_1),
SAGEInfo("node", sampler, FLAGS.samples_2, FLAGS.dim_2)]
model = SampleAndAggregate(placeholders,
features,
adj_info,
minibatch.deg,
layer_infos=layer_infos,
identity_dim = FLAGS.identity_dim,
aggregator_type="seq",
model_size=FLAGS.model_size,
logging=True)
elif FLAGS.model == 'graphsage_maxpool':
sampler = UniformNeighborSampler(adj_info)
layer_infos = [SAGEInfo("node", sampler, FLAGS.samples_1, FLAGS.dim_1),
SAGEInfo("node", sampler, FLAGS.samples_2, FLAGS.dim_2)]
model = SampleAndAggregate(placeholders,
features,
adj_info,
minibatch.deg,
layer_infos=layer_infos,
aggregator_type="maxpool",
model_size=FLAGS.model_size,
identity_dim = FLAGS.identity_dim,
logging=True)
elif FLAGS.model == 'graphsage_meanpool':
sampler = UniformNeighborSampler(adj_info)
layer_infos = [SAGEInfo("node", sampler, FLAGS.samples_1, FLAGS.dim_1),
SAGEInfo("node", sampler, FLAGS.samples_2, FLAGS.dim_2)]
model = SampleAndAggregate(placeholders,
features,
adj_info,
minibatch.deg,
layer_infos=layer_infos,
aggregator_type="meanpool",
model_size=FLAGS.model_size,
identity_dim = FLAGS.identity_dim,
logging=True)
elif FLAGS.model == 'n2v':
model = Node2VecModel(placeholders, features.shape[0],
minibatch.deg,
#2x because graphsage uses concat
nodevec_dim=2*FLAGS.dim_1,
lr=FLAGS.learning_rate)
else:
raise Exception('Error: model name unrecognized.')
config = tf.ConfigProto(log_device_placement=FLAGS.log_device_placement)
config.gpu_options.allow_growth = True
#config.gpu_options.per_process_gpu_memory_fraction = GPU_MEM_FRACTION
config.allow_soft_placement = True
# Initialize session
sess = tf.Session(config=config)
merged = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(log_dir(), sess.graph)
# Init variables
sess.run(tf.global_variables_initializer(), feed_dict={adj_info_ph: minibatch.adj})
# Train model
train_shadow_mrr = None
shadow_mrr = None
total_steps = 0
avg_time = 0.0
epoch_val_costs = []
train_adj_info = tf.assign(adj_info, minibatch.adj)
val_adj_info = tf.assign(adj_info, minibatch.test_adj)
for epoch in range(FLAGS.epochs):
minibatch.shuffle()
iter = 0
print('Epoch: %04d' % (epoch + 1))
epoch_val_costs.append(0)
while not minibatch.end():
# Construct feed dictionary
feed_dict = minibatch.next_minibatch_feed_dict()
feed_dict.update({placeholders['dropout']: FLAGS.dropout})
t = time.time()
# Training step
outs = sess.run([model.opt_op, model.loss, model.ranks, model.aff_all,
model.mrr, model.outputs1], feed_dict=feed_dict)
train_cost = outs[1]
train_mrr = outs[4]
if train_shadow_mrr is None:
train_shadow_mrr = train_mrr#
else:
train_shadow_mrr -= (1-0.99) * (train_shadow_mrr - train_mrr)
if iter % FLAGS.validate_iter == 0:
# Validation
sess.run(val_adj_info.op)
val_cost, ranks, val_mrr, duration = evaluate(sess, model, minibatch, size=FLAGS.validate_batch_size)
sess.run(train_adj_info.op)
epoch_val_costs[-1] += val_cost
if shadow_mrr is None:
shadow_mrr = val_mrr
else:
shadow_mrr -= (1-0.99) * (shadow_mrr - val_mrr)
#if total_steps % FLAGS.print_every == 0:
# summary_writer.add_summary(outs[0], total_steps)
# Print results
avg_time = (avg_time * total_steps + time.time() - t) / (total_steps + 1)
if total_steps % FLAGS.print_every == 0:
print("Iter:", '%04d' % iter,
"train_loss=", "{:.5f}".format(train_cost),
"train_mrr=", "{:.5f}".format(train_mrr),
"train_mrr_ema=", "{:.5f}".format(train_shadow_mrr), # exponential moving average
"val_loss=", "{:.5f}".format(val_cost),
"val_mrr=", "{:.5f}".format(val_mrr),
"val_mrr_ema=", "{:.5f}".format(shadow_mrr), # exponential moving average
"time=", "{:.5f}".format(avg_time))
iter += 1
total_steps += 1
if total_steps > FLAGS.max_total_steps:
break
if total_steps > FLAGS.max_total_steps:
break
print("Optimization Finished!")
if FLAGS.save_embeddings:
sess.run(val_adj_info.op)
save_val_embeddings(sess, model, minibatch, FLAGS.validate_batch_size, log_dir())
if FLAGS.model == "n2v":
# stopping the gradient for the already trained nodes
train_ids = tf.constant([[id_map[n]] for n in G.nodes_iter() if not G.node[n]['val'] and not G.node[n]['test']],
dtype=tf.int32)
test_ids = tf.constant([[id_map[n]] for n in G.nodes_iter() if G.node[n]['val'] or G.node[n]['test']],
dtype=tf.int32)
update_nodes = tf.nn.embedding_lookup(model.context_embeds, tf.squeeze(test_ids))
no_update_nodes = tf.nn.embedding_lookup(model.context_embeds,tf.squeeze(train_ids))
update_nodes = tf.scatter_nd(test_ids, update_nodes, tf.shape(model.context_embeds))
no_update_nodes = tf.stop_gradient(tf.scatter_nd(train_ids, no_update_nodes, tf.shape(model.context_embeds)))
model.context_embeds = update_nodes + no_update_nodes
sess.run(model.context_embeds)
# run random walks
from graphsage.utils import run_random_walks
nodes = [n for n in G.nodes_iter() if G.node[n]["val"] or G.node[n]["test"]]
start_time = time.time()
pairs = run_random_walks(G, nodes, num_walks=50)
walk_time = time.time() - start_time
test_minibatch = EdgeMinibatchIterator(G,
id_map,
placeholders, batch_size=FLAGS.batch_size,
max_degree=FLAGS.max_degree,
num_neg_samples=FLAGS.neg_sample_size,
context_pairs = pairs,
n2v_retrain=True,
fixed_n2v=True)
start_time = time.time()
print("Doing test training for n2v.")
test_steps = 0
for epoch in range(FLAGS.n2v_test_epochs):
test_minibatch.shuffle()
while not test_minibatch.end():
feed_dict = test_minibatch.next_minibatch_feed_dict()
feed_dict.update({placeholders['dropout']: FLAGS.dropout})
outs = sess.run([model.opt_op, model.loss, model.ranks, model.aff_all,
model.mrr, model.outputs1], feed_dict=feed_dict)
if test_steps % FLAGS.print_every == 0:
print("Iter:", '%04d' % test_steps,
"train_loss=", "{:.5f}".format(outs[1]),
"train_mrr=", "{:.5f}".format(outs[-2]))
test_steps += 1
train_time = time.time() - start_time
save_val_embeddings(sess, model, minibatch, FLAGS.validate_batch_size, log_dir(), mod="-test")
print("Total time: ", train_time+walk_time)
print("Walk time: ", walk_time)
print("Train time: ", train_time)
def main(_argv=None):
print("Loading training data..")
train_data = load_data(FLAGS.train_prefix, load_walks=True)
print("Done loading training data..")
train(train_data)
if __name__ == '__main__':
tf.app.run()
|
[] |
[] |
[
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
|
python
| 2 | 0 | |
kp2d/utils/logging.py
|
# Copyright 2020 Toyota Research Institute. All rights reserved.
"""Logging utilities for training
"""
import os
from termcolor import colored
import horovod.torch as hvd
import numpy as np
import torch
from kp2d.utils.wandb import WandBLogger
def printcolor_single(message, color="white"):
"""Print a message in a certain color"""
print(colored(message, color))
def printcolor(message, color="white"):
"Print a message in a certain color (only rank 0)"
if hvd.rank() == 0:
print(colored(message, color))
class SummaryWriter:
"""Wrapper class for tensorboard and WandB logging"""
def __init__(self, log_path, params,
description=None,
project='monodepth',
entity='tri',
mode='run',
job_type='train',
log_wb=True):
self.log_wb = log_wb
self._global_step = 0
if self.log_wb:
os.environ['WANDB_DIR'] = log_path
self.wb_logger = WandBLogger(
params, description=description,
project=project, entity=entity, mode=mode, job_type=job_type)
@property
def run_name(self):
return self.wb_logger.run_name
@property
def run_url(self):
return self.wb_logger.run_url
@property
def global_step(self):
return self._global_step
def log_wandb(self, value):
self.log_wb = value
def add_scalar(self, tag, scalar_value):
if self.log_wb:
self.wb_logger.log_values(tag, scalar_value, now=False)
def add_image(self, tag, img_tensor):
assert img_tensor.max() <= 1.0
assert (isinstance(img_tensor, torch.Tensor) and img_tensor.device == torch.device(
'cpu')) or isinstance(img_tensor, np.ndarray)
if self.log_wb:
caption = tag
if isinstance(img_tensor, torch.Tensor):
# shape: (C, H, W)
size = tuple(img_tensor.shape[-2:][::-1])
assert img_tensor.shape[0] == 1 or img_tensor.shape[0] == 3, \
'Expects CHW with C=1 or 3, provided {}'.format(img_tensor.shape)
self.wb_logger.log_tensor_image(img_tensor * 255, tag, caption, size=size, now=False)
else:
# shape: (H, W, C)
size = tuple(img_tensor.shape[:2][::-1])
assert img_tensor.shape[-1] == 1 or img_tensor.shape[-1] == 3, \
'Expects HWC with C=1 or 3, provided {}'.format(img_tensor.shape)
self.wb_logger.log_numpy_image((img_tensor * 255).astype(np.uint8), tag, caption, size=size, now=False)
def commit_log(self):
if self.log_wb and self._global_step >= 0:
self.wb_logger.commit_log()
self._global_step += 1
|
[] |
[] |
[
"WANDB_DIR"
] |
[]
|
["WANDB_DIR"]
|
python
| 1 | 0 | |
bgremover/tools/setup.py
|
"""
Name: Setup file
Description: This file contains the setup tool code.
Version: [release][3.2]
Source url: https://github.com/OPHoperHPO/image-background-remove-tool
Author: Anodev (OPHoperHPO)[https://github.com/OPHoperHPO] .
License: Apache License 2.0
License:
Copyright 2020 OPHoperHPO
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 sys
sys.path.append("../")
import os
import gdown
import tarfile
from bgremover.libs.strings import MODELS_NAMES
class Config:
"""Config object"""
# general
arc_name = "model.tar.gz"
# mobile_net_model
mn_url = "https://github.com/OPHoperHPO/image-background-remove-tool/releases/download/3.2/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz"
mn_dir = os.path.join("..", "models", "mobile_net_model")
# xception_model
xc_url = "https://github.com/OPHoperHPO/image-background-remove-tool/releases/download/3.2/deeplabv3_pascal_train_aug_2018_01_04.tar.gz"
xc_dir = os.path.join("..", "models", "xception_model")
# u2net
u2_url = "https://github.com/OPHoperHPO/image-background-remove-tool/releases/download/3.2/u2net.pth"
u2_dir = os.environ['MODEL_DIR']
# basnet
bn_url = "https://github.com/OPHoperHPO/image-background-remove-tool/releases/download/3.2/basnet.pth"
bn_dir = os.path.join("..", "models", "basnet")
# u2netp
u2p_url = "https://github.com/OPHoperHPO/image-background-remove-tool/releases/download/3.2/u2netp.pth"
u2p_dir = os.path.join("..", "models", "u2netp")
def prepare():
"""Creates folders"""
print("Create folders")
try:
if not os.path.exists(Config.mn_dir):
os.makedirs(Config.mn_dir)
if not os.path.exists(Config.xc_dir):
os.makedirs(Config.xc_dir)
if not os.path.exists(Config.u2_dir):
os.makedirs(Config.u2_dir)
if not os.path.exists(Config.u2p_dir):
os.makedirs(Config.u2p_dir)
if not os.path.exists(Config.bn_dir):
os.makedirs(Config.bn_dir)
except BaseException as e:
print("Error creating model folders! Error:", e)
exit(1)
return True
def download():
"""Loads model archives"""
path_mn = os.path.join(Config.mn_dir, Config.arc_name)
path_xc = os.path.join(Config.xc_dir, Config.arc_name)
try:
if os.path.exists(path_mn): # Clean old files
os.remove(path_mn)
if os.path.exists(path_xc):
os.remove(path_xc)
print("Start download model archives!")
gdown.download(Config.mn_url, path_mn, quiet=False)
gdown.download(Config.xc_url, path_xc, quiet=False)
gdown.download(Config.u2_url, os.path.join(Config.u2_dir, "u2net.pth"), quiet=False)
gdown.download(Config.u2p_url, os.path.join(Config.u2p_dir, "u2netp.pth"), quiet=False)
gdown.download(Config.bn_url, os.path.join(Config.bn_dir, "basnet.pth"), quiet=False)
print("Download finished!")
except BaseException as e:
print("Error download model archives! Error:", e)
exit(1)
return True
def untar():
"""Untar archives"""
path_mn = os.path.join(Config.mn_dir, Config.arc_name)
path_xc = os.path.join(Config.xc_dir, Config.arc_name)
try:
print("Start unpacking")
if path_mn.endswith("tar.gz"):
tar = tarfile.open(path_mn, "r:gz")
tar.extractall(path=Config.mn_dir)
tar.close()
os.rename(os.path.join(Config.mn_dir, "deeplabv3_mnv2_pascal_train_aug"),
os.path.join(Config.mn_dir, "model"))
print("Unpacking 1 archive finished!")
if path_xc.endswith("tar.gz"):
tar = tarfile.open(path_xc, "r:gz")
tar.extractall(path=Config.xc_dir)
tar.close()
os.rename(os.path.join(Config.xc_dir, "deeplabv3_pascal_train_aug"),
os.path.join(Config.xc_dir, "model"))
print("Unpacking 2 archive finished!")
except BaseException as e:
print("Unpacking error! Error:", e)
exit(1)
return True
def clean():
"""Cleans temp files"""
path_mn = os.path.join(Config.mn_dir, Config.arc_name)
path_xc = os.path.join(Config.xc_dir, Config.arc_name)
try:
if os.path.exists(path_mn): # Clean old files
os.remove(path_mn)
if os.path.exists(path_xc):
os.remove(path_xc)
except BaseException as e:
print("Cleaning error! Error:", e)
return True
def setup():
"""Performs program setup before use"""
if prepare():
if download():
if untar():
if clean():
pass
def cli():
print("Choose which model you want to install:\n{}\nall".format('\n'.join(MODELS_NAMES)))
model_name = input("Enter model name: ")
if model_name == "all":
setup()
elif model_name == "u2net":
if not os.path.exists(Config.u2_dir):
os.makedirs(Config.u2_dir)
gdown.download(Config.u2_url, os.path.join(Config.u2_dir, "u2net.pth"), quiet=False)
elif model_name == "basnet":
if not os.path.exists(Config.bn_dir):
os.makedirs(Config.bn_dir)
gdown.download(Config.bn_url, os.path.join(Config.bn_dir, "basnet.pth"), quiet=False)
elif model_name == "u2netp":
if not os.path.exists(Config.u2p_dir):
os.makedirs(Config.u2p_dir)
gdown.download(Config.u2p_url, os.path.join(Config.u2p_dir, "u2netp.pth"), quiet=False)
elif model_name == "xception_model":
if not os.path.exists(Config.xc_dir):
os.makedirs(Config.xc_dir)
path_xc = os.path.join(Config.xc_dir, Config.arc_name)
gdown.download(Config.xc_url, path_xc, quiet=False)
if path_xc.endswith("tar.gz"):
tar = tarfile.open(path_xc, "r:gz")
tar.extractall(path=Config.xc_dir)
tar.close()
os.rename(os.path.join(Config.xc_dir, "deeplabv3_pascal_train_aug"),
os.path.join(Config.xc_dir, "model"))
print("Unpacking archive finished!")
if os.path.exists(path_xc):
os.remove(path_xc)
elif model_name == "mobile_net_model":
if not os.path.exists(Config.mn_dir):
os.makedirs(Config.mn_dir)
path_mn = os.path.join(Config.mn_dir, Config.arc_name)
if os.path.exists(path_mn): # Clean old files
os.remove(path_mn)
gdown.download(Config.mn_url, path_mn, quiet=False)
if path_mn.endswith("tar.gz"):
tar = tarfile.open(path_mn, "r:gz")
tar.extractall(path=Config.mn_dir)
tar.close()
os.rename(os.path.join(Config.mn_dir, "deeplabv3_mnv2_pascal_train_aug"),
os.path.join(Config.mn_dir, "model"))
print("Unpacking archive finished!")
if os.path.exists(path_mn): # Clean old files
os.remove(path_mn)
else:
print("ERROR! You specified an invalid model type! EXIT!")
exit(1)
print("Setup finished! :)")
if __name__ == "__main__":
cli()
|
[] |
[] |
[
"MODEL_DIR"
] |
[]
|
["MODEL_DIR"]
|
python
| 1 | 0 | |
conf/conf.go
|
package conf
import (
"bufio"
_ "embed"
"encoding/json"
"fmt"
"os"
"runtime"
"strconv"
"time"
"github.com/joho/godotenv"
"genshin-sign-helper/model"
"genshin-sign-helper/util"
"genshin-sign-helper/util/constant"
)
var (
LogLevel string // 显示日志等级
LogDetailed bool // 是否显示详细的日志内容
Cycle int // 签到周期(小时)
SignTime int // 签到时间,用于确定几点签到,如果当前运行时间大于签到时间,且当日未签到,则立刻签到
SignInterval int // 每个账号签到的时间间隔(分钟)
)
var (
RunDir string // 运行目录
EnvFile string // .env目录
RecordFile string // record.json目录
LogFile string // log.txt目录
CookieFile string // cookie.txt目录
)
var SignRecordJSON *model.SignRecordJSON = nil
//go:embed conf.env
var confFile []byte
func Init() {
InitFile()
SendEnv()
ReadRecordJSON()
}
func InitFile() {
RunDir = util.GetCurrentDir()
s := "%v/%v"
if runtime.GOOS == "windows" {
s = "%v\\%v"
}
EnvFile = fmt.Sprintf(s, RunDir, constant.EnvFileName)
RecordFile = fmt.Sprintf(s, RunDir, constant.RecordFileName)
LogFile = fmt.Sprintf(s, RunDir, constant.LogFileName)
CookieFile = fmt.Sprintf(s, RunDir, constant.CookieFileName)
if !util.CheckFileIsExist(EnvFile) {
osFile, err := os.OpenFile(EnvFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
panic(err)
}
if _, err = osFile.Write(confFile); err != nil {
panic(err)
}
}
if !util.CheckFileIsExist(CookieFile) {
create, err := os.Create(CookieFile)
if err != nil {
panic(err)
}
if err := create.Close(); err != nil {
panic(err)
}
}
if !util.CheckFileIsExist(RecordFile) {
_, err := os.Create(RecordFile)
if err != nil {
panic(err)
}
}
}
//SendEnv 读取.env配置文件
func SendEnv() {
err := godotenv.Load(EnvFile)
if err != nil {
panic(err)
}
LogLevel = os.Getenv("LOG_LEVEL")
//var err error
LogDetailed, err = strconv.ParseBool(os.Getenv("LOG_DETAILED"))
if err != nil {
LogDetailed = false
}
cycle64, err := strconv.ParseInt(os.Getenv("CYCLE"), 10, 8)
if err != nil {
Cycle = 1
}
Cycle = int(cycle64)
signTime64, err := strconv.ParseInt(os.Getenv("SIGN_TIME"), 10, 8)
if err != nil {
SignTime = 7
}
SignTime = int(signTime64)
signInterval64, err := strconv.ParseInt(os.Getenv("SIGN_INTERVAL"), 10, 8)
if err != nil {
SignTime = 3
}
SignInterval = int(signInterval64)
}
//ReadRecordJSON 读取保存签到记录的json
func ReadRecordJSON() {
body, err := util.ReadFile(RecordFile)
if err == nil {
if err := json.Unmarshal(body, &SignRecordJSON); err != nil {
SignRecordJSON = nil
}
}
if SignRecordJSON == nil {
SignRecordJSON = &model.SignRecordJSON{
Time: time.Unix(1600131600, 0), //1601254800
Roles: map[string]model.RolesJSON{},
}
}
}
//SendRecordJSON 储存保存签到记录的json
func SendRecordJSON() (err error) {
file, err := os.OpenFile(RecordFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
return err
}
defer file.Close()
toJSON, err := util.StructToJSON(SignRecordJSON)
if err != nil {
return err
}
fileIO := bufio.NewWriter(file)
_, err = fileIO.Write(toJSON)
err = fileIO.Flush()
if err != nil {
return err
}
return err
}
|
[
"\"LOG_LEVEL\"",
"\"LOG_DETAILED\"",
"\"CYCLE\"",
"\"SIGN_TIME\"",
"\"SIGN_INTERVAL\""
] |
[] |
[
"LOG_LEVEL",
"LOG_DETAILED",
"SIGN_TIME",
"SIGN_INTERVAL",
"CYCLE"
] |
[]
|
["LOG_LEVEL", "LOG_DETAILED", "SIGN_TIME", "SIGN_INTERVAL", "CYCLE"]
|
go
| 5 | 0 | |
modules/common_builder.py
|
# ************************************************************
# |docname| - Routines shared between the server and WAF build
# ************************************************************
#
# Imports
# =======
# These are listed in the order prescribed by `PEP 8
# <http://www.python.org/dev/peps/pep-0008/#imports>`_.
#
# Standard library
# ----------------
import atexit
import os
from pathlib import Path
import random
import subprocess
from tempfile import TemporaryDirectory
import threading
import time
# Third-party imports
# -------------------
# None.
# Local imports
# -------------
# None.
#
#
# Globals
# =======
# Set up thread-local storage
_tls = threading.local()
# Simulation scripts and checks
# =============================
# Return the string needed to run a SIM30 simulation.
def get_sim_str_sim30(
# A string giving the MCU to simulate.
sim_mcu,
# The ELF file to load and simulate.
elf_file,
# The name of an output file for UART output.
uart_out_file,
# Additional, optional commands.
optional_commands="",
):
# Spaces in file names break the simulator.
if " " in elf_file:
raise ValueError(
"sim30 does not support spaces in file names, which occurs in {}.".format(
elf_file
)
)
return (
# In SIM30, type ? to get help. See also :alink:`the manual <asmguide#page=218>`.
#
# .. _supported devices:
#
# Select the dsPIC33E. From the help:
# ``LD <devicename> -Load Device: dspic30super dspic33epsuper pic24epsuper pic24fpsuper pic24super``
"LD {}\n"
# Load in the pic24_intro.elf. From the help:
# ``LC <filename> -Load COFF/ELF File``
"LC {}\n"
# Have the simulator save UART1 IO to a file. From the help:
# ``IO [stdin [stdout]] -Input/Output On (use nul if no stdin and/or stdout)``
"IO nul {}\n"
# Reset the processor. From the help:
# ``RP -Reset processor POR``
"RP\n"
# Set a breakpoint at the end of the program (the label ``_done``).
# From the help:
# ``BS <location> ...[locations] -Breakpoint Set``
"BS _done\n"
# Include any other setup (stimulus file, pin assignments, etc.).
"{}"
# Run the program. From the help:
# ; ``E -Execute``
"E 10000\n"
# Quit. From the help:
# ``Q -Quit``
"Q\n"
).format(sim_mcu, elf_file, uart_out_file, optional_commands)
# Return the string needed to run a simulation under MDB.
def get_sim_str_mdb(
# A string giving the MCU to simulate.
sim_mcu,
# The ELF file to load and simulate.
elf_file,
# The name of an output file for UART output.
uart_out_file,
# Additional, optional commands.
optional_commands="",
):
return get_sim_setup_str_mdb(sim_mcu) + get_sim_run_str_mdb(
elf_file, uart_out_file, optional_commands
)
# Return the string needed to run a simulation under MDB.
def get_sim_setup_str_mdb(
# A string giving the MCU to simulate.
sim_mcu,
):
return (
# See :alink:`the MDB manual <http://ww1.microchip.com/downloads/en/DeviceDoc/50002102D.pdf>` for more information.
#
# Select the device to simulate.
"device {}\n"
# Set up to capture UART 1 output to a file. The simulator produces an error if a file name isn't given here.
"set uart1io.uartioenabled true\n"
"set uart1io.output file\n"
# Configure the clock to match the setup in the PIC24 library ``lib/include/pic24_clockfreq.h`` named ``SIM_CLOCK``.
"set oscillator.frequency 1\n"
"set oscillator.frequencyunit Mega\n"
).format(sim_mcu)
def get_sim_run_str_mdb(
# The ELF file to load and simulate.
elf_file,
# The name of an output file for UART output.
uart_out_file,
# Additional, optional commands.
optional_commands="",
):
return (
# Specify the path to the output file.
"set uart1io.outputfile {}\n"
# This is required to get the above setting applied.
"hwtool sim\n"
# Load in the program.
'program "{}"\n'
# Set a breakpoint at the end of the program (the label ``_done``).
"break _done\n"
# Include any other setup (stimulus file, pin assignments, etc.).
"{}"
# Run the program. Wait a time in ms for it to finish.
"run\n"
"wait 6000\n"
# In case the wait time expired before encountering a breakpoint, halt the simulation.
"halt\n"
# Remove all breakpoints.
"delete\n"
# Tell the runner that the simulation is finished.
"echo Simulation finished.\n"
# Exit the simulator. For some reason, it takes a while for MDB to exit. This is commented out, so that mdb will stay running until it's shut down after running many sims.
##"quit\n"
).format(
# MDB starting in MPLAB X v5.35 doesn't understand Windows-style paths (although using \\ instead of \ does work). It does work with Posix paths.
Path(uart_out_file).as_posix(),
Path(elf_file).as_posix(),
optional_commands,
)
# Get a verification code (a random, 32-bit value).
def get_verification_code():
return random.randrange(0, 2 ** 32)
# Returns True if a simulation produced the correct answer.
def check_sim_out(out_str, verification_code):
sl = out_str.splitlines()
second_to_last_line = sl[-2] if len(sl) >= 2 else ""
last_line = sl[-1] if len(sl) >= 1 else ""
return (second_to_last_line == "Correct.") and (
last_line == "{}".format(verification_code)
)
# Run MDB
# =======
# This function runs a simulation, verifying that the simulation results
# are correct, using the newer MDB simulator.
#
# Inputs: path_to_elf_binary
#
# Outputs: sim_output_file
def sim_run_mdb(
# A path to the MDB script.
mdb_path,
# The microcontroller to simulate; for example, "dsPIC33EP128GP502".
mcu_name,
# A path to the binary (typically in .elf format) to simulate.
sim_binary_path,
):
# Get or create an instance of the simulator.
po = _tls.__dict__.get("po")
if (
# If the simulator hasn't been started, ...
(not po)
or
# ... or it died, (re)create it.
(po and po.poll() is not None)
):
# Create a temp file for the simulation results. Since the simulator doesn't close the file after the simulation finishes, it can't be deleted. Instead, we need a single file to be used for a simulation, read, then truncated.
_tls.tempdir = tempdir = TemporaryDirectory()
_tls.simout_path = Path(_tls.tempdir.name) / "mdb_simout.txt"
_tls.simout_file = simout_file = open(
_tls.simout_path, "w+", encoding="utf-8", errors="backslashreplace"
)
# Start the simulator.
po = subprocess.Popen(
[
mdb_path,
# These options must go before the ``--jar`` option, meaning they require hand edits to ``mdb.bat/sh``; they can't be passed as paramters (which are placed after ```--jar`` by ``mdb.bat/sh``.)
#
# Per a conversation with Microchip's support team, this disables the start-up check for new language packs, which takes several seconds to complete.
##"-Dpackslib.workonline=false",
# Java, by default, doesn't free memory until it gets low, making this a memory hog. On Windows, it starts up at around 400 MB. This seems to keep it below 600 MB.
##"-Xmx750M",
],
text=True,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=os.environ,
)
s = get_sim_setup_str_mdb(mcu_name)
po.stdin.write(s)
po.stdin.flush()
_tls.po = po
def on_exit():
# Shut down the simulator and end the simulation process.
po.communicate("quit\n")
# Remove the simout file.
simout_file.close()
tempdir.cleanup()
atexit.register(on_exit)
# Delete any previous simulation results.
_tls.simout_file.truncate(0)
# Run the simulation.
s = get_sim_run_str_mdb(sim_binary_path, _tls.simout_path)
po.stdin.write(s)
po.stdin.flush()
# Wait for it to finish by watching stdout.
time_left = 10
while time_left > 0:
line = po.stdout.readline()
if not line:
time.sleep(0.1)
time_left -= 0.1
continue
if line == ">/*Simulation finished.*/\n":
break
# Read then return the result, starting from the beginning of the file.
_tls.simout_file.seek(0)
return _tls.simout_file.read()
# Celery config
# =============
# Provide the `Celery configuration <https://docs.celeryproject.org/en/latest/userguide/application.html#configuration>`_.
celery_config = dict(
# Use `Redis with Celery <http://docs.celeryproject.org/en/latest/getting-started/brokers/redis.html#configuration>`_.
broker_url=os.environ.get("REDIS_URI", "redis://localhost:6379/0"),
result_backend=os.environ.get("REDIS_URI", "redis://localhost:6379/0"),
# Given that tasks time out in 60 seconds, expire them after that. See `result_expires <https://docs.celeryproject.org/en/latest/userguide/configuration.html#result-expires>`.
result_expires=120,
# This follows the `Redis caveats <http://docs.celeryproject.org/en/latest/getting-started/brokers/redis.html#redis-caveats>`_.
broker_transport_options={
# 1 hour.
"visibility_timeout": 3600,
"fanout_prefix": True,
"fanout_patterns": True,
},
)
|
[] |
[] |
[
"REDIS_URI"
] |
[]
|
["REDIS_URI"]
|
python
| 1 | 0 | |
integration/integration_test.go
|
package integration_test
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
)
const (
configDir = "./fixture"
)
// cf runs the cf CLI with the specified args.
func cf(args ...string) ([]byte, error) {
cmd := exec.Command("cf", args...)
out, err := cmd.Output()
if err != nil {
return out, fmt.Errorf("cf %s: %v", strings.Join(args, " "), err)
}
return out, nil
}
var (
outPath string
systemDomain string
userID string
password string
clientSecret string
)
var _ = BeforeSuite(func() {
SetDefaultEventuallyTimeout(time.Second * 30)
systemDomain = os.Getenv("SYSTEM_DOMAIN")
userID = "admin"
password = os.Getenv("CF_ADMIN_PASSWORD")
clientSecret = os.Getenv("ADMIN_CLIENT_SECRET")
_, err := cf("login", "--skip-ssl-validation", "-a", "https://api."+systemDomain, "-u", userID, "-p", password)
Expect(err).ShouldNot(HaveOccurred())
outPath, err = Build("github.com/vmwarepivotallabs/cf-mgmt/cmd/cf-mgmt")
Expect(err).ShouldNot(HaveOccurred())
})
var _ = AfterSuite(func() {
CleanupBuildArtifacts()
})
var _ = Describe("cf-mgmt cli", func() {
Describe("running against pcfdev", func() {
Describe("orgs, spaces, isolation segments", func() {
BeforeEach(func() {
fmt.Println("******** Before called *********")
cf("delete-org", "-f", "test1")
cf("delete-org", "-f", "test2")
cf("delete-org", "-f", "rogue-org1")
cf("delete-org", "-f", "rogue-org2")
})
AfterEach(func() {
fmt.Println("******** after called *********")
os.RemoveAll("./config")
cf("delete-org", "-f", "test1")
cf("delete-org", "-f", "test2")
cf("delete-org", "-f", "rogue-org1")
cf("delete-org", "-f", "rogue-org2")
})
It("should complete successfully", func() {
orgs, err := cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(orgs).ShouldNot(ContainElement("test1"))
Expect(orgs).ShouldNot(ContainElement("test2"))
By("creating orgs")
createOrgsCommand := exec.Command(outPath, "create-orgs",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", userID,
"--password", password,
"--client-secret", clientSecret)
session, err := Start(createOrgsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
orgs, err = cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgs, []byte("test1"))).Should(BeTrue())
Expect(bytes.Contains(orgs, []byte("test2"))).Should(BeTrue())
By("deleting unused orgs")
deleteOrgsCommand := exec.Command(outPath, "delete-orgs",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", userID,
"--password", password,
"--client-secret", clientSecret)
session, err = Start(deleteOrgsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
orgs, err = cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgs, []byte("system"))).Should(BeTrue())
Expect(bytes.Contains(orgs, []byte("rogue-org1"))).ShouldNot(BeTrue())
Expect(bytes.Contains(orgs, []byte("rogue-org1"))).ShouldNot(BeTrue())
By("creating spaces")
createSpacesCommand := exec.Command(outPath, "create-spaces",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", userID,
"--password", password,
"--client-secret", clientSecret)
session, err = Start(createSpacesCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
_, err = cf("target", "-o", "test1")
Expect(err).ShouldNot(HaveOccurred())
spaces, err := cf("spaces")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaces, []byte("dev"))).Should(BeTrue())
Expect(bytes.Contains(spaces, []byte("prod"))).Should(BeTrue())
_, err = cf("target", "-o", "test2")
Expect(err).ShouldNot(HaveOccurred())
spaces, err = cf("spaces")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaces, []byte("No spaces found"))).Should(BeTrue())
By("updating isolation segments")
updateIsoSegmentsCommand := exec.Command(outPath, "isolation-segments",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", userID,
"--password", password,
"--client-secret", clientSecret)
session, err = Start(updateIsoSegmentsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
is, err := cf("isolation-segments")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(is, []byte("test1-iso-segment"))).Should(BeTrue())
Expect(bytes.Contains(is, []byte("test2-iso-segment"))).Should(BeTrue())
// test1-iso-segment should be default for org test1, space dev
cf("target", "-o", "test1")
spaceInfo, err := cf("space", "dev")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaceInfo, []byte("test1-iso-segment"))).Should(BeTrue())
// test2-iso-segment should be default for all of org test2
orgInfo, err := cf("org", "test2")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgInfo, []byte("test2-iso-segment"))).Should(BeTrue())
})
It("should complete successfully without password", func() {
orgs, err := cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgs, []byte("test1"))).ShouldNot(BeTrue())
Expect(bytes.Contains(orgs, []byte("test2"))).ShouldNot(BeTrue())
By("creating orgs")
createOrgsCommand := exec.Command(outPath, "create-orgs",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", "cf-mgmt",
"--client-secret", "cf-mgmt-secret")
session, err := Start(createOrgsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
orgs, err = cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgs, []byte("test1"))).Should(BeTrue())
Expect(bytes.Contains(orgs, []byte("test2"))).Should(BeTrue())
By("deleting unused orgs")
deleteOrgsCommand := exec.Command(outPath, "delete-orgs",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", "cf-mgmt",
"--client-secret", "cf-mgmt-secret")
session, err = Start(deleteOrgsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
orgs, err = cf("orgs")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgs, []byte("system"))).Should(BeTrue())
Expect(bytes.Contains(orgs, []byte("rogue-org1"))).ShouldNot(BeTrue())
Expect(bytes.Contains(orgs, []byte("rogue-org2"))).ShouldNot(BeTrue())
By("creating spaces")
createSpacesCommand := exec.Command(outPath, "create-spaces",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", "cf-mgmt",
"--client-secret", "cf-mgmt-secret")
session, err = Start(createSpacesCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
_, err = cf("target", "-o", "test1")
Expect(err).ShouldNot(HaveOccurred())
spaces, err := cf("spaces")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaces, []byte("dev"))).Should(BeTrue())
Expect(bytes.Contains(spaces, []byte("prod"))).Should(BeTrue())
_, err = cf("target", "-o", "test2")
Expect(err).ShouldNot(HaveOccurred())
spaces, err = cf("spaces")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaces, []byte("No spaces found"))).Should(BeTrue())
By("updating isolation segments")
updateIsoSegmentsCommand := exec.Command(outPath, "isolation-segments",
"--config-dir", configDir,
"--system-domain", systemDomain,
"--user-id", "cf-mgmt",
"--client-secret", "cf-mgmt-secret")
session, err = Start(updateIsoSegmentsCommand, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(Exit(0))
is, err := cf("isolation-segments")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(is, []byte("test1-iso-segment"))).Should(BeTrue())
Expect(bytes.Contains(is, []byte("test2-iso-segment"))).Should(BeTrue())
// test1-iso-segment should be default for org test1, space dev
cf("target", "-o", "test1")
spaceInfo, err := cf("space", "dev")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(spaceInfo, []byte("test1-iso-segment"))).Should(BeTrue())
// test2-iso-segment should be default for all of org test2
orgInfo, err := cf("org", "test2")
Expect(err).ShouldNot(HaveOccurred())
Expect(bytes.Contains(orgInfo, []byte("test2-iso-segment"))).Should(BeTrue())
})
})
})
})
|
[
"\"SYSTEM_DOMAIN\"",
"\"CF_ADMIN_PASSWORD\"",
"\"ADMIN_CLIENT_SECRET\""
] |
[] |
[
"CF_ADMIN_PASSWORD",
"SYSTEM_DOMAIN",
"ADMIN_CLIENT_SECRET"
] |
[]
|
["CF_ADMIN_PASSWORD", "SYSTEM_DOMAIN", "ADMIN_CLIENT_SECRET"]
|
go
| 3 | 0 | |
app/config/wsgi.py
|
"""
WSGI config for the project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
cmd/thanos/main.go
|
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"runtime/debug"
"syscall"
gmetrics "github.com/armon/go-metrics"
gprom "github.com/armon/go-metrics/prometheus"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/oklog/run"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"github.com/thanos-io/thanos/pkg/runutil"
"github.com/thanos-io/thanos/pkg/tracing"
"github.com/thanos-io/thanos/pkg/tracing/client"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
"gopkg.in/alecthomas/kingpin.v2"
)
const (
logFormatLogfmt = "logfmt"
logFormatJson = "json"
)
type setupFunc func(*run.Group, log.Logger, *prometheus.Registry, opentracing.Tracer, bool) error
func main() {
if os.Getenv("DEBUG") != "" {
runtime.SetMutexProfileFraction(10)
runtime.SetBlockProfileRate(10)
}
app := kingpin.New(filepath.Base(os.Args[0]), "A block storage based long-term storage for Prometheus")
app.Version(version.Print("thanos"))
app.HelpFlag.Short('h')
debugName := app.Flag("debug.name", "Name to add as prefix to log lines.").Hidden().String()
logLevel := app.Flag("log.level", "Log filtering level.").
Default("info").Enum("error", "warn", "info", "debug")
logFormat := app.Flag("log.format", "Log format to use.").
Default(logFormatLogfmt).Enum(logFormatLogfmt, logFormatJson)
tracingConfig := regCommonTracingFlags(app)
cmds := map[string]setupFunc{}
registerSidecar(cmds, app, "sidecar")
registerStore(cmds, app, "store")
registerQuery(cmds, app, "query")
registerRule(cmds, app, "rule")
registerCompact(cmds, app, "compact")
registerBucket(cmds, app, "bucket")
registerDownsample(cmds, app, "downsample")
registerReceive(cmds, app, "receive")
registerChecks(cmds, app, "check")
cmd, err := app.Parse(os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "Error parsing commandline arguments"))
app.Usage(os.Args[1:])
os.Exit(2)
}
var logger log.Logger
{
var lvl level.Option
switch *logLevel {
case "error":
lvl = level.AllowError()
case "warn":
lvl = level.AllowWarn()
case "info":
lvl = level.AllowInfo()
case "debug":
lvl = level.AllowDebug()
default:
panic("unexpected log level")
}
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
if *logFormat == logFormatJson {
logger = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
}
logger = level.NewFilter(logger, lvl)
if *debugName != "" {
logger = log.With(logger, "name", *debugName)
}
logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
}
metrics := prometheus.NewRegistry()
metrics.MustRegister(
version.NewCollector("thanos"),
prometheus.NewGoCollector(),
prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
)
prometheus.DefaultRegisterer = metrics
// Memberlist uses go-metrics
sink, err := gprom.NewPrometheusSink()
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "%s command failed", cmd))
os.Exit(1)
}
gmetricsConfig := gmetrics.DefaultConfig("thanos_" + cmd)
gmetricsConfig.EnableRuntimeMetrics = false
if _, err = gmetrics.NewGlobal(gmetricsConfig, sink); err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "%s command failed", cmd))
os.Exit(1)
}
var g run.Group
var tracer opentracing.Tracer
// Setup optional tracing.
{
ctx := context.Background()
var closer io.Closer
var confContentYaml []byte
confContentYaml, err = tracingConfig.Content()
if err != nil {
level.Error(logger).Log("msg", "getting tracing config failed", "err", err)
os.Exit(1)
}
if len(confContentYaml) == 0 {
level.Info(logger).Log("msg", "Tracing will be disabled")
tracer = client.NoopTracer()
} else {
tracer, closer, err = client.NewTracer(ctx, logger, metrics, confContentYaml)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "tracing failed"))
os.Exit(1)
}
}
// This is bad, but Prometheus does not support any other tracer injections than just global one.
// TODO(bplotka): Work with basictracer to handle gracefully tracker mismatches, and also with Prometheus to allow
// tracer injection.
opentracing.SetGlobalTracer(tracer)
ctx, cancel := context.WithCancel(ctx)
g.Add(func() error {
<-ctx.Done()
return ctx.Err()
}, func(error) {
if closer != nil {
if err := closer.Close(); err != nil {
level.Warn(logger).Log("msg", "closing tracer failed", "err", err)
}
}
cancel()
})
}
if err := cmds[cmd](&g, logger, metrics, tracer, *logLevel == "debug"); err != nil {
level.Error(logger).Log("err", errors.Wrapf(err, "%s command failed", cmd))
os.Exit(1)
}
// Listen for termination signals.
{
cancel := make(chan struct{})
g.Add(func() error {
return interrupt(logger, cancel)
}, func(error) {
close(cancel)
})
}
if err := g.Run(); err != nil {
level.Error(logger).Log("msg", "running command failed", "err", err)
os.Exit(1)
}
level.Info(logger).Log("msg", "exiting")
}
func interrupt(logger log.Logger, cancel <-chan struct{}) error {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
select {
case s := <-c:
level.Info(logger).Log("msg", "caught signal. Exiting.", "signal", s)
return nil
case <-cancel:
return errors.New("canceled")
}
}
func registerProfile(mux *http.ServeMux) {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.Handle("/debug/pprof/block", pprof.Handler("block"))
mux.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
}
func registerMetrics(mux *http.ServeMux, g prometheus.Gatherer) {
mux.Handle("/metrics", promhttp.HandlerFor(g, promhttp.HandlerOpts{}))
}
// defaultGRPCServerOpts returns default gRPC server opts that includes:
// - request histogram
// - tracing
// - panic recovery with panic counter
func defaultGRPCServerOpts(logger log.Logger, reg *prometheus.Registry, tracer opentracing.Tracer, cert, key, clientCA string) ([]grpc.ServerOption, error) {
met := grpc_prometheus.NewServerMetrics()
met.EnableHandlingTimeHistogram(
grpc_prometheus.WithHistogramBuckets([]float64{
0.001, 0.01, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4,
}),
)
panicsTotal := prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_grpc_req_panics_recovered_total",
Help: "Total number of gRPC requests recovered from internal panic.",
})
grpcPanicRecoveryHandler := func(p interface{}) (err error) {
panicsTotal.Inc()
level.Error(logger).Log("msg", "recovered from panic", "panic", p, "stack", debug.Stack())
return status.Errorf(codes.Internal, "%s", p)
}
reg.MustRegister(met, panicsTotal)
opts := []grpc.ServerOption{
grpc.MaxSendMsgSize(math.MaxInt32),
grpc_middleware.WithUnaryServerChain(
met.UnaryServerInterceptor(),
tracing.UnaryServerInterceptor(tracer),
grpc_recovery.UnaryServerInterceptor(grpc_recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
),
grpc_middleware.WithStreamServerChain(
met.StreamServerInterceptor(),
tracing.StreamServerInterceptor(tracer),
grpc_recovery.StreamServerInterceptor(grpc_recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
),
}
if key == "" && cert == "" {
if clientCA != "" {
return nil, errors.New("when a client CA is used a server key and certificate must also be provided")
}
level.Info(logger).Log("msg", "disabled TLS, key and cert must be set to enable")
return opts, nil
}
if key == "" || cert == "" {
return nil, errors.New("both server key and certificate must be provided")
}
tlsCfg := &tls.Config{
MinVersion: tls.VersionTLS12,
}
tlsCert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, errors.Wrap(err, "server credentials")
}
level.Info(logger).Log("msg", "enabled gRPC server side TLS")
tlsCfg.Certificates = []tls.Certificate{tlsCert}
if clientCA != "" {
caPEM, err := ioutil.ReadFile(clientCA)
if err != nil {
return nil, errors.Wrap(err, "reading client CA")
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(caPEM) {
return nil, errors.Wrap(err, "building client CA")
}
tlsCfg.ClientCAs = certPool
tlsCfg.ClientAuth = tls.RequireAndVerifyClientCert
level.Info(logger).Log("msg", "gRPC server TLS client verification enabled")
}
return append(opts, grpc.Creds(credentials.NewTLS(tlsCfg))), nil
}
// metricHTTPListenGroup is a run.Group that servers HTTP endpoint with only Prometheus metrics.
func metricHTTPListenGroup(g *run.Group, logger log.Logger, reg *prometheus.Registry, httpBindAddr string) error {
mux := http.NewServeMux()
registerMetrics(mux, reg)
registerProfile(mux)
l, err := net.Listen("tcp", httpBindAddr)
if err != nil {
return errors.Wrap(err, "listen metrics address")
}
g.Add(func() error {
level.Info(logger).Log("msg", "Listening for metrics", "address", httpBindAddr)
return errors.Wrap(http.Serve(l, mux), "serve metrics")
}, func(error) {
runutil.CloseWithLogOnErr(logger, l, "metric listener")
})
return nil
}
|
[
"\"DEBUG\""
] |
[] |
[
"DEBUG"
] |
[]
|
["DEBUG"]
|
go
| 1 | 0 | |
src/config/default.py
|
import os
import urllib
# Flask settings
FLASK_DEBUG = True # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = f"mssql+pyodbc:///?odbc_connect={urllib.parse.quote_plus(str(os.getenv('SQL_AZURE_CONNSTR')))}"
SQLALCHEMY_POOL_SIZE = 20
SQLALCHEMY_ECHO = True if '1' == os.environ.get('SQLALCHEMY_ECHO', None) else False
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
[] |
[] |
[
"SQLALCHEMY_ECHO",
"SQL_AZURE_CONNSTR"
] |
[]
|
["SQLALCHEMY_ECHO", "SQL_AZURE_CONNSTR"]
|
python
| 2 | 0 | |
src/main/java/com/sparrowwallet/sparrow/io/Storage.java
|
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.Network;
import com.sparrowwallet.drongo.SecureString;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.crypto.*;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.MainApp;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.controlsfx.tools.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Storage {
private static final Logger log = LoggerFactory.getLogger(Storage.class);
public static final ECKey NO_PASSWORD_KEY = ECKey.fromPublicOnly(ECKey.fromPrivate(Utils.hexToBytes("885e5a09708a167ea356a252387aa7c4893d138d632e296df8fbf5c12798bd28")));
private static final DateFormat BACKUP_DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private static final Pattern DATE_PATTERN = Pattern.compile(".+-([0-9]{14}?).*");
public static final String SPARROW_DIR = ".sparrow";
public static final String WINDOWS_SPARROW_DIR = "Sparrow";
public static final String WALLETS_DIR = "wallets";
public static final String WALLETS_BACKUP_DIR = "backup";
public static final String CERTS_DIR = "certs";
public static final String TEMP_BACKUP_PREFIX = "tmp";
public static final List<String> RESERVED_WALLET_NAMES = List.of("temp");
private Persistence persistence;
private File walletFile;
private ECKey encryptionPubKey;
public Storage(File walletFile) {
this(!walletFile.exists() || walletFile.getName().endsWith("." + PersistenceType.DB.getExtension()) ? PersistenceType.DB : PersistenceType.JSON, walletFile);
}
public Storage(PersistenceType persistenceType, File walletFile) {
this.persistence = persistenceType.getInstance();
this.walletFile = walletFile;
}
public Storage(Persistence persistence, File walletFile) {
this.persistence = persistence;
this.walletFile = walletFile;
}
public File getWalletFile() {
return walletFile;
}
public boolean isEncrypted() throws IOException {
if(!walletFile.exists()) {
return false;
}
return persistence.isEncrypted(walletFile);
}
public String getWalletId(Wallet wallet) {
return persistence.getWalletId(this, wallet);
}
public String getWalletName(Wallet wallet) {
return persistence.getWalletName(walletFile, wallet);
}
public String getWalletFileExtension() {
if(walletFile.getName().endsWith("." + getType().getExtension())) {
return getType().getExtension();
}
return "";
}
public WalletBackupAndKey loadUnencryptedWallet() throws IOException, StorageException {
WalletBackupAndKey masterWalletAndKey = persistence.loadWallet(this);
encryptionPubKey = NO_PASSWORD_KEY;
return migrateToDb(masterWalletAndKey);
}
public WalletBackupAndKey loadEncryptedWallet(CharSequence password) throws IOException, StorageException {
WalletBackupAndKey masterWalletAndKey = persistence.loadWallet(this, password);
encryptionPubKey = ECKey.fromPublicOnly(masterWalletAndKey.getEncryptionKey());
return migrateToDb(masterWalletAndKey);
}
public void saveWallet(Wallet wallet) throws IOException, StorageException {
File parent = walletFile.getParentFile();
if(!parent.exists() && !Storage.createOwnerOnlyDirectory(parent)) {
throw new IOException("Could not create folder " + parent);
}
if(encryptionPubKey != null && !NO_PASSWORD_KEY.equals(encryptionPubKey)) {
walletFile = persistence.storeWallet(this, wallet, encryptionPubKey);
return;
}
walletFile = persistence.storeWallet(this, wallet);
}
public void updateWallet(Wallet wallet) throws IOException, StorageException {
if(encryptionPubKey != null && !NO_PASSWORD_KEY.equals(encryptionPubKey)) {
persistence.updateWallet(this, wallet, encryptionPubKey);
} else {
persistence.updateWallet(this, wallet);
}
}
public boolean isPersisted(Wallet wallet) {
return persistence.isPersisted(this, wallet);
}
public void close() {
ClosePersistenceService closePersistenceService = new ClosePersistenceService();
closePersistenceService.start();
}
public void backupWallet() throws IOException {
if(walletFile.toPath().startsWith(getWalletsDir().toPath())) {
backupWallet(null);
}
}
public void backupTempWallet() {
try {
backupWallet(TEMP_BACKUP_PREFIX);
} catch(IOException e) {
log.error("Error creating " + TEMP_BACKUP_PREFIX + " backup wallet", e);
}
}
private void backupWallet(String prefix) throws IOException {
File backupDir = getWalletsBackupDir();
Date backupDate = new Date();
String walletName = persistence.getWalletName(walletFile, null);
String dateSuffix = "-" + BACKUP_DATE_FORMAT.format(backupDate);
String backupName = walletName + dateSuffix + walletFile.getName().substring(walletName.length());
if(prefix != null) {
backupName = prefix + "_" + backupName;
}
File backupFile = new File(backupDir, backupName);
if(!backupFile.exists()) {
createOwnerOnlyFile(backupFile);
}
try(FileOutputStream outputStream = new FileOutputStream(backupFile)) {
copyWallet(outputStream);
}
}
public void copyWallet(OutputStream outputStream) throws IOException {
persistence.copyWallet(walletFile, outputStream);
}
public void deleteBackups() {
deleteBackups(null);
}
public void deleteTempBackups(boolean forceSave) {
File[] backups = getBackups(Storage.TEMP_BACKUP_PREFIX);
if(backups.length > 0 && (forceSave || hasStartedSince(backups[0]))) {
File permanent = new File(backups[0].getParent(), backups[0].getName().substring(Storage.TEMP_BACKUP_PREFIX.length() + 1));
backups[0].renameTo(permanent);
}
deleteBackups(Storage.TEMP_BACKUP_PREFIX);
}
private boolean hasStartedSince(File lastBackup) {
try {
Date date = BACKUP_DATE_FORMAT.parse(getBackupDate(lastBackup.getName()));
ProcessHandle.Info processInfo = ProcessHandle.current().info();
return (processInfo.startInstant().isPresent() && processInfo.startInstant().get().isAfter(date.toInstant()));
} catch(Exception e) {
log.error("Error parsing date for backup file " + lastBackup.getName(), e);
return false;
}
}
private void deleteBackups(String prefix) {
File[] backups = getBackups(prefix);
for(File backup : backups) {
backup.delete();
}
}
public File getTempBackup() {
File[] backups = getBackups(TEMP_BACKUP_PREFIX);
return backups.length == 0 ? null : backups[0];
}
File[] getBackups(String prefix) {
File backupDir = getWalletsBackupDir();
String walletName = persistence.getWalletName(walletFile, null);
String extension = walletFile.getName().substring(walletName.length());
File[] backups = backupDir.listFiles((dir, name) -> {
return name.startsWith((prefix == null ? "" : prefix + "_") + walletName + "-") &&
getBackupDate(name) != null &&
(extension.isEmpty() || name.endsWith(extension));
});
backups = backups == null ? new File[0] : backups;
Arrays.sort(backups, Comparator.comparing(o -> getBackupDate(((File)o).getName())).reversed());
return backups;
}
private String getBackupDate(String backupFileName) {
Matcher matcher = DATE_PATTERN.matcher(backupFileName);
if(matcher.matches()) {
return matcher.group(1);
}
return null;
}
private WalletBackupAndKey migrateToDb(WalletBackupAndKey masterWalletAndKey) throws IOException, StorageException {
if(getType() == PersistenceType.JSON) {
log.info("Migrating " + masterWalletAndKey.getWallet().getName() + " from JSON to DB persistence");
masterWalletAndKey = migrateType(PersistenceType.DB, masterWalletAndKey.getWallet(), masterWalletAndKey.getEncryptionKey());
}
return masterWalletAndKey;
}
private WalletBackupAndKey migrateType(PersistenceType type, Wallet wallet, ECKey encryptionKey) throws IOException, StorageException {
File existingFile = walletFile;
try {
AsymmetricKeyDeriver keyDeriver = persistence.getKeyDeriver();
persistence = type.getInstance();
persistence.setKeyDeriver(keyDeriver);
walletFile = new File(walletFile.getParentFile(), wallet.getName() + "." + type.getExtension());
if(walletFile.exists()) {
walletFile.delete();
}
saveWallet(wallet);
if(type == PersistenceType.DB) {
for(Wallet childWallet : wallet.getChildWallets()) {
saveWallet(childWallet);
}
}
if(NO_PASSWORD_KEY.equals(encryptionPubKey)) {
return persistence.loadWallet(this);
}
return persistence.loadWallet(this, null, encryptionKey);
} catch(Exception e) {
existingFile = null;
throw e;
} finally {
if(existingFile != null) {
existingFile.delete();
}
}
}
public ECKey getEncryptionPubKey() {
return encryptionPubKey;
}
public void setEncryptionPubKey(ECKey encryptionPubKey) {
this.encryptionPubKey = encryptionPubKey;
}
public ECKey getEncryptionKey(CharSequence password) throws IOException, StorageException {
return persistence.getEncryptionKey(password);
}
public AsymmetricKeyDeriver getKeyDeriver() {
return persistence.getKeyDeriver();
}
void setKeyDeriver(AsymmetricKeyDeriver keyDeriver) {
persistence.setKeyDeriver(keyDeriver);
}
public PersistenceType getType() {
return persistence.getType();
}
public static boolean walletExists(String walletName) {
File encrypted = new File(getWalletsDir(), walletName.trim());
if(encrypted.exists()) {
return true;
}
for(PersistenceType persistenceType : PersistenceType.values()) {
File unencrypted = new File(getWalletsDir(), walletName.trim() + "." + persistenceType.getExtension());
if(unencrypted.exists()) {
return true;
}
}
return RESERVED_WALLET_NAMES.contains(walletName);
}
public static File getExistingWallet(String walletName) {
return getExistingWallet(getWalletsDir(), walletName);
}
public static File getExistingWallet(File walletsDir, String walletName) {
File encrypted = new File(walletsDir, walletName.trim());
if(encrypted.exists()) {
return encrypted;
}
for(PersistenceType persistenceType : PersistenceType.values()) {
File unencrypted = new File(walletsDir, walletName.trim() + "." + persistenceType.getExtension());
if(unencrypted.exists()) {
return unencrypted;
}
}
return null;
}
public static File getWalletFile(String walletName) {
//TODO: Check for existing file
return new File(getWalletsDir(), walletName);
}
public static boolean isWalletFile(File walletFile) {
for(PersistenceType type : PersistenceType.values()) {
if(walletFile.getName().endsWith("." + type.getExtension())) {
return true;
}
try {
if(type == PersistenceType.JSON && type.getInstance().isEncrypted(walletFile)) {
return true;
}
} catch(IOException e) {
//ignore
}
}
return false;
}
public static boolean isEncrypted(File walletFile) {
try {
for(PersistenceType type : PersistenceType.values()) {
if(walletFile.getName().endsWith("." + type.getExtension())) {
return type.getInstance().isEncrypted(walletFile);
}
}
PersistenceType detectedType = detectPersistenceType(walletFile);
if(detectedType != null) {
return detectedType.getInstance().isEncrypted(walletFile);
}
} catch(IOException e) {
//ignore
}
return FileType.BINARY.equals(IOUtils.getFileType(walletFile));
}
public static PersistenceType detectPersistenceType(File walletFile) {
try(Reader reader = new FileReader(walletFile, StandardCharsets.UTF_8)) {
int firstChar = reader.read();
if(firstChar == 'U' || firstChar == '{') {
return PersistenceType.JSON;
}
if(firstChar == 'H') {
return PersistenceType.DB;
}
} catch(IOException e) {
log.error("Error detecting persistence type", e);
}
return null;
}
public static File getWalletsBackupDir() {
File walletsBackupDir = new File(getWalletsDir(), WALLETS_BACKUP_DIR);
if(!walletsBackupDir.exists()) {
createOwnerOnlyDirectory(walletsBackupDir);
}
return walletsBackupDir;
}
public static File getWalletsDir() {
File walletsDir = new File(getSparrowDir(), WALLETS_DIR);
if(!walletsDir.exists()) {
createOwnerOnlyDirectory(walletsDir);
}
return walletsDir;
}
public static File getCertificateFile(String host) {
File certsDir = getCertsDir();
File[] certs = certsDir.listFiles((dir, name) -> name.equals(host));
if(certs != null && certs.length > 0) {
return certs[0];
}
return null;
}
public static void saveCertificate(String host, Certificate cert) {
try(FileWriter writer = new FileWriter(new File(getCertsDir(), host))) {
writer.write("-----BEGIN CERTIFICATE-----\n");
writer.write(Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})", "$1\n"));
writer.write("\n-----END CERTIFICATE-----\n");
} catch(CertificateEncodingException e) {
log.error("Error encoding PEM certificate", e);
} catch(IOException e) {
log.error("Error writing PEM certificate", e);
}
}
static File getCertsDir() {
File certsDir = new File(getSparrowDir(), CERTS_DIR);
if(!certsDir.exists()) {
createOwnerOnlyDirectory(certsDir);
}
return certsDir;
}
static File getSparrowDir() {
File sparrowDir;
if(Network.get() != Network.MAINNET) {
sparrowDir = new File(getSparrowHome(), Network.get().getName());
} else {
sparrowDir = getSparrowHome();
}
if(!sparrowDir.exists()) {
createOwnerOnlyDirectory(sparrowDir);
}
return sparrowDir;
}
public static File getSparrowHome() {
if(System.getProperty(MainApp.APP_HOME_PROPERTY) != null) {
return new File(System.getProperty(MainApp.APP_HOME_PROPERTY));
}
if(Platform.getCurrent() == Platform.WINDOWS) {
return new File(getHomeDir(), WINDOWS_SPARROW_DIR);
}
return new File(getHomeDir(), SPARROW_DIR);
}
static File getHomeDir() {
if(Platform.getCurrent() == Platform.WINDOWS) {
return new File(System.getenv("APPDATA"));
}
return new File(System.getProperty("user.home"));
}
public static boolean createOwnerOnlyDirectory(File directory) {
try {
if(Platform.getCurrent() == Platform.WINDOWS) {
Files.createDirectories(directory.toPath());
return true;
}
Files.createDirectories(directory.toPath(), PosixFilePermissions.asFileAttribute(getDirectoryOwnerOnlyPosixFilePermissions()));
return true;
} catch(UnsupportedOperationException e) {
return directory.mkdirs();
} catch(IOException e) {
log.error("Could not create directory " + directory.getAbsolutePath(), e);
}
return false;
}
public static boolean createOwnerOnlyFile(File file) {
try {
if(Platform.getCurrent() == Platform.WINDOWS) {
Files.createFile(file.toPath());
return true;
}
Files.createFile(file.toPath(), PosixFilePermissions.asFileAttribute(getFileOwnerOnlyPosixFilePermissions()));
return true;
} catch(UnsupportedOperationException e) {
return false;
} catch(IOException e) {
log.error("Could not create file " + file.getAbsolutePath(), e);
}
return false;
}
private static Set<PosixFilePermission> getDirectoryOwnerOnlyPosixFilePermissions() {
Set<PosixFilePermission> ownerOnly = getFileOwnerOnlyPosixFilePermissions();
ownerOnly.add(PosixFilePermission.OWNER_EXECUTE);
return ownerOnly;
}
private static Set<PosixFilePermission> getFileOwnerOnlyPosixFilePermissions() {
Set<PosixFilePermission> ownerOnly = EnumSet.noneOf(PosixFilePermission.class);
ownerOnly.add(PosixFilePermission.OWNER_READ);
ownerOnly.add(PosixFilePermission.OWNER_WRITE);
return ownerOnly;
}
public static class LoadWalletService extends Service<WalletBackupAndKey> {
private final Storage storage;
private final SecureString password;
public LoadWalletService(Storage storage, SecureString password) {
this.storage = storage;
this.password = password;
}
@Override
protected Task<WalletBackupAndKey> createTask() {
return new Task<>() {
protected WalletBackupAndKey call() throws IOException, StorageException {
WalletBackupAndKey walletBackupAndKey = storage.loadEncryptedWallet(password);
password.clear();
return walletBackupAndKey;
}
};
}
}
public static class KeyDerivationService extends Service<ECKey> {
private final Storage storage;
private final SecureString password;
private final boolean verifyPassword;
public KeyDerivationService(Storage storage, SecureString password) {
this.storage = storage;
this.password = password;
this.verifyPassword = false;
}
public KeyDerivationService(Storage storage, SecureString password, boolean verifyPassword) {
this.storage = storage;
this.password = password;
this.verifyPassword = verifyPassword;
}
@Override
protected Task<ECKey> createTask() {
return new Task<>() {
protected ECKey call() throws IOException, StorageException {
try {
ECKey encryptionFullKey = storage.getEncryptionKey(password);
if(verifyPassword && !ECKey.fromPublicOnly(encryptionFullKey).equals(storage.getEncryptionPubKey())) {
throw new InvalidPasswordException("Derived pubkey does not match stored pubkey");
}
return encryptionFullKey;
} finally {
password.clear();
}
}
};
}
}
public static class DecryptWalletService extends Service<Wallet> {
private final Wallet wallet;
private final SecureString password;
public DecryptWalletService(Wallet wallet, SecureString password) {
this.wallet = wallet;
this.password = password;
}
@Override
protected Task<Wallet> createTask() {
return new Task<>() {
protected Wallet call() throws IOException, StorageException {
try {
wallet.decrypt(password);
return wallet;
} finally {
password.clear();
}
}
};
}
}
public class ClosePersistenceService extends Service<Void> {
@Override
protected Task<Void> createTask() {
return new Task<>() {
protected Void call() {
persistence.close();
return null;
}
};
}
}
}
|
[
"\"APPDATA\""
] |
[] |
[
"APPDATA"
] |
[]
|
["APPDATA"]
|
java
| 1 | 0 | |
test/functional/buildAndPackage/src/net/adoptopenjdk/test/VendorPropertiesTest.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.adoptopenjdk.test;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static net.adoptopenjdk.test.JdkVersion.VM;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;
/**
* Tests whether vendor names and correct URLs appear in all the places they are supposed to.
*/
@Test(groups = {"level.extended"})
public class VendorPropertiesTest {
/**
* The checks for a given vendor.
*/
private final VmPropertiesChecks vendorChecks;
/**
* Class tells us what the jdk version and vm type is.
*/
private final JdkVersion jdkVersion = new JdkVersion();
/**
* Constructor method.
*/
public VendorPropertiesTest() {
Set<VmPropertiesChecks> allPropertiesChecks = new LinkedHashSet<>();
allPropertiesChecks.add(new AdoptOpenJDKPropertiesChecks());
allPropertiesChecks.add(new CorrettoPropertiesChecks());
// TODO: Somehow obtain the vendor name from the outside. Using any JVM properties is not a solution
// because that's what we want to test here.
String vendor = "AdoptOpenJDK";
this.vendorChecks = allPropertiesChecks.stream()
.filter(checks -> checks.supports(vendor))
.findFirst()
.orElseThrow(() -> new AssertionError("No checks found for vendor: " + vendor));
}
/**
* Verifies that the vendor name is displayed within
* the java -version output, where applicable.
*/
@Test
public void javaVersionPrintsVendor() {
// Skip test on JDK8 for non-Hotspot JDKs.
if (!jdkVersion.isNewerOrEqual(9) && !jdkVersion.usesVM(VM.HOTSPOT)) {
return;
}
String testJdkHome = System.getenv("TEST_JDK_HOME");
if (testJdkHome == null) {
throw new AssertionError("TEST_JDK_HOME is not set");
}
List<String> command = new ArrayList<>();
command.add(String.format("%s/bin/java", testJdkHome));
command.add("-version");
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
String stderr = StreamUtils.consumeStream(process.getErrorStream());
if (process.waitFor() != 0) {
throw new AssertionError("Could not run java -version");
}
this.vendorChecks.javaVersion(stderr);
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Failed to launch JVM", e);
}
}
/**
* Test method that calls a number of other test methods
* themed around vendor-related property checks.
*/
@Test
public void vmPropertiesPointToVendor() {
this.vendorChecks.javaVendor(System.getProperty("java.vendor"));
this.vendorChecks.javaVendorUrl(System.getProperty("java.vendor.url"));
this.vendorChecks.javaVendorUrlBug(System.getProperty("java.vendor.url.bug"));
this.vendorChecks.javaVendorVersion(System.getProperty("java.vendor.version"));
this.vendorChecks.javaVmVendor(System.getProperty("java.vm.vendor"));
this.vendorChecks.javaVmVersion(System.getProperty("java.vm.version"));
}
private interface VmPropertiesChecks {
/**
* Tests whether the implementation of {@linkplain VmPropertiesChecks} is suitable to verify a JDK.
* @param vendor Name identifying the vendor.
* @return boolean result
*/
boolean supports(String vendor);
/**
* Checks whether the output of {@code java -version} is acceptable.
* @param value the value to be validated.
*/
void javaVersion(String value);
/**
* Checks the value of {@code java.vendor}.
* @param value the value to be validated.
*/
void javaVendor(String value);
/**
* Checks the value of {@code java.vendor.url}.
* @param value the value to be validated.
*/
void javaVendorUrl(String value);
/**
* Checks the value of {@code java.vendor.url.bug}.
* @param value the value to be validated.
*/
void javaVendorUrlBug(String value);
/**
* Checks the value of {@code java.vendor.version}.
* @param value the value to be validated.
*/
void javaVendorVersion(String value);
/**
* Checks the value of {@code java.vm.vendor}.
* @param value the value to be validated.
*/
void javaVmVendor(String value);
/**
* Checks the value of {@code java.vm.version}.
* @param value the value to be validated.
*/
void javaVmVersion(String value);
}
private static class AdoptOpenJDKPropertiesChecks implements VmPropertiesChecks {
@Override
public boolean supports(final String vendor) {
return vendor.toLowerCase(Locale.US).equals("adoptopenjdk");
}
@Override
public void javaVersion(final String value) {
assertTrue(value.contains("AdoptOpenJDK"));
}
@Override
public void javaVendor(final String value) {
assertEquals(value, "AdoptOpenJDK");
}
@Override
public void javaVendorUrl(final String value) {
assertEquals(value, "https://adoptium.net/");
}
@Override
public void javaVendorUrlBug(final String value) {
assertEquals(value, "https://github.com/AdoptOpenJDK/openjdk-support/issues");
}
@Override
public void javaVendorVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vendor.version contains no numbers: " + value);
}
@Override
public void javaVmVendor(final String value) {
assertTrue(value.equals("AdoptOpenJDK") || value.equals("Eclipse OpenJ9"));
}
@Override
public void javaVmVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vm.version contains no numbers: " + value);
}
}
private static class CorrettoPropertiesChecks implements VmPropertiesChecks {
@Override
public boolean supports(final String vendor) {
return vendor.toLowerCase(Locale.US).startsWith("amazon");
}
@Override
public void javaVersion(final String value) {
assertTrue(value.contains("Corretto"));
}
@Override
public void javaVendor(final String value) {
assertEquals(value, "Amazon.com Inc.");
}
@Override
public void javaVendorUrl(final String value) {
assertEquals(value, "https://aws.amazon.com/corretto/");
}
@Override
public void javaVendorUrlBug(final String value) {
assertTrue(value.startsWith("https://github.com/corretto/corretto"));
}
@Override
public void javaVendorVersion(final String value) {
assertTrue(value.startsWith("Corretto"));
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vendor.version contains no numbers: " + value);
}
@Override
public void javaVmVendor(final String value) {
assertEquals(value, "Amazon.com Inc.");
}
@Override
public void javaVmVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vm.version contains no numbers: " + value);
}
}
}
|
[
"\"TEST_JDK_HOME\""
] |
[] |
[
"TEST_JDK_HOME"
] |
[]
|
["TEST_JDK_HOME"]
|
java
| 1 | 0 | |
scripts/gen_kobject_list.py
|
#!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
"""
Script to generate gperf tables of kernel object metadata
User mode threads making system calls reference kernel objects by memory
address, as the kernel/driver APIs in Zephyr are the same for both user
and supervisor contexts. It is necessary for the kernel to be able to
validate accesses to kernel objects to make the following assertions:
- That the memory address points to a kernel object
- The kernel object is of the expected type for the API being invoked
- The kernel object is of the expected initialization state
- The calling thread has sufficient permissions on the object
For more details see the :ref:`kernelobjects` section in the documentation.
The zephyr build generates an intermediate ELF binary, zephyr_prebuilt.elf,
which this script scans looking for kernel objects by examining the DWARF
debug information to look for instances of data structures that are considered
kernel objects. For device drivers, the API struct pointer populated at build
time is also examined to disambiguate between various device driver instances
since they are all 'struct device'.
This script can generate five different output files:
- A gperf script to generate the hash table mapping kernel object memory
addresses to kernel object metadata, used to track permissions,
object type, initialization state, and any object-specific data.
- A header file containing generated macros for validating driver instances
inside the system call handlers for the driver subsystem APIs.
- A code fragment included by kernel.h with one enum constant for
each kernel object type and each driver instance.
- The inner cases of a switch/case C statement, included by
kernel/userspace.c, mapping the kernel object types and driver
instances to their human-readable representation in the
otype_to_str() function.
- The inner cases of a switch/case C statement, included by
kernel/userspace.c, mapping kernel object types to their sizes.
This is used for allocating instances of them at runtime
(CONFIG_DYNAMIC_OBJECTS) in the obj_size_get() function.
"""
import sys
import argparse
import math
import os
import struct
import json
from distutils.version import LooseVersion
import elftools
from elftools.elf.elffile import ELFFile
from elftools.elf.sections import SymbolTableSection
if LooseVersion(elftools.__version__) < LooseVersion('0.24'):
sys.exit("pyelftools is out of date, need version 0.24 or later")
from collections import OrderedDict
# Keys in this dictionary are structs which should be recognized as kernel
# objects. Values are a tuple:
#
# - The first item is None, or the name of a Kconfig that
# indicates the presence of this object's definition in case it is not
# available in all configurations.
#
# - The second item is a boolean indicating whether it is permissible for
# the object to be located in user-accessible memory.
#
# - The third items is a boolean indicating whether this item can be
# dynamically allocated with k_object_alloc(). Keep this in sync with
# the switch statement in z_impl_k_object_alloc().
#
# Key names in all caps do not correspond to a specific data type but instead
# indicate that objects of its type are of a family of compatible data
# structures
# Regular dictionaries are ordered only with Python 3.6 and
# above. Good summary and pointers to official documents at:
# https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6
kobjects = OrderedDict([
("k_mem_slab", (None, False, True)),
("k_msgq", (None, False, True)),
("k_mutex", (None, False, True)),
("k_pipe", (None, False, True)),
("k_queue", (None, False, True)),
("k_poll_signal", (None, False, True)),
("k_sem", (None, False, True)),
("k_stack", (None, False, True)),
("k_thread", (None, False, True)), # But see #
("k_timer", (None, False, True)),
("z_thread_stack_element", (None, False, False)),
("device", (None, False, False)),
("NET_SOCKET", (None, False, False)),
("net_if", (None, False, False)),
("sys_mutex", (None, True, False)),
("k_futex", (None, True, False)),
("k_condvar", (None, False, True))
])
def kobject_to_enum(kobj):
if kobj.startswith("k_") or kobj.startswith("z_"):
name = kobj[2:]
else:
name = kobj
return "K_OBJ_%s" % name.upper()
subsystems = [
# Editing the list is deprecated, add the __subsystem sentinal to your driver
# api declaration instead. e.x.
#
# __subsystem struct my_driver_api {
# ....
#};
]
# Names of all structs tagged with __net_socket, found by parse_syscalls.py
net_sockets = [ ]
def subsystem_to_enum(subsys):
return "K_OBJ_DRIVER_" + subsys[:-11].upper()
# --- debug stuff ---
scr = os.path.basename(sys.argv[0])
def debug(text):
if not args.verbose:
return
sys.stdout.write(scr + ": " + text + "\n")
def error(text):
sys.exit("%s ERROR: %s" % (scr, text))
def debug_die(die, text):
lp_header = die.dwarfinfo.line_program_for_CU(die.cu).header
files = lp_header["file_entry"]
includes = lp_header["include_directory"]
fileinfo = files[die.attributes["DW_AT_decl_file"].value - 1]
filename = fileinfo.name.decode("utf-8")
filedir = includes[fileinfo.dir_index - 1].decode("utf-8")
path = os.path.join(filedir, filename)
lineno = die.attributes["DW_AT_decl_line"].value
debug(str(die))
debug("File '%s', line %d:" % (path, lineno))
debug(" %s" % text)
# -- ELF processing
DW_OP_addr = 0x3
DW_OP_fbreg = 0x91
STACK_TYPE = "z_thread_stack_element"
thread_counter = 0
sys_mutex_counter = 0
futex_counter = 0
stack_counter = 0
# Global type environment. Populated by pass 1.
type_env = {}
extern_env = {}
class KobjectInstance:
def __init__(self, type_obj, addr):
self.addr = addr
self.type_obj = type_obj
# Type name determined later since drivers needs to look at the
# API struct address
self.type_name = None
self.data = 0
class KobjectType:
def __init__(self, offset, name, size, api=False):
self.name = name
self.size = size
self.offset = offset
self.api = api
def __repr__(self):
return "<kobject %s>" % self.name
@staticmethod
def has_kobject():
return True
def get_kobjects(self, addr):
return {addr: KobjectInstance(self, addr)}
class ArrayType:
def __init__(self, offset, elements, member_type):
self.elements = elements
self.member_type = member_type
self.offset = offset
def __repr__(self):
return "<array of %d>" % self.member_type
def has_kobject(self):
if self.member_type not in type_env:
return False
return type_env[self.member_type].has_kobject()
def get_kobjects(self, addr):
mt = type_env[self.member_type]
# Stacks are arrays of _k_stack_element_t but we want to treat
# the whole array as one kernel object (a thread stack)
# Data value gets set to size of entire region
if isinstance(mt, KobjectType) and mt.name == STACK_TYPE:
# An array of stacks appears as a multi-dimensional array.
# The last size is the size of each stack. We need to track
# each stack within the array, not as one huge stack object.
*dimensions, stacksize = self.elements
num_members = 1
for e in dimensions:
num_members = num_members * e
ret = {}
for i in range(num_members):
a = addr + (i * stacksize)
o = mt.get_kobjects(a)
o[a].data = stacksize
ret.update(o)
return ret
objs = {}
# Multidimensional array flattened out
num_members = 1
for e in self.elements:
num_members = num_members * e
for i in range(num_members):
objs.update(mt.get_kobjects(addr + (i * mt.size)))
return objs
class AggregateTypeMember:
def __init__(self, offset, member_name, member_type, member_offset):
self.member_name = member_name
self.member_type = member_type
if isinstance(member_offset, list):
# DWARF v2, location encoded as set of operations
# only "DW_OP_plus_uconst" with ULEB128 argument supported
if member_offset[0] == 0x23:
self.member_offset = member_offset[1] & 0x7f
for i in range(1, len(member_offset)-1):
if member_offset[i] & 0x80:
self.member_offset += (
member_offset[i+1] & 0x7f) << i*7
else:
raise Exception("not yet supported location operation (%s:%d:%d)" %
(self.member_name, self.member_type, member_offset[0]))
else:
self.member_offset = member_offset
def __repr__(self):
return "<member %s, type %d, offset %d>" % (
self.member_name, self.member_type, self.member_offset)
def has_kobject(self):
if self.member_type not in type_env:
return False
return type_env[self.member_type].has_kobject()
def get_kobjects(self, addr):
mt = type_env[self.member_type]
return mt.get_kobjects(addr + self.member_offset)
class ConstType:
def __init__(self, child_type):
self.child_type = child_type
def __repr__(self):
return "<const %d>" % self.child_type
def has_kobject(self):
if self.child_type not in type_env:
return False
return type_env[self.child_type].has_kobject()
def get_kobjects(self, addr):
return type_env[self.child_type].get_kobjects(addr)
class AggregateType:
def __init__(self, offset, name, size):
self.name = name
self.size = size
self.offset = offset
self.members = []
def add_member(self, member):
self.members.append(member)
def __repr__(self):
return "<struct %s, with %s>" % (self.name, self.members)
def has_kobject(self):
result = False
bad_members = []
for member in self.members:
if member.has_kobject():
result = True
else:
bad_members.append(member)
# Don't need to consider this again, just remove it
for bad_member in bad_members:
self.members.remove(bad_member)
return result
def get_kobjects(self, addr):
objs = {}
for member in self.members:
objs.update(member.get_kobjects(addr))
return objs
# --- helper functions for getting data from DIEs ---
def die_get_spec(die):
if 'DW_AT_specification' not in die.attributes:
return None
spec_val = die.attributes["DW_AT_specification"].value
# offset of the DW_TAG_variable for the extern declaration
offset = spec_val + die.cu.cu_offset
return extern_env.get(offset)
def die_get_name(die):
if 'DW_AT_name' not in die.attributes:
die = die_get_spec(die)
if not die:
return None
return die.attributes["DW_AT_name"].value.decode("utf-8")
def die_get_type_offset(die):
if 'DW_AT_type' not in die.attributes:
die = die_get_spec(die)
if not die:
return None
return die.attributes["DW_AT_type"].value + die.cu.cu_offset
def die_get_byte_size(die):
if 'DW_AT_byte_size' not in die.attributes:
return 0
return die.attributes["DW_AT_byte_size"].value
def analyze_die_struct(die):
name = die_get_name(die) or "<anon>"
offset = die.offset
size = die_get_byte_size(die)
# Incomplete type
if not size:
return
if name in kobjects:
type_env[offset] = KobjectType(offset, name, size)
elif name in subsystems:
type_env[offset] = KobjectType(offset, name, size, api=True)
elif name in net_sockets:
type_env[offset] = KobjectType(offset, "NET_SOCKET", size)
else:
at = AggregateType(offset, name, size)
type_env[offset] = at
for child in die.iter_children():
if child.tag != "DW_TAG_member":
continue
data_member_location = child.attributes.get("DW_AT_data_member_location")
if not data_member_location:
continue
child_type = die_get_type_offset(child)
member_offset = data_member_location.value
cname = die_get_name(child) or "<anon>"
m = AggregateTypeMember(child.offset, cname, child_type,
member_offset)
at.add_member(m)
return
def analyze_die_const(die):
type_offset = die_get_type_offset(die)
if not type_offset:
return
type_env[die.offset] = ConstType(type_offset)
def analyze_die_array(die):
type_offset = die_get_type_offset(die)
elements = []
for child in die.iter_children():
if child.tag != "DW_TAG_subrange_type":
continue
if "DW_AT_upper_bound" in child.attributes:
ub = child.attributes["DW_AT_upper_bound"]
if not ub.form.startswith("DW_FORM_data"):
continue
elements.append(ub.value + 1)
# in DWARF 4, e.g. ARC Metaware toolchain, DW_AT_count is used
# not DW_AT_upper_bound
elif "DW_AT_count" in child.attributes:
ub = child.attributes["DW_AT_count"]
if not ub.form.startswith("DW_FORM_data"):
continue
elements.append(ub.value)
else:
continue
if not elements:
if type_offset in type_env.keys():
mt = type_env[type_offset]
if mt.has_kobject():
if isinstance(mt, KobjectType) and mt.name == STACK_TYPE:
elements.append(1)
type_env[die.offset] = ArrayType(die.offset, elements, type_offset)
else:
type_env[die.offset] = ArrayType(die.offset, elements, type_offset)
def analyze_typedef(die):
type_offset = die_get_type_offset(die)
if type_offset not in type_env.keys():
return
type_env[die.offset] = type_env[type_offset]
def unpack_pointer(elf, data, offset):
endian_code = "<" if elf.little_endian else ">"
if elf.elfclass == 32:
size_code = "I"
size = 4
else:
size_code = "Q"
size = 8
return struct.unpack(endian_code + size_code,
data[offset:offset + size])[0]
def addr_deref(elf, addr):
for section in elf.iter_sections():
start = section['sh_addr']
end = start + section['sh_size']
if start <= addr < end:
data = section.data()
offset = addr - start
return unpack_pointer(elf, data, offset)
return 0
def device_get_api_addr(elf, addr):
# See include/device.h for a description of struct device
offset = 8 if elf.elfclass == 32 else 16
return addr_deref(elf, addr + offset)
def find_kobjects(elf, syms):
global thread_counter
global sys_mutex_counter
global futex_counter
global stack_counter
if not elf.has_dwarf_info():
sys.exit("ELF file has no DWARF information")
app_smem_start = syms["_app_smem_start"]
app_smem_end = syms["_app_smem_end"]
user_stack_start = syms["z_user_stacks_start"]
user_stack_end = syms["z_user_stacks_end"]
di = elf.get_dwarf_info()
variables = []
# Step 1: collect all type information.
for CU in di.iter_CUs():
for die in CU.iter_DIEs():
# Unions are disregarded, kernel objects should never be union
# members since the memory is not dedicated to that object and
# could be something else
if die.tag == "DW_TAG_structure_type":
analyze_die_struct(die)
elif die.tag == "DW_TAG_const_type":
analyze_die_const(die)
elif die.tag == "DW_TAG_array_type":
analyze_die_array(die)
elif die.tag == "DW_TAG_typedef":
analyze_typedef(die)
elif die.tag == "DW_TAG_variable":
variables.append(die)
# Step 2: filter type_env to only contain kernel objects, or structs
# and arrays of kernel objects
bad_offsets = []
for offset, type_object in type_env.items():
if not type_object.has_kobject():
bad_offsets.append(offset)
for offset in bad_offsets:
del type_env[offset]
# Step 3: Now that we know all the types we are looking for, examine
# all variables
all_objs = {}
for die in variables:
name = die_get_name(die)
if not name:
continue
if name.startswith("__init_sys_init"):
# Boot-time initialization function; not an actual device
continue
type_offset = die_get_type_offset(die)
# Is this a kernel object, or a structure containing kernel
# objects?
if type_offset not in type_env:
continue
if "DW_AT_declaration" in die.attributes:
# Extern declaration, only used indirectly
extern_env[die.offset] = die
continue
if "DW_AT_location" not in die.attributes:
debug_die(die,
"No location information for object '%s'; possibly stack allocated"
% name)
continue
loc = die.attributes["DW_AT_location"]
if loc.form != "DW_FORM_exprloc" and \
loc.form != "DW_FORM_block1":
debug_die(die, "kernel object '%s' unexpected location format" %
name)
continue
opcode = loc.value[0]
if opcode != DW_OP_addr:
# Check if frame pointer offset DW_OP_fbreg
if opcode == DW_OP_fbreg:
debug_die(die, "kernel object '%s' found on stack" % name)
else:
debug_die(die,
"kernel object '%s' unexpected exprloc opcode %s" %
(name, hex(opcode)))
continue
if "CONFIG_64BIT" in syms:
addr = ((loc.value[1] << 0 ) | (loc.value[2] << 8) |
(loc.value[3] << 16) | (loc.value[4] << 24) |
(loc.value[5] << 32) | (loc.value[6] << 40) |
(loc.value[7] << 48) | (loc.value[8] << 56))
else:
addr = ((loc.value[1] << 0 ) | (loc.value[2] << 8) |
(loc.value[3] << 16) | (loc.value[4] << 24))
if addr == 0:
# Never linked; gc-sections deleted it
continue
type_obj = type_env[type_offset]
objs = type_obj.get_kobjects(addr)
all_objs.update(objs)
debug("symbol '%s' at %s contains %d object(s)"
% (name, hex(addr), len(objs)))
# Step 4: objs is a dictionary mapping variable memory addresses to
# their associated type objects. Now that we have seen all variables
# and can properly look up API structs, convert this into a dictionary
# mapping variables to the C enumeration of what kernel object type it
# is.
ret = {}
for addr, ko in all_objs.items():
# API structs don't get into the gperf table
if ko.type_obj.api:
continue
_, user_ram_allowed, _ = kobjects[ko.type_obj.name]
if not user_ram_allowed and app_smem_start <= addr < app_smem_end:
debug("object '%s' found in invalid location %s"
% (ko.type_obj.name, hex(addr)))
continue
if (ko.type_obj.name == STACK_TYPE and
(addr < user_stack_start or addr >= user_stack_end)):
debug("skip kernel-only stack at %s" % hex(addr))
continue
# At this point we know the object will be included in the gperf table
if ko.type_obj.name == "k_thread":
# Assign an ID for this thread object, used to track its
# permissions to other kernel objects
ko.data = thread_counter
thread_counter = thread_counter + 1
elif ko.type_obj.name == "sys_mutex":
ko.data = "&kernel_mutexes[%d]" % sys_mutex_counter
sys_mutex_counter += 1
elif ko.type_obj.name == "k_futex":
ko.data = "&futex_data[%d]" % futex_counter
futex_counter += 1
elif ko.type_obj.name == STACK_TYPE:
stack_counter += 1
if ko.type_obj.name != "device":
# Not a device struct so we immediately know its type
ko.type_name = kobject_to_enum(ko.type_obj.name)
ret[addr] = ko
continue
# Device struct. Need to get the address of its API struct,
# if it has one.
apiaddr = device_get_api_addr(elf, addr)
if apiaddr not in all_objs:
if apiaddr == 0:
debug("device instance at 0x%x has no associated subsystem"
% addr)
else:
debug("device instance at 0x%x has unknown API 0x%x"
% (addr, apiaddr))
# API struct does not correspond to a known subsystem, skip it
continue
apiobj = all_objs[apiaddr]
ko.type_name = subsystem_to_enum(apiobj.type_obj.name)
ret[addr] = ko
debug("found %d kernel object instances total" % len(ret))
# 1. Before python 3.7 dict order is not guaranteed. With Python
# 3.5 it doesn't seem random with *integer* keys but can't
# rely on that.
# 2. OrderedDict means _insertion_ order, so not enough because
# built from other (random!) dicts: need to _sort_ first.
# 3. Sorting memory address looks good.
return OrderedDict(sorted(ret.items()))
def get_symbols(elf):
for section in elf.iter_sections():
if isinstance(section, SymbolTableSection):
return {sym.name: sym.entry.st_value
for sym in section.iter_symbols()}
raise LookupError("Could not find symbol table")
# -- GPERF generation logic
header = """%compare-lengths
%define lookup-function-name z_object_lookup
%language=ANSI-C
%global-table
%struct-type
%{
#include <kernel.h>
#include <toolchain.h>
#include <syscall_handler.h>
#include <string.h>
%}
struct z_object;
"""
# Different versions of gperf have different prototypes for the lookup
# function, best to implement the wrapper here. The pointer value itself is
# turned into a string, we told gperf to expect binary strings that are not
# NULL-terminated.
footer = """%%
struct z_object *z_object_gperf_find(const void *obj)
{
return z_object_lookup((const char *)obj, sizeof(void *));
}
void z_object_gperf_wordlist_foreach(_wordlist_cb_func_t func, void *context)
{
int i;
for (i = MIN_HASH_VALUE; i <= MAX_HASH_VALUE; i++) {
if (wordlist[i].name != NULL) {
func(&wordlist[i], context);
}
}
}
#ifndef CONFIG_DYNAMIC_OBJECTS
struct z_object *z_object_find(const void *obj)
ALIAS_OF(z_object_gperf_find);
void z_object_wordlist_foreach(_wordlist_cb_func_t func, void *context)
ALIAS_OF(z_object_gperf_wordlist_foreach);
#endif
"""
def write_gperf_table(fp, syms, objs, little_endian, static_begin, static_end):
fp.write(header)
if sys_mutex_counter != 0:
fp.write("static struct k_mutex kernel_mutexes[%d] = {\n"
% sys_mutex_counter)
for i in range(sys_mutex_counter):
fp.write("Z_MUTEX_INITIALIZER(kernel_mutexes[%d])" % i)
if i != sys_mutex_counter - 1:
fp.write(", ")
fp.write("};\n")
if futex_counter != 0:
fp.write("static struct z_futex_data futex_data[%d] = {\n"
% futex_counter)
for i in range(futex_counter):
fp.write("Z_FUTEX_DATA_INITIALIZER(futex_data[%d])" % i)
if i != futex_counter - 1:
fp.write(", ")
fp.write("};\n")
metadata_names = {
"K_OBJ_THREAD" : "thread_id",
"K_OBJ_SYS_MUTEX" : "mutex",
"K_OBJ_FUTEX" : "futex_data"
}
if "CONFIG_GEN_PRIV_STACKS" in syms:
metadata_names["K_OBJ_THREAD_STACK_ELEMENT"] = "stack_data"
if stack_counter != 0:
# Same as K_KERNEL_STACK_ARRAY_DEFINE, but routed to a different
# memory section.
fp.write("static uint8_t Z_GENERIC_SECTION(.priv_stacks.noinit) "
" __aligned(Z_KERNEL_STACK_OBJ_ALIGN)"
" priv_stacks[%d][Z_KERNEL_STACK_LEN(CONFIG_PRIVILEGED_STACK_SIZE)];\n"
% stack_counter)
fp.write("static struct z_stack_data stack_data[%d] = {\n"
% stack_counter)
counter = 0
for _, ko in objs.items():
if ko.type_name != "K_OBJ_THREAD_STACK_ELEMENT":
continue
# ko.data currently has the stack size. fetch the value to
# populate the appropriate entry in stack_data, and put
# a reference to the entry in stack_data into the data value
# instead
size = ko.data
ko.data = "&stack_data[%d]" % counter
fp.write("\t{ %d, (uint8_t *)(&priv_stacks[%d]) }"
% (size, counter))
if counter != (stack_counter - 1):
fp.write(",")
fp.write("\n")
counter += 1
fp.write("};\n")
else:
metadata_names["K_OBJ_THREAD_STACK_ELEMENT"] = "stack_size"
fp.write("%%\n")
# Setup variables for mapping thread indexes
thread_max_bytes = syms["CONFIG_MAX_THREAD_BYTES"]
thread_idx_map = {}
for i in range(0, thread_max_bytes):
thread_idx_map[i] = 0xFF
for obj_addr, ko in objs.items():
obj_type = ko.type_name
# pre-initialized objects fall within this memory range, they are
# either completely initialized at build time, or done automatically
# at boot during some PRE_KERNEL_* phase
initialized = static_begin <= obj_addr < static_end
is_driver = obj_type.startswith("K_OBJ_DRIVER_")
if "CONFIG_64BIT" in syms:
format_code = "Q"
else:
format_code = "I"
if little_endian:
endian = "<"
else:
endian = ">"
byte_str = struct.pack(endian + format_code, obj_addr)
fp.write("\"")
for byte in byte_str:
val = "\\x%02x" % byte
fp.write(val)
flags = "0"
if initialized:
flags += " | K_OBJ_FLAG_INITIALIZED"
if is_driver:
flags += " | K_OBJ_FLAG_DRIVER"
if ko.type_name in metadata_names:
tname = metadata_names[ko.type_name]
else:
tname = "unused"
fp.write("\", {}, %s, %s, { .%s = %s }\n" % (obj_type, flags,
tname, str(ko.data)))
if obj_type == "K_OBJ_THREAD":
idx = math.floor(ko.data / 8)
bit = ko.data % 8
thread_idx_map[idx] = thread_idx_map[idx] & ~(2**bit)
fp.write(footer)
# Generate the array of already mapped thread indexes
fp.write('\n')
fp.write('Z_GENERIC_SECTION(.kobject_data.data) ')
fp.write('uint8_t _thread_idx_map[%d] = {' % (thread_max_bytes))
for i in range(0, thread_max_bytes):
fp.write(' 0x%x, ' % (thread_idx_map[i]))
fp.write('};\n')
driver_macro_tpl = """
#define Z_SYSCALL_DRIVER_%(driver_upper)s(ptr, op) Z_SYSCALL_DRIVER_GEN(ptr, op, %(driver_lower)s, %(driver_upper)s)
"""
def write_validation_output(fp):
fp.write("#ifndef DRIVER_VALIDATION_GEN_H\n")
fp.write("#define DRIVER_VALIDATION_GEN_H\n")
fp.write("""#define Z_SYSCALL_DRIVER_GEN(ptr, op, driver_lower_case, driver_upper_case) \\
(Z_SYSCALL_OBJ(ptr, K_OBJ_DRIVER_##driver_upper_case) || \\
Z_SYSCALL_DRIVER_OP(ptr, driver_lower_case##_driver_api, op))
""")
for subsystem in subsystems:
subsystem = subsystem.replace("_driver_api", "")
fp.write(driver_macro_tpl % {
"driver_lower": subsystem.lower(),
"driver_upper": subsystem.upper(),
})
fp.write("#endif /* DRIVER_VALIDATION_GEN_H */\n")
def write_kobj_types_output(fp):
fp.write("/* Core kernel objects */\n")
for kobj, obj_info in kobjects.items():
dep, _, _ = obj_info
if kobj == "device":
continue
if dep:
fp.write("#ifdef %s\n" % dep)
fp.write("%s,\n" % kobject_to_enum(kobj))
if dep:
fp.write("#endif\n")
fp.write("/* Driver subsystems */\n")
for subsystem in subsystems:
subsystem = subsystem.replace("_driver_api", "").upper()
fp.write("K_OBJ_DRIVER_%s,\n" % subsystem)
def write_kobj_otype_output(fp):
fp.write("/* Core kernel objects */\n")
for kobj, obj_info in kobjects.items():
dep, _, _ = obj_info
if kobj == "device":
continue
if dep:
fp.write("#ifdef %s\n" % dep)
fp.write('case %s: ret = "%s"; break;\n' %
(kobject_to_enum(kobj), kobj))
if dep:
fp.write("#endif\n")
fp.write("/* Driver subsystems */\n")
for subsystem in subsystems:
subsystem = subsystem.replace("_driver_api", "")
fp.write('case K_OBJ_DRIVER_%s: ret = "%s driver"; break;\n' % (
subsystem.upper(),
subsystem
))
def write_kobj_size_output(fp):
fp.write("/* Non device/stack objects */\n")
for kobj, obj_info in kobjects.items():
dep, _, alloc = obj_info
if not alloc:
continue
if dep:
fp.write("#ifdef %s\n" % dep)
fp.write('case %s: ret = sizeof(struct %s); break;\n' %
(kobject_to_enum(kobj), kobj))
if dep:
fp.write("#endif\n")
def parse_subsystems_list_file(path):
with open(path, "r") as fp:
subsys_list = json.load(fp)
subsystems.extend(subsys_list["__subsystem"])
net_sockets.extend(subsys_list["__net_socket"])
def parse_args():
global args
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-k", "--kernel", required=False,
help="Input zephyr ELF binary")
parser.add_argument(
"-g", "--gperf-output", required=False,
help="Output list of kernel object addresses for gperf use")
parser.add_argument(
"-V", "--validation-output", required=False,
help="Output driver validation macros")
parser.add_argument(
"-K", "--kobj-types-output", required=False,
help="Output k_object enum constants")
parser.add_argument(
"-S", "--kobj-otype-output", required=False,
help="Output case statements for otype_to_str()")
parser.add_argument(
"-Z", "--kobj-size-output", required=False,
help="Output case statements for obj_size_get()")
parser.add_argument("-i", "--include-subsystem-list", required=False, action='append',
help='''Specifies a file with a JSON encoded list of subsystem names to append to
the driver subsystems list. Can be specified multiple times:
-i file1 -i file2 ...''')
parser.add_argument("-v", "--verbose", action="store_true",
help="Print extra debugging information")
args = parser.parse_args()
if "VERBOSE" in os.environ:
args.verbose = 1
def main():
parse_args()
if args.include_subsystem_list is not None:
for list_file in args.include_subsystem_list:
parse_subsystems_list_file(list_file)
if args.gperf_output:
assert args.kernel, "--kernel ELF required for --gperf-output"
elf = ELFFile(open(args.kernel, "rb"))
syms = get_symbols(elf)
max_threads = syms["CONFIG_MAX_THREAD_BYTES"] * 8
objs = find_kobjects(elf, syms)
if not objs:
sys.stderr.write("WARNING: zero kobject found in %s\n"
% args.kernel)
if thread_counter > max_threads:
sys.exit("Too many thread objects ({})\n"
"Increase CONFIG_MAX_THREAD_BYTES to {}"
.format(thread_counter, -(-thread_counter // 8)))
with open(args.gperf_output, "w") as fp:
write_gperf_table(fp, syms, objs, elf.little_endian,
syms["_static_kernel_objects_begin"],
syms["_static_kernel_objects_end"])
if args.validation_output:
with open(args.validation_output, "w") as fp:
write_validation_output(fp)
if args.kobj_types_output:
with open(args.kobj_types_output, "w") as fp:
write_kobj_types_output(fp)
if args.kobj_otype_output:
with open(args.kobj_otype_output, "w") as fp:
write_kobj_otype_output(fp)
if args.kobj_size_output:
with open(args.kobj_size_output, "w") as fp:
write_kobj_size_output(fp)
if __name__ == "__main__":
main()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
test/e2e/app/main.go
|
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/line/ostracon/types"
"github.com/spf13/viper"
"github.com/line/ostracon/abci/server"
"github.com/line/ostracon/config"
"github.com/line/ostracon/crypto/ed25519"
tmflags "github.com/line/ostracon/libs/cli/flags"
"github.com/line/ostracon/libs/log"
tmnet "github.com/line/ostracon/libs/net"
"github.com/line/ostracon/light"
lproxy "github.com/line/ostracon/light/proxy"
lrpc "github.com/line/ostracon/light/rpc"
dbs "github.com/line/ostracon/light/store/db"
"github.com/line/ostracon/node"
"github.com/line/ostracon/p2p"
"github.com/line/ostracon/privval"
"github.com/line/ostracon/proxy"
rpcserver "github.com/line/ostracon/rpc/jsonrpc/server"
e2e "github.com/line/ostracon/test/e2e/pkg"
mcs "github.com/line/ostracon/test/maverick/consensus"
maverick "github.com/line/ostracon/test/maverick/node"
)
var logger = log.NewOCLogger(log.NewSyncWriter(os.Stdout))
// main is the binary entrypoint.
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %v <configfile>", os.Args[0])
return
}
configFile := ""
if len(os.Args) == 2 {
configFile = os.Args[1]
}
if err := run(configFile); err != nil {
logger.Error(err.Error())
os.Exit(1)
}
}
// run runs the application - basically like main() with error handling.
func run(configFile string) error {
cfg, err := LoadConfig(configFile)
if err != nil {
return err
}
// Start remote signer (must start before node if running builtin).
if cfg.PrivValServer != "" {
if err = startSigner(cfg); err != nil {
return err
}
if cfg.Protocol == "builtin" {
time.Sleep(1 * time.Second)
}
}
// Start app server.
switch cfg.Protocol {
case "socket", "grpc":
err = startApp(cfg)
case "builtin":
if len(cfg.Misbehaviors) == 0 {
if cfg.Mode == string(e2e.ModeLight) {
err = startLightClient(cfg)
} else {
err = startNode(cfg)
}
} else {
err = startMaverick(cfg)
}
default:
err = fmt.Errorf("invalid protocol %q", cfg.Protocol)
}
if err != nil {
return err
}
// Apparently there's no way to wait for the server, so we just sleep
for {
time.Sleep(1 * time.Hour)
}
}
// startApp starts the application server, listening for connections from Ostracon.
func startApp(cfg *Config) error {
app, err := NewApplication(cfg)
if err != nil {
return err
}
server, err := server.NewServer(cfg.Listen, cfg.Protocol, app)
if err != nil {
return err
}
err = server.Start()
if err != nil {
return err
}
logger.Info(fmt.Sprintf("Server listening on %v (%v protocol)", cfg.Listen, cfg.Protocol))
return nil
}
// startNode starts an Ostracon node running the application directly. It assumes the Ostracon
// configuration is in $OCHOME/config/ostracon.toml.
//
// FIXME There is no way to simply load the configuration from a file, so we need to pull in Viper.
func startNode(cfg *Config) error {
app, err := NewApplication(cfg)
if err != nil {
return err
}
tmcfg, nodeLogger, nodeKey, err := setupNode()
if err != nil {
return fmt.Errorf("failed to setup config: %w", err)
}
privVal, err := privval.LoadOrGenFilePV(
tmcfg.PrivValidatorKeyFile(),
tmcfg.PrivValidatorStateFile(),
privval.PrivKeyTypeEd25519,
)
if err != nil {
return fmt.Errorf("failed to load/generate FilePV%w", err)
}
n, err := node.NewNode(tmcfg,
privVal,
nodeKey,
proxy.NewLocalClientCreator(app),
node.DefaultGenesisDocProviderFunc(tmcfg),
node.DefaultDBProvider,
node.DefaultMetricsProvider(tmcfg.Instrumentation),
nodeLogger,
)
if err != nil {
return err
}
return n.Start()
}
func startLightClient(cfg *Config) error {
tmcfg, nodeLogger, _, err := setupNode()
if err != nil {
return err
}
dbContext := &node.DBContext{ID: "light", Config: tmcfg}
lightDB, err := node.DefaultDBProvider(dbContext)
if err != nil {
return err
}
providers := rpcEndpoints(tmcfg.P2P.PersistentPeers)
c, err := light.NewHTTPClient(
context.Background(),
cfg.ChainID,
light.TrustOptions{
Period: tmcfg.StateSync.TrustPeriod,
Height: tmcfg.StateSync.TrustHeight,
Hash: tmcfg.StateSync.TrustHashBytes(),
},
providers[0],
providers[1:],
dbs.New(lightDB, "light"),
types.DefaultVoterParams(),
light.Logger(nodeLogger),
)
if err != nil {
return err
}
rpccfg := rpcserver.DefaultConfig()
rpccfg.MaxBodyBytes = tmcfg.RPC.MaxBodyBytes
rpccfg.MaxHeaderBytes = tmcfg.RPC.MaxHeaderBytes
rpccfg.MaxOpenConnections = tmcfg.RPC.MaxOpenConnections
// If necessary adjust global WriteTimeout to ensure it's greater than
// TimeoutBroadcastTxCommit.
// See https://github.com/tendermint/tendermint/issues/3435
if rpccfg.WriteTimeout <= tmcfg.RPC.TimeoutBroadcastTxCommit {
rpccfg.WriteTimeout = tmcfg.RPC.TimeoutBroadcastTxCommit + 1*time.Second
}
p, err := lproxy.NewProxy(c, tmcfg.RPC.ListenAddress, providers[0], rpccfg, nodeLogger,
lrpc.KeyPathFn(lrpc.DefaultMerkleKeyPathFn()))
if err != nil {
return err
}
logger.Info("Starting proxy...", "laddr", tmcfg.RPC.ListenAddress)
if err := p.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
logger.Error("proxy ListenAndServe", "err", err)
}
return nil
}
// FIXME: Temporarily disconnected maverick until it is redesigned
// startMaverick starts a Maverick node that runs the application directly. It assumes the Tendermint
// configuration is in $TMHOME/config/tendermint.toml.
func startMaverick(cfg *Config) error {
app, err := NewApplication(cfg)
if err != nil {
return err
}
tmcfg, logger, nodeKey, err := setupNode()
if err != nil {
return fmt.Errorf("failed to setup config: %w", err)
}
misbehaviors := make(map[int64]mcs.Misbehavior, len(cfg.Misbehaviors))
for heightString, misbehaviorString := range cfg.Misbehaviors {
height, _ := strconv.ParseInt(heightString, 10, 64)
misbehaviors[height] = mcs.MisbehaviorList[misbehaviorString]
}
privKey, _ := maverick.LoadOrGenFilePV(tmcfg.PrivValidatorKeyFile(), tmcfg.PrivValidatorStateFile(), tmcfg.PrivKeyType)
n, err := maverick.NewNode(tmcfg,
privKey,
nodeKey,
proxy.NewLocalClientCreator(app),
maverick.DefaultGenesisDocProviderFunc(tmcfg),
maverick.DefaultDBProvider,
maverick.DefaultMetricsProvider(tmcfg.Instrumentation),
logger,
misbehaviors,
)
if err != nil {
return err
}
return n.Start()
}
// startSigner starts a signer server connecting to the given endpoint.
func startSigner(cfg *Config) error {
filePV := privval.LoadFilePV(cfg.PrivValKey, cfg.PrivValState)
protocol, address := tmnet.ProtocolAndAddress(cfg.PrivValServer)
var dialFn privval.SocketDialer
switch protocol {
case "tcp":
dialFn = privval.DialTCPFn(address, 3*time.Second, ed25519.GenPrivKey())
case "unix":
dialFn = privval.DialUnixFn(address)
default:
return fmt.Errorf("invalid privval protocol %q", protocol)
}
endpoint := privval.NewSignerDialerEndpoint(logger, dialFn,
privval.SignerDialerEndpointRetryWaitInterval(1*time.Second),
privval.SignerDialerEndpointConnRetries(100))
err := privval.NewSignerServer(endpoint, cfg.ChainID, filePV).Start()
if err != nil {
return err
}
logger.Info(fmt.Sprintf("Remote signer connecting to %v", cfg.PrivValServer))
return nil
}
func setupNode() (*config.Config, log.Logger, *p2p.NodeKey, error) {
var tmcfg *config.Config
home := os.Getenv("OCHOME")
if home == "" {
return nil, nil, nil, errors.New("OCHOME not set")
}
viper.AddConfigPath(filepath.Join(home, "config"))
viper.SetConfigName("config")
if err := viper.ReadInConfig(); err != nil {
return nil, nil, nil, err
}
tmcfg = config.DefaultConfig()
if err := viper.Unmarshal(tmcfg); err != nil {
return nil, nil, nil, err
}
tmcfg.SetRoot(home)
if err := tmcfg.ValidateBasic(); err != nil {
return nil, nil, nil, fmt.Errorf("error in config file: %w", err)
}
if tmcfg.LogFormat == config.LogFormatJSON {
logger = log.NewOCJSONLogger(log.NewSyncWriter(os.Stdout))
}
nodeLogger, err := tmflags.ParseLogLevel(tmcfg.LogLevel, logger, config.DefaultLogLevel)
if err != nil {
return nil, nil, nil, err
}
nodeLogger = nodeLogger.With("module", "main")
nodeKey, err := p2p.LoadOrGenNodeKey(tmcfg.NodeKeyFile())
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to load or gen node key %s: %w", tmcfg.NodeKeyFile(), err)
}
return tmcfg, nodeLogger, nodeKey, nil
}
// rpcEndpoints takes a list of persistent peers and splits them into a list of rpc endpoints
// using 26657 as the port number
func rpcEndpoints(peers string) []string {
arr := strings.Split(peers, ",")
endpoints := make([]string, len(arr))
for i, v := range arr {
urlString := strings.SplitAfter(v, "@")[1]
hostName := strings.Split(urlString, ":26656")[0]
// use RPC port instead
port := 26657
rpcEndpoint := "http://" + hostName + ":" + fmt.Sprint(port)
endpoints[i] = rpcEndpoint
}
return endpoints
}
|
[
"\"OCHOME\""
] |
[] |
[
"OCHOME"
] |
[]
|
["OCHOME"]
|
go
| 1 | 0 | |
shakemap/coremods/model.py
|
"""
Process a ShakeMap, based on the configuration and data found in
shake_data.hdf, and produce output in shake_result.hdf.
"""
import os
import argparse
import inspect
import os.path
import time as time
import copy
from time import gmtime, strftime
import shutil
from datetime import date
import json
import numpy as np
import numpy.ma as ma
from openquake.hazardlib import imt
import openquake.hazardlib.const as oqconst
import fiona
import cartopy.io.shapereader as shpreader
from shapely.geometry import shape
import concurrent.futures as cf
# local imports
from mapio.geodict import GeoDict
from mapio.grid2d import Grid2D
from .base import CoreModule, Contents
from shakelib.rupture.point_rupture import PointRupture
from shakelib.sites import Sites
from shakelib.distance import Distance, get_distance, get_distance_measures
from shakelib.multigmpe import MultiGMPE
from shakelib.virtualipe import VirtualIPE
from shakelib.utils.utils import get_extent, thirty_sec_min, thirty_sec_max
from shakelib.utils.imt_string import oq_to_file
from shakelib.utils.containers import ShakeMapInputContainer
from impactutils.io.smcontainers import ShakeMapOutputContainer
from shakelib.rupture import constants
from shakemap.utils.config import get_config_paths
from shakemap.utils.utils import get_object_from_config
from shakemap._version import get_versions
from shakemap.utils.generic_amp import get_generic_amp_factors
from shakemap.c.clib import make_sigma_matrix, geodetic_distance_fast, make_sd_array
# from shakemap.utils.exception import TerminateShakeMap
from shakelib.directivity.rowshandel2013 import Rowshandel2013
#
# default_stddev_inter: This is a stand-in for tau when the gmpe set
# doesn't provide it. It is an educated guess based
# on the NGA-west, Akkar et al, and BC Hydro gmpes.
# It's not perfect, but probably isn't too far off.
# It is only used when the GMPE(s) don't provide a
# breakdown of the uncertainty terms. When used,
# this value is multiplied by the total standard
# deviation to get tau. The square of tau is then
# subtracted from the squared total stddev and the
# square root of the result is then used as the
# within-event stddev (phi).
#
SM_CONSTS = {"default_stddev_inter": 0.55, "default_stddev_inter_mmi": 0.55}
class DataFrame:
def __init__(self):
df = None # noqa
imts = None # noqa
sx = None # noqa
dx = None # noqa
class ModelModule(CoreModule):
"""
model -- Interpolate ground motions to a grid or list of locations.
"""
command_name = "model"
targets = [r"products/shake_result\.hdf"]
dependencies = [("shake_data.hdf", True)]
no_seismic = False
no_macroseismic = False
no_rupture = False
use_simulations = False
rock_vs30 = 760.0
soil_vs30 = 180.0
def __init__(self, eventid):
super(ModelModule, self).__init__(eventid)
self.contents = Contents(None, None, eventid)
#
# Set up a bunch of dictionaries that will be keyed to IMTs
#
self.nominal_bias = {} # holds an average bias for each IMT
self.psd_raw = {} # raw phi (intra-event stddev) of the output points
self.psd = {} # phi (intra-event stddev) of the output points
self.tsd = {} # tau (inter-event stddev) of the output points
#
# These are arrays (keyed by IMT) of the station data that will be
# used to compute the bias and do the interpolation, they are filled
# in the _fillDataArrays method
#
self.sta_per_ix = {}
self.sta_lons_rad = {}
self.sta_lats_rad = {}
self.sta_resids = {}
self.sta_phi = {}
self.sta_tau = {}
self.sta_sig_extra = {}
self.sta_rrups = {}
#
# These are useful matrices that we compute in the bias function
# that we can reuse in the MVN function
#
self.T_D = {}
self.cov_WD_WD_inv = {}
self.mu_H_yD = {}
self.cov_HH_yD = {}
#
# Some variables and arrays used in both the bias and MVN functions
#
self.no_native_flag = {}
self.imt_types = {}
self.len_types = {}
self.imt_Y_ind = {}
#
# These hold the main outputs of the MVN
#
self.outgrid = {} # Holds the interpolated output arrays keyed by IMT
self.outsd = {} # Holds the standard deviation arrays keyed by IMT
self.outphi = {} # Holds the intra-event standard deviation arrays
self.outtau = {} # Holds the inter-event standard deviation arrays
#
# Places to put the results for the attenuation plots
#
self.atten_rock_mean = {}
self.atten_soil_mean = {}
self.atten_rock_sd = {}
self.atten_soil_sd = {}
def parseArgs(self, arglist):
"""
Set up the object to accept the --no_seismic, --no_macroseismic,
and --no_rupture flags.
"""
parser = argparse.ArgumentParser(
prog=self.__class__.command_name, description=inspect.getdoc(self.__class__)
)
parser.add_argument(
"-s",
"--no_seismic",
action="store_true",
help="Exclude instrumental seismic data from "
"the processing, ignoring any that may exist in "
"the input directory.",
)
parser.add_argument(
"-m",
"--no_macroseismic",
action="store_true",
help="Exclude macroseismic data from the "
"processing, ignoring any that may exist in the "
"input directory.",
)
parser.add_argument(
"-r",
"--no_rupture",
action="store_true",
help="Exclude a rupture model from the "
"processing, ignoring any that may exist in the "
"input directory.",
)
#
# This line should be in any modules that overrides this
# one. It will collect up everything after the current
# modules options in args.rem, which should be returned
# by this function. Note: doing parser.parse_known_args()
# will not work as it will suck up any later modules'
# options that are the same as this one's.
#
parser.add_argument("rem", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
args = parser.parse_args(arglist)
if args.no_seismic:
self.no_seismic = True
if args.no_macroseismic:
self.no_macroseismic = True
if args.no_rupture:
self.no_rupture = True
return args.rem
def execute(self):
"""
Interpolate ground motions to a grid or list of locations.
Raises:
NotADirectoryError: When the event data directory does not exist.
FileNotFoundError: When the the shake_data HDF file does not exist.
"""
self.logger.debug("Starting model...")
# ---------------------------------------------------------------------
# Make the input container and extract the config
# ---------------------------------------------------------------------
self._setInputContainer()
self.config = self.ic.getConfig()
self.sim_imt_paths = [x for x in self.ic.getArrays() if "simulations" in x]
if len(self.sim_imt_paths):
self.use_simulations = True
self.config["use_simulations"] = self.use_simulations
# ---------------------------------------------------------------------
# Clear away results from previous runs
# ---------------------------------------------------------------------
self._clearProducts()
# ---------------------------------------------------------------------
# Retrieve a bunch of config options and set them as attributes
# ---------------------------------------------------------------------
self._setConfigOptions()
# ---------------------------------------------------------------------
# Instantiate the gmpe, gmice, and ipe
# Here we make a placeholder gmpe so that we can make the
# rupture and distance contexts; later we'll make the
# IMT-specific gmpes
# ---------------------------------------------------------------------
self.default_gmpe = MultiGMPE.__from_config__(self.config)
self.gmice = get_object_from_config("gmice", "modeling", self.config)
if (
self.config["ipe_modules"][self.config["modeling"]["ipe"]][0]
== "VirtualIPE"
):
pgv_imt = imt.from_string("PGV")
ipe_gmpe = MultiGMPE.__from_config__(self.config, filter_imt=pgv_imt)
self.ipe = VirtualIPE.__fromFuncs__(ipe_gmpe, self.gmice)
else:
ipe = get_object_from_config("ipe", "modeling", self.config)
if "vs30" not in ipe.REQUIRES_SITES_PARAMETERS:
# REQUIRES_SITES_PARAMETERS is now a frozen set so we have to
# work around it
tmpset = set(ipe.REQUIRES_SITES_PARAMETERS)
tmpset.add("vs30")
ipe.REQUIRES_SITES_PARAMETERS = frozenset(tmpset)
ipe.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = (
oqconst.IMC.GREATER_OF_TWO_HORIZONTAL
)
self.ipe = MultiGMPE.__from_list__([ipe], [1.0])
ipe_sd_types = self.ipe.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if len(ipe_sd_types) == 1:
self.ipe_total_sd_only = True
self.ipe_stddev_types = [oqconst.StdDev.TOTAL]
else:
self.ipe_total_sd_only = False
self.ipe_stddev_types = [
oqconst.StdDev.TOTAL,
oqconst.StdDev.INTER_EVENT,
oqconst.StdDev.INTRA_EVENT,
]
# ---------------------------------------------------------------------
# Get the rupture object and rupture context
# ---------------------------------------------------------------------
self.rupture_obj = self.ic.getRuptureObject()
# If the --no_rupture flag is used, switch to a PointRupture
if self.no_rupture:
self.rupture_obj = PointRupture(self.rupture_obj._origin)
if self.config["modeling"]["mechanism"] is not None:
self.rupture_obj._origin.setMechanism(
mech=self.config["modeling"]["mechanism"]
)
self.rx = self.rupture_obj.getRuptureContext([self.default_gmpe])
# TODO: figure out how to not have to do this
if self.rx.rake is None:
self.rx.rake = 0
#
# Set up the coordinates for the attenuation curves
#
repi = np.logspace(-1, 3, 200)
pt = self.rupture_obj._origin.getHypo()
self.atten_coords = {
"lons": np.full_like(repi, pt.x),
"lats": np.array([pt.y + x / 111.0 for x in repi]),
}
self.point_source = PointRupture(self.rupture_obj._origin)
# ---------------------------------------------------------------------
# The output locations: either a grid or a list of points
# ---------------------------------------------------------------------
self.logger.debug("Setting output params...")
self._setOutputParams()
landmask = self._getLandMask()
# We used to do this, but we've decided not to. Leaving the code
# in place in case we change our minds.
# if landmask is not None and np.all(landmask):
# raise TerminateShakeMap("Mapped area is entirely water")
# ---------------------------------------------------------------------
# If the gmpe doesn't break down its stardard deviation into
# within- and between-event terms, we need to handle things
# somewhat differently.
# ---------------------------------------------------------------------
gmpe_sd_types = self.default_gmpe.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if len(gmpe_sd_types) == 1:
self.gmpe_total_sd_only = True
self.gmpe_stddev_types = [oqconst.StdDev.TOTAL]
else:
self.gmpe_total_sd_only = False
self.gmpe_stddev_types = [
oqconst.StdDev.TOTAL,
oqconst.StdDev.INTER_EVENT,
oqconst.StdDev.INTRA_EVENT,
]
# ---------------------------------------------------------------------
# Are we going to include directivity?
# ---------------------------------------------------------------------
# Config option?
dir_conf = self.config["modeling"]["directivity"]
# Is the rupture not a point source?
rup_check = not isinstance(self.rupture_obj, PointRupture)
if dir_conf and rup_check:
self.do_directivity = True
# The following attribute will be used to store a list of tuples,
# where each tuple will contain the 1) result of the directivity
# model (for the periods defined by Rowshandel2013) and 2) the
# associated distance context. The distance context is needed
# within the _gmas function for figuring out which of the results
# should be used when combining it with the GMPE result. We store
# the pre-defined period first and interpolate later because there
# is some optimization to doing it this way (some of the
# calculation is period independent).
self.dir_results = []
# But if we want to save the results that were actually used for
# each IMT, so we use a dictionary. This uses keys that are
# the same as self.outgrid.
self.dir_output = {}
else:
self.do_directivity = False
# ---------------------------------------------------------------------
# Station data: Create DataFrame(s) with the input data:
# df1 for instrumented data
# df2 for non-instrumented data
# ---------------------------------------------------------------------
self.logger.debug("Setting data frames...")
self._setDataFrames()
# ---------------------------------------------------------------------
# Add the predictions, etc. to the data frames
# ---------------------------------------------------------------------
self.logger.debug("Populating data frames...")
self._populateDataFrames()
# ---------------------------------------------------------------------
# Try to make all the derived IMTs possible from MMI (if we have MMI)
# ---------------------------------------------------------------------
self._deriveIMTsFromMMI()
# ---------------------------------------------------------------------
# Now make MMI from the station data where possible
# ---------------------------------------------------------------------
self._deriveMMIFromIMTs()
self.logger.debug("Getting combined IMTs")
# ---------------------------------------------------------------------
# Get the combined set of input and output IMTs, their periods,
# and an index dictionary, then make the cross-correlation function
# ---------------------------------------------------------------------
if self.use_simulations:
#
# Ignore what is in the configuration and make maps only for the
# IMTs that are in the set of simulations (and MMI).
#
self.combined_imt_set = set([x.split("/")[-1] for x in self.sim_imt_paths])
self.sim_df = {}
for imtstr in self.combined_imt_set:
dset, _ = self.ic.getArray(["simulations"], imtstr)
self.sim_df[imtstr] = dset
self.combined_imt_set |= set(["MMI"])
else:
self.combined_imt_set = self.imt_out_set.copy()
for ndf in self.dataframes:
self.combined_imt_set |= getattr(self, ndf).imts
self.imt_per, self.imt_per_ix = _get_period_arrays(self.combined_imt_set)
self.ccf = get_object_from_config("ccf", "modeling", self.config, self.imt_per)
self.logger.debug("Doing bias")
# ---------------------------------------------------------------------
# Do the bias for all of the input and output IMTs. Hold on
# to some of the products that will be used for the interpolation.
# The "raw" values are the stddevs that have not been inflated by
# the additional sigma (if any) of the point-source to finite
# rupture approximation.
# ---------------------------------------------------------------------
# ---------------------------------------------------------------------
# Do some prep, the bias, and the directivity prep
# ---------------------------------------------------------------------
self._fillDataArrays()
self._computeBias()
self._computeDirectivityPredictionLocations()
# ---------------------------------------------------------------------
# Now do the MVN with the intra-event residuals
# ---------------------------------------------------------------------
self.logger.debug("Doing MVN...")
if self.max_workers > 0:
with cf.ThreadPoolExecutor(max_workers=self.max_workers) as ex:
results = ex.map(self._computeMVN, self.imt_out_set)
list(results) # Check threads for possible exceptions, etc.
else:
for imt_str in self.imt_out_set:
self._computeMVN(imt_str)
self._applyCustomMask()
# ---------------------------------------------------------------------
# Output the data and metadata
# ---------------------------------------------------------------------
product_path = os.path.join(self.datadir, "products")
if not os.path.isdir(product_path):
os.mkdir(product_path)
oc = ShakeMapOutputContainer.create(
os.path.join(product_path, "shake_result.hdf")
)
# ---------------------------------------------------------------------
# Might as well stick the whole config in the result
# ---------------------------------------------------------------------
oc.setConfig(self.config)
# ---------------------------------------------------------------------
# We're going to need masked arrays of the output grids later, so
# make them now.
# ---------------------------------------------------------------------
moutgrid = self._getMaskedGrids(landmask)
# ---------------------------------------------------------------------
# Get the info dictionary that will become info.json, and
# store it in the output container
# ---------------------------------------------------------------------
info = self._getInfo(moutgrid)
oc.setMetadata(info)
# ---------------------------------------------------------------------
# Add the rupture JSON as a text string
# ---------------------------------------------------------------------
oc.setRuptureDict(self.rupture_obj._geojson)
# ---------------------------------------------------------------------
# Fill the station dictionary for stationlist.json and add it to
# the output container
# ---------------------------------------------------------------------
sjdict = self._fillStationJSON()
oc.setStationDict(sjdict)
# ---------------------------------------------------------------------
# Add the output grids or points to the output; include some
# metadata.
# ---------------------------------------------------------------------
if self.do_grid:
self._storeGriddedData(oc)
else:
self._storePointData(oc)
self._storeAttenuationData(oc)
oc.close()
self.ic.close()
self.contents.addFile(
"shakemapHDF",
"Comprehensive ShakeMap HDF Data File",
"HDF file containing all ShakeMap results.",
"shake_result.hdf",
"application/x-bag",
)
# -------------------------------------------------------------------------
# End execute()
# -------------------------------------------------------------------------
def _setInputContainer(self):
"""
Open the input container and set
the event's current data directory.
Raises:
NotADirectoryError: When the event data directory does not exist.
FileNotFoundError: When the the shake_data HDF file does not exist.
"""
#
# Find the shake_data.hdf file
#
_, data_path = get_config_paths()
datadir = os.path.join(data_path, self._eventid, "current")
if not os.path.isdir(datadir):
raise NotADirectoryError(f"{datadir} is not a valid directory.")
datafile = os.path.join(datadir, "shake_data.hdf")
if not os.path.isfile(datafile):
raise FileNotFoundError(f"{datafile} does not exist.")
self.datadir = datadir
self.ic = ShakeMapInputContainer.load(datafile)
def _clearProducts(self):
"""
Function to delete an event's products directory if it exists.
Returns:
nothing
"""
products_path = os.path.join(self.datadir, "products")
if os.path.isdir(products_path):
shutil.rmtree(products_path, ignore_errors=True)
pdl_path = os.path.join(self.datadir, "pdl")
if os.path.isdir(pdl_path):
shutil.rmtree(pdl_path, ignore_errors=True)
def _setConfigOptions(self):
"""
Pull various useful configuration options out of the config
dictionary.
Returns:
nothing
"""
# ---------------------------------------------------------------------
# Processing parameters
# ---------------------------------------------------------------------
self.max_workers = self.config["system"]["max_workers"]
# ---------------------------------------------------------------------
# Do we apply the generic amplification factors?
# ---------------------------------------------------------------------
self.apply_gafs = self.config["modeling"]["apply_generic_amp_factors"]
# ---------------------------------------------------------------------
# Bias parameters
# ---------------------------------------------------------------------
self.do_bias = self.config["modeling"]["bias"]["do_bias"]
self.bias_max_range = self.config["modeling"]["bias"]["max_range"]
self.bias_max_mag = self.config["modeling"]["bias"]["max_mag"]
self.bias_max_dsigma = self.config["modeling"]["bias"]["max_delta_sigma"]
# ---------------------------------------------------------------------
# Outlier parameters
# ---------------------------------------------------------------------
self.do_outliers = self.config["data"]["outlier"]["do_outliers"]
self.outlier_deviation_level = self.config["data"]["outlier"]["max_deviation"]
self.outlier_max_mag = self.config["data"]["outlier"]["max_mag"]
self.outlier_valid_stations = self.config["data"]["outlier"]["valid_stations"]
# ---------------------------------------------------------------------
# These are the IMTs we want to make
# ---------------------------------------------------------------------
self.imt_out_set = set(self.config["interp"]["imt_list"])
# ---------------------------------------------------------------------
# The x and y resolution of the output grid
# ---------------------------------------------------------------------
self.smdx = self.config["interp"]["prediction_location"]["xres"]
self.smdy = self.config["interp"]["prediction_location"]["yres"]
self.nmax = self.config["interp"]["prediction_location"]["nmax"]
# ---------------------------------------------------------------------
# Get the Vs30 file name
# ---------------------------------------------------------------------
self.vs30default = self.config["data"]["vs30default"]
self.vs30_file = self.config["data"]["vs30file"]
if not self.vs30_file:
self.vs30_file = None
self.mask_file = self.config["data"]["maskfile"]
if not self.mask_file:
self.mask_file = None
def _setOutputParams(self):
"""
Set variables dealing with the output grid or points
Returns:
nothing
"""
if self.use_simulations:
self.do_grid = True
imt_grp = self.sim_imt_paths[0]
groups = imt_grp.split("/")
myimt = groups[-1]
del groups[-1]
data, geodict = self.ic.getArray(groups, myimt)
self.W = geodict["xmin"]
self.E = geodict["xmax"]
self.S = geodict["ymin"]
self.N = geodict["ymax"]
self.smdx = geodict["dx"]
self.smdy = geodict["dy"]
self.sites_obj_out = Sites.fromBounds(
self.W,
self.E,
self.S,
self.N,
self.smdx,
self.smdy,
defaultVs30=self.vs30default,
vs30File=self.vs30_file,
padding=True,
resample=True,
)
self.smnx, self.smny = self.sites_obj_out.getNxNy()
self.sx_out = self.sites_obj_out.getSitesContext()
lons, lats = np.meshgrid(self.sx_out.lons, self.sx_out.lats)
self.sx_out.lons = lons.copy()
self.sx_out.lats = lats.copy()
self.lons = lons.flatten()
self.lats = lats.flatten()
self.depths = np.zeros_like(lats)
dist_obj_out = Distance.fromSites(
self.default_gmpe, self.sites_obj_out, self.rupture_obj
)
elif (
self.config["interp"]["prediction_location"]["file"]
and self.config["interp"]["prediction_location"]["file"] != "None"
):
#
# FILE: Open the file and get the output points
#
self.do_grid = False
in_sites = np.genfromtxt(
self.config["interp"]["prediction_location"]["file"],
autostrip=True,
unpack=True,
dtype=[np.double, np.double, np.double, "<U80"],
)
if np.size(in_sites) == 0:
self.logger.info("Points file is empty; nothing to do")
return
elif np.size(in_sites) == 1:
lons, lats, vs30, idents = in_sites.item()
self.idents = [idents]
else:
try:
lons, lats, vs30, self.idents = zip(*in_sites)
except Exception:
lons, lats, vs30, self.idents = zip(in_sites)
self.lons = np.array(lons).reshape(1, -1)
self.lats = np.array(lats).reshape(1, -1)
self.vs30 = np.array(vs30).reshape(1, -1)
self.depths = np.zeros_like(self.lats)
self.W = thirty_sec_min(np.min(self.lons))
self.E = thirty_sec_max(np.max(self.lons))
self.S = thirty_sec_min(np.min(self.lats))
self.N = thirty_sec_max(np.max(self.lats))
self.smnx = np.size(self.lons)
self.smny = 1
dist_obj_out = Distance(
self.default_gmpe, self.lons, self.lats, self.depths, self.rupture_obj
)
self.sites_obj_out = Sites.fromBounds(
self.W,
self.E,
self.S,
self.N,
self.smdx,
self.smdy,
defaultVs30=self.vs30default,
vs30File=self.vs30_file,
padding=True,
resample=True,
)
self.sx_out = self.sites_obj_out.getSitesContext(
{"lats": self.lats, "lons": self.lons}
)
# Replace the Vs30 from the grid (or default) with the Vs30
# provided with the site list.
if np.any(self.vs30 > 0):
self.sx_out.vs30 = self.vs30
Sites._addDepthParameters(self.sx_out)
else:
#
# GRID: Figure out the grid parameters and get output points
#
self.do_grid = True
if self.config["interp"]["prediction_location"]["extent"]:
self.W, self.S, self.E, self.N = self.config["interp"][
"prediction_location"
]["extent"]
else:
self.W, self.E, self.S, self.N = get_extent(
self.rupture_obj, config=self.config
)
# Adjust resolution to be under nmax
self._adjustResolution()
self.sites_obj_out = Sites.fromBounds(
self.W,
self.E,
self.S,
self.N,
self.smdx,
self.smdy,
defaultVs30=self.vs30default,
vs30File=self.vs30_file,
padding=True,
resample=True,
)
self.smnx, self.smny = self.sites_obj_out.getNxNy()
self.sx_out = self.sites_obj_out.getSitesContext()
lons, lats = np.meshgrid(self.sx_out.lons, self.sx_out.lats)
self.sx_out.lons = lons.copy()
self.sx_out.lats = lats.copy()
self.lons = lons.flatten()
self.lats = lats.flatten()
self.depths = np.zeros_like(lats)
dist_obj_out = Distance.fromSites(
self.default_gmpe, self.sites_obj_out, self.rupture_obj
)
#
# TODO: This will break if the IPE needs distance measures
# that the GMPE doesn't; should make this a union of the
# requirements of both
#
self.dx_out = dist_obj_out.getDistanceContext()
#
# Set up the sites and distance contexts for the attenuation curves
#
self.atten_sx_rock = self.sites_obj_out.getSitesContext(
self.atten_coords, rock_vs30=self.rock_vs30
)
self.atten_sx_soil = self.sites_obj_out.getSitesContext(
self.atten_coords, rock_vs30=self.soil_vs30
)
self.atten_dx = Distance(
self.default_gmpe,
self.atten_coords["lons"],
self.atten_coords["lats"],
np.zeros_like(self.atten_coords["lons"]),
rupture=self.point_source,
).getDistanceContext()
self.lons_out_rad = np.radians(self.lons).flatten()
self.lats_out_rad = np.radians(self.lats).flatten()
self.flip_lons = False
if self.W > 0 and self.E < 0:
self.flip_lons = True
self.lons_out_rad[self.lons_out_rad < 0] += 2 * np.pi
def _setDataFrames(self):
"""
Extract the StationList object from the input container and
fill the DataFrame class and keep a list of dataframes.
- df1 holds the instrumented data (PGA, PGV, SA)
- df2 holds the non-instrumented data (MMI)
"""
self.dataframes = []
try:
self.stations = self.ic.getStationList()
except AttributeError:
return
if self.stations is None:
return
for dfid, val in (("df1", True), ("df2", False)):
if dfid == "df1" and self.no_seismic:
continue
if dfid == "df2" and self.no_macroseismic:
continue
sdf, imts = self.stations.getStationDictionary(instrumented=val)
if sdf is not None:
df = DataFrame()
df.df = sdf
df.imts = imts
setattr(self, dfid, df)
self.dataframes.append(dfid)
# Flag the stations in the bad stations list from the config
if not hasattr(self, "df1"):
return
evdt = date(
self.rupture_obj._origin.time.year,
self.rupture_obj._origin.time.month,
self.rupture_obj._origin.time.day,
)
nostart = date(1970, 1, 1)
self.df1.df["flagged"] = np.full_like(self.df1.df["lon"], 0, dtype=np.bool)
if "bad_stations" not in self.config["data"]:
return
for sid, dates in self.config["data"]["bad_stations"].items():
ondate, offdate = dates.split(":")
year, month, day = map(int, ondate.split("-"))
ondt = date(year, month, day)
if offdate:
year, month, day = map(int, offdate.split("-"))
offdt = date(year, month, day)
else:
offdt = None
bad = False
if (ondt == nostart or ondt <= evdt) and (offdt is None or offdt >= evdt):
bad = True
if bad:
self.df1.df["flagged"] |= self.df1.df["id"] == sid
def _populateDataFrames(self):
"""
Make the sites and distance contexts for each dataframe then
compute the predictions for the IMTs in that dataframe.
"""
for dfid in self.dataframes:
dfn = getattr(self, dfid)
df = dfn.df
# -----------------------------------------------------------------
# Get the sites and distance contexts
# -----------------------------------------------------------------
df["depth"] = np.zeros_like(df["lon"])
lldict = {"lons": df["lon"], "lats": df["lat"]}
dfn.sx = self.sites_obj_out.getSitesContext(lldict)
dfn.sx_rock = copy.deepcopy(dfn.sx)
dfn.sx_rock.vs30 = np.full_like(dfn.sx.vs30, self.rock_vs30)
dfn.sx_soil = copy.deepcopy(dfn.sx)
dfn.sx_soil.vs30 = np.full_like(dfn.sx.vs30, self.soil_vs30)
dist_obj = Distance(
self.default_gmpe, df["lon"], df["lat"], df["depth"], self.rupture_obj
)
dfn.dx = dist_obj.getDistanceContext()
# -----------------------------------------------------------------
# Are we doing directivity?
# -----------------------------------------------------------------
if self.do_directivity is True:
self.logger.info(f"Directivity for {dfid}...")
time1 = time.time()
dir_df = Rowshandel2013(
self.rupture_obj._origin,
self.rupture_obj,
df["lat"].reshape((1, -1)),
df["lon"].reshape((1, -1)),
df["depth"].reshape((1, -1)),
dx=1.0,
T=Rowshandel2013.getPeriods(),
a_weight=0.5,
mtype=1,
)
self.dir_results.append((dir_df, dfn.dx))
directivity_time = time.time() - time1
self.logger.debug(
f"Directivity {dfid} evaluation time: {directivity_time:f} sec"
)
# -----------------------------------------------------------------
# Do the predictions and other bookkeeping for each IMT
# -----------------------------------------------------------------
imt_set = self.imt_out_set | set(dfn.imts)
for imtstr in imt_set:
oqimt = imt.from_string(imtstr)
gmpe = None
not_supported = False
if imtstr != "MMI":
try:
gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)
except KeyError:
self.logger.warn(
f"Input IMT {imtstr} not supported by GMPE: ignoring"
)
not_supported = True
if not_supported:
pmean = np.full_like(df[imtstr], np.nan)
pmean_rock = np.full_like(df[imtstr], np.nan)
pmean_soil = np.full_like(df[imtstr], np.nan)
pstddev = [None] * 3
pstddev[0] = np.full_like(df[imtstr], np.nan)
pstddev[1] = np.full_like(df[imtstr], np.nan)
pstddev[2] = np.full_like(df[imtstr], np.nan)
pstddev_rock = [None] * 1
pstddev_soil = [None] * 1
pstddev_rock[0] = np.full_like(df[imtstr], np.nan)
pstddev_soil[0] = np.full_like(df[imtstr], np.nan)
else:
pmean, pstddev = self._gmas(
gmpe, dfn.sx, dfn.dx, oqimt, self.apply_gafs
)
pmean_rock, pstddev_rock = self._gmas(
gmpe, dfn.sx_rock, dfn.dx, oqimt, self.apply_gafs
)
pmean_soil, pstddev_soil = self._gmas(
gmpe, dfn.sx_soil, dfn.dx, oqimt, self.apply_gafs
)
df[imtstr + "_pred"] = pmean
df[imtstr + "_pred_sigma"] = pstddev[0]
df[imtstr + "_pred_rock"] = pmean_rock
df[imtstr + "_pred_sigma_rock"] = pstddev_rock[0]
df[imtstr + "_pred_soil"] = pmean_soil
df[imtstr + "_pred_sigma_soil"] = pstddev_soil[0]
if imtstr != "MMI":
total_only = self.gmpe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter"]
else:
total_only = self.ipe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter_mmi"]
if total_only:
df[imtstr + "_pred_tau"] = tau_guess * pstddev[0]
df[imtstr + "_pred_phi"] = np.sqrt(
pstddev[0] ** 2 - df[imtstr + "_pred_tau"] ** 2
)
else:
df[imtstr + "_pred_tau"] = pstddev[1]
df[imtstr + "_pred_phi"] = pstddev[2]
#
# If we're just computing the predictions of an output
# IMT, then we can skip the residual and outlier stuff
#
if imtstr not in df:
continue
#
# Compute the total residual
#
df[imtstr + "_residual"] = df[imtstr] - df[imtstr + "_pred"]
# -------------------------------------------------------------
# Do the outlier flagging if we have a fault, or we don't
# have a fault but the event magnitude is under the limit
# -------------------------------------------------------------
if self.do_outliers and (
not isinstance(self.rupture_obj, PointRupture)
or self.rx.mag <= self.outlier_max_mag
):
#
# Make a boolean array of stations that have been
# manually rehabilitated by the operator
#
is_valid = np.full(np.shape(df["id"]), False, dtype=bool)
for valid in self.outlier_valid_stations:
is_valid |= valid == df["id"]
#
# turn off nan warnings for this statement
#
np.seterr(invalid="ignore")
flagged = (
np.abs(df[imtstr + "_residual"])
> self.outlier_deviation_level * df[imtstr + "_pred_sigma"]
) & (~is_valid)
np.seterr(invalid="warn")
#
# Add NaN values to the list of outliers
#
flagged |= np.isnan(df[imtstr + "_residual"])
self.logger.debug(
"IMT: %s, flagged: %d" % (imtstr, np.sum(flagged))
)
df[imtstr + "_outliers"] = flagged
else:
#
# Not doing outliers, but should still flag NaNs
#
flagged = np.isnan(df[imtstr + "_residual"])
df[imtstr + "_outliers"] = flagged
#
# If uncertainty hasn't been set for MMI, give it
# the default value
#
if imtstr == "MMI" and all(df["MMI_sd"] == 0):
df["MMI_sd"][:] = self.config["data"]["default_mmi_stddev"]
#
# Get the lons/lats in radians while we're at it
#
df["lon_rad"] = np.radians(df["lon"])
df["lat_rad"] = np.radians(df["lat"])
if self.flip_lons:
df["lon_rad"][df["lon_rad"] < 0] += 2 * np.pi
#
# It will be handy later on to have the rupture distance
# in the dataframes
#
dd = get_distance(
["rrup"], df["lat"], df["lon"], df["depth"], self.rupture_obj
)
df["rrup"] = dd["rrup"]
if dd["rrup_var"] is not None:
df["rrup_var"] = dd["rrup_var"]
else:
df["rrup_var"] = np.zeros_like(dd["rrup"])
def _deriveIMTsFromMMI(self):
"""
Compute all the IMTs possible from MMI
TODO: This logic needs to be revisited. We should probably make what
we have to to do the CMS to make the needed output IMTs, but
for now, we're just going to use what we have and the ccf.
"""
if "df2" not in self.dataframes:
return
df2 = self.df2.df
for gmice_imt in self.gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES:
if imt.SA == gmice_imt:
iterlist = self.gmice.DEFINED_FOR_SA_PERIODS
else:
iterlist = [None]
for period in iterlist:
if period:
oqimt = gmice_imt(period)
else:
oqimt = gmice_imt()
imtstr = str(oqimt)
np.seterr(invalid="ignore")
df2[imtstr], _ = self.gmice.getGMfromMI(
df2["MMI"], oqimt, dists=df2["rrup"], mag=self.rx.mag
)
df2[imtstr][
df2["MMI"] < self.config["data"]["min_mmi_convert"]
] = np.nan
np.seterr(invalid="warn")
df2[imtstr + "_sd"] = np.full_like(
df2["MMI"], self.gmice.getMI2GMsd()[oqimt]
)
self.df2.imts.add(imtstr)
#
# Get the predictions and stddevs
#
not_supported = False
try:
gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)
except KeyError:
self.logger.warn(
f"Input IMT {imtstr} not supported by GMPE: ignoring"
)
not_supported = True
if not_supported:
pmean = np.full_like(df2["MMI"], np.nan)
pstddev = [None] * 3
pstddev[0] = np.full_like(df2["MMI"], np.nan)
pstddev[1] = np.full_like(df2["MMI"], np.nan)
pstddev[2] = np.full_like(df2["MMI"], np.nan)
else:
pmean, pstddev = self._gmas(
gmpe, self.df2.sx, self.df2.dx, oqimt, self.apply_gafs
)
pmean_rock, pstddev_rock = self._gmas(
gmpe, self.df2.sx_rock, self.df2.dx, oqimt, self.apply_gafs
)
pmean_soil, pstddev_soil = self._gmas(
gmpe, self.df2.sx_soil, self.df2.dx, oqimt, self.apply_gafs
)
df2[imtstr + "_pred"] = pmean
df2[imtstr + "_pred_sigma"] = pstddev[0]
df2[imtstr + "_pred_rock"] = pmean_rock
df2[imtstr + "_pred_sigma_rock"] = pstddev_rock[0]
df2[imtstr + "_pred_soil"] = pmean_soil
df2[imtstr + "_pred_sigma_soil"] = pstddev_soil[0]
if imtstr != "MMI":
total_only = self.gmpe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter"]
else:
total_only = self.ipe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter_mmi"]
if total_only:
df2[imtstr + "_pred_tau"] = tau_guess * pstddev[0]
df2[imtstr + "_pred_phi"] = np.sqrt(
pstddev[0] ** 2 - df2[imtstr + "_pred_tau"] ** 2
)
else:
df2[imtstr + "_pred_tau"] = pstddev[1]
df2[imtstr + "_pred_phi"] = pstddev[2]
df2[imtstr + "_residual"] = df2[imtstr] - pmean
df2[imtstr + "_outliers"] = np.isnan(df2[imtstr + "_residual"])
df2[imtstr + "_outliers"] |= df2["MMI_outliers"]
def _deriveMMIFromIMTs(self):
"""
Make derived MMI from each of the IMTs in the input (for
which the GMICE is defined; then select the best MMI for
each station based on a list of "preferred" IMTs; also
calculate the predicted MMI and the residual.
"""
if "df1" not in self.dataframes:
return
df1 = self.df1.df
gmice_imts = [
imt.__name__ for imt in self.gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES
]
gmice_pers = self.gmice.DEFINED_FOR_SA_PERIODS
np.seterr(invalid="ignore")
df1["MMI"] = self.gmice.getPreferredMI(df1, dists=df1["rrup"], mag=self.rx.mag)
np.seterr(invalid="warn")
df1["MMI_sd"] = self.gmice.getPreferredSD()
if df1["MMI_sd"] is not None:
df1["MMI_sd"] = np.full_like(df1["lon"], df1["MMI_sd"])
for imtstr in self.df1.imts:
oqimt = imt.from_string(imtstr)
if not oqimt.string in gmice_imts:
continue
if "SA" in oqimt.string and oqimt.period not in gmice_pers:
continue
np.seterr(invalid="ignore")
df1["derived_MMI_from_" + imtstr], _ = self.gmice.getMIfromGM(
df1[imtstr], oqimt, dists=df1["rrup"], mag=self.rx.mag
)
np.seterr(invalid="warn")
df1["derived_MMI_from_" + imtstr + "_sd"] = np.full_like(
df1[imtstr], self.gmice.getGM2MIsd()[oqimt]
)
preferred_imts = ["PGV", "PGA", "SA(1.0)", "SA(0.3)", "SA(3.0"]
if df1["MMI"] is None:
df1["MMI"] = np.full_like(df1["lon"], np.nan)
df1["MMI_sd"] = np.full_like(df1["lon"], np.nan)
df1["MMI_outliers"] = np.full_like(df1["lon"], True, dtype=np.bool)
for imtstr in preferred_imts:
if "derived_MMI_from_" + imtstr in df1:
ixx = (np.isnan(df1["MMI"]) | df1["MMI_outliers"]) & ~(
np.isnan(df1["derived_MMI_from_" + imtstr])
| df1[imtstr + "_outliers"]
)
df1["MMI"][ixx] = df1["derived_MMI_from_" + imtstr][ixx]
df1["MMI_sd"][ixx] = df1["derived_MMI_from_" + imtstr + "_sd"][ixx]
df1["MMI_outliers"][ixx] = False
self.df1.imts.add("MMI")
#
# Get the prediction and stddevs
#
gmpe = None
pmean, pstddev = self._gmas(
gmpe, self.df1.sx, self.df1.dx, imt.from_string("MMI"), self.apply_gafs
)
pmean_rock, pstddev_rock = self._gmas(
gmpe, self.df1.sx_rock, self.df1.dx, imt.from_string("MMI"), self.apply_gafs
)
pmean_soil, pstddev_soil = self._gmas(
gmpe, self.df1.sx_soil, self.df1.dx, imt.from_string("MMI"), self.apply_gafs
)
df1["MMI" + "_pred"] = pmean
df1["MMI" + "_pred_sigma"] = pstddev[0]
df1["MMI" + "_pred_rock"] = pmean_rock
df1["MMI" + "_pred_sigma_rock"] = pstddev_rock[0]
df1["MMI" + "_pred_soil"] = pmean_soil
df1["MMI" + "_pred_sigma_soil"] = pstddev_soil[0]
if self.ipe_total_sd_only:
tau_guess = SM_CONSTS["default_stddev_inter_mmi"]
df1["MMI" + "_pred_tau"] = tau_guess * pstddev[0]
df1["MMI" + "_pred_phi"] = np.sqrt(
pstddev[0] ** 2 - df1["MMI" + "_pred_tau"] ** 2
)
else:
df1["MMI" + "_pred_tau"] = pstddev[1]
df1["MMI" + "_pred_phi"] = pstddev[2]
df1["MMI" + "_residual"] = df1["MMI"] - pmean
df1["MMI" + "_outliers"] |= np.isnan(df1["MMI" + "_residual"])
def _fillDataArrays(self):
"""
For each IMT get lists of the amplitudes that can contribute
to the bias and the interpolation. Keep lists of IMT, period
index, lons, lats, residuals, tau, phi, additional uncertainty,
and rupture distance.
"""
imtsets = {}
sasets = {}
for ndf in ("df1", "df2"):
df = getattr(self, ndf, None)
if df is None:
continue
imtsets[ndf], sasets[ndf] = _get_imt_lists(df)
for imtstr in self.imt_out_set:
#
# Fill the station arrays; here we use lists and append to
# them because it is much faster than appending to a numpy
# array; after the loop, the lists are converted to numpy
# arrays:
#
lons_rad = [] # longitude (in radians) of the input station
lats_rad = [] # latitude (in radians) of the input station
resids = [] # The residual of the input IMT
tau = [] # The between-event stddev of the input IMT
phi = [] # The within-event stddev of the input IMT
sig_extra = [] # Additional stddev of the input IMT
rrups = [] # The rupture distance of the input station
per_ix = []
for ndf in ("df1", "df2"):
tdf = getattr(self, ndf, None)
if tdf is None:
continue
sdf = tdf.df
for i in range(np.size(sdf["lon"])):
#
# Each station can provide 0, 1, or 2 IMTs:
#
for imtin in _get_nearest_imts(
imtstr, imtsets[ndf][i], sasets[ndf][i]
):
per_ix.append(self.imt_per_ix[imtin])
lons_rad.append(sdf["lon_rad"][i])
lats_rad.append(sdf["lat_rad"][i])
resids.append(sdf[imtin + "_residual"][i])
tau.append(sdf[imtin + "_pred_tau"][i])
phi.append(sdf[imtin + "_pred_phi"][i])
sig_extra.append(sdf[imtin + "_sd"][i])
rrups.append(sdf["rrup"][i])
self.sta_per_ix[imtstr] = np.array(per_ix)
self.sta_lons_rad[imtstr] = np.array(lons_rad)
self.sta_lats_rad[imtstr] = np.array(lats_rad)
if self.flip_lons:
self.sta_lons_rad[imtstr][self.sta_lons_rad[imtstr] < 0] += 2 * np.pi
self.sta_resids[imtstr] = np.array(resids).reshape((-1, 1))
self.sta_tau[imtstr] = np.array(tau).reshape((-1, 1))
self.sta_phi[imtstr] = np.array(phi).reshape((-1, 1))
self.sta_sig_extra[imtstr] = np.array(sig_extra)
self.sta_rrups[imtstr] = np.array(rrups)
def _computeBias(self):
"""
Compute a bias for all of the IMTs in the outputs
"""
for imtstr in self.imt_out_set:
time1 = time.time()
#
# Get the index of the (pseudo-) period of the output IMT
#
outperiod_ix = self.imt_per_ix[imtstr]
#
# Get the data and distance-limited residuals for computing
# the bias
#
sta_per_ix = self.sta_per_ix[imtstr]
sta_lons_rad = self.sta_lons_rad[imtstr]
sta_lats_rad = self.sta_lats_rad[imtstr]
sta_tau = self.sta_tau[imtstr]
sta_phi = self.sta_phi[imtstr]
sta_sig_extra = self.sta_sig_extra[imtstr]
dix = self.sta_rrups[imtstr] > self.bias_max_range
sta_resids_dl = self.sta_resids[imtstr].copy()
if len(dix) > 0:
sta_resids_dl[dix] = 0.0
#
# If there are no stations, bail out
#
nsta = np.size(sta_lons_rad)
if nsta == 0:
self.mu_H_yD[imtstr] = 0.0
self.cov_HH_yD[imtstr] = 0.0
self.nominal_bias[imtstr] = 0.0
nom_variance = 0.0
bias_time = time.time() - time1
#
# Write the nominal values of the bias and its stddev to log
#
self.logger.debug(
"%s: nom bias %f nom stddev %f; %d stations (time=%f sec)"
% (
imtstr,
self.nominal_bias[imtstr],
np.sqrt(nom_variance),
nsta,
bias_time,
)
)
continue
#
# Set up the IMT indices
#
imt_types = np.sort(np.unique(sta_per_ix))
len_types = len(imt_types)
self.imt_types[imtstr] = imt_types
self.len_types[imtstr] = len_types
sa_inds = {}
for i in range(len_types):
sa_inds[imt_types[i]] = np.where(sta_per_ix == imt_types[i])[0]
if outperiod_ix not in imt_types:
self.no_native_flag[imtstr] = True
imt_types_alt = np.sort(
np.concatenate([imt_types, np.array([outperiod_ix])])
)
self.imt_Y_ind[imtstr] = np.where(outperiod_ix == imt_types_alt)[0][0]
else:
self.no_native_flag[imtstr] = False
#
# Build T_D and corr_HH_D
#
if self.no_native_flag[imtstr] is False:
T_D = np.zeros((nsta, len_types))
for i in range(len_types):
T_D[sa_inds[imt_types[i]], i] = sta_tau[sa_inds[imt_types[i]], 0]
corr_HH_D = np.zeros((len_types, len_types))
ones = np.ones(len_types, dtype=np.long).reshape((-1, 1))
t1 = imt_types.reshape((1, -1)) * ones
t2 = imt_types.reshape((-1, 1)) * ones.T
self.ccf.getCorrelation(t1, t2, corr_HH_D)
else:
T_D = np.zeros((nsta, len_types + 1))
for i in range(len_types + 1):
if i == self.imt_Y_ind[imtstr]:
continue
if i < self.imt_Y_ind[imtstr]:
T_D[sa_inds[imt_types[i]], i] = sta_tau[
sa_inds[imt_types[i]], 0
]
else:
T_D[sa_inds[imt_types[i - 1]], i] = sta_tau[
sa_inds[imt_types[i - 1]], 0
]
corr_HH_D = np.zeros((len_types + 1, len_types + 1))
ones = np.ones(len_types + 1, dtype=np.long).reshape((-1, 1))
t1 = imt_types_alt.reshape((1, -1)) * ones
t2 = imt_types_alt.reshape((-1, 1)) * ones.T
self.ccf.getCorrelation(t1, t2, corr_HH_D)
#
# Make cov_WD_WD_inv (Sigma_22_inv)
#
matrix22 = np.empty((nsta, nsta), dtype=np.double)
geodetic_distance_fast(
sta_lons_rad, sta_lats_rad, sta_lons_rad, sta_lats_rad, matrix22
)
ones = np.ones(nsta, dtype=np.long).reshape((-1, 1))
t1_22 = sta_per_ix.reshape((1, -1)) * ones
t2_22 = sta_per_ix.reshape((-1, 1)) * ones.T
self.ccf.getCorrelation(t1_22, t2_22, matrix22)
sta_phi_flat = sta_phi.flatten()
make_sigma_matrix(matrix22, sta_phi_flat, sta_phi_flat)
np.fill_diagonal(matrix22, np.diag(matrix22) + sta_sig_extra ** 2)
cov_WD_WD_inv = np.linalg.pinv(matrix22)
#
# Hold on to some things we'll need later
#
self.T_D[imtstr] = T_D
self.cov_WD_WD_inv[imtstr] = cov_WD_WD_inv
#
# Compute the bias mu_H_yD and cov_HH_yD pieces
#
cov_HH_yD = np.linalg.pinv(
np.linalg.multi_dot([T_D.T, cov_WD_WD_inv, T_D])
+ np.linalg.pinv(corr_HH_D)
)
mu_H_yD = np.linalg.multi_dot(
[cov_HH_yD, T_D.T, cov_WD_WD_inv, sta_resids_dl]
)
if self.do_bias and (
not isinstance(self.rupture_obj, PointRupture)
or self.rx.mag <= self.bias_max_mag
):
self.mu_H_yD[imtstr] = mu_H_yD
self.cov_HH_yD[imtstr] = cov_HH_yD
else:
self.mu_H_yD[imtstr] = np.zeros_like(mu_H_yD)
self.cov_HH_yD[imtstr] = np.zeros_like(cov_HH_yD)
#
# Get the nominal bias and variance
#
delta_B_yD = T_D.dot(mu_H_yD)
self.nominal_bias[imtstr] = np.mean(delta_B_yD)
sig_B_yD = np.sqrt(np.diag(np.linalg.multi_dot([T_D, cov_HH_yD, T_D.T])))
nom_variance = np.mean(sig_B_yD)
bias_time = time.time() - time1
#
# Write the nominal values of the bias and its stddev to log
#
self.logger.debug(
"%s: nom bias %f nom stddev %f; %d stations (time=%f sec)"
% (
imtstr,
self.nominal_bias[imtstr],
np.sqrt(nom_variance),
nsta,
bias_time,
)
)
def _computeDirectivityPredictionLocations(self):
"""
Figure out if we need the directivity factors, and if so, pre-calculate
them. These will be used later in _computeMVN.
"""
if self.do_directivity is True:
self.logger.info("Directivity for prediction locations...")
time1 = time.time()
# Precompute directivity at all periods
dir_out = Rowshandel2013(
self.rupture_obj._origin,
self.rupture_obj,
self.lats.reshape((1, -1)),
self.lons.reshape((1, -1)),
np.zeros_like((len(self.lats), 1)),
dx=1.0,
T=Rowshandel2013.getPeriods(),
a_weight=0.5,
mtype=1,
)
self.dir_results.append((dir_out, self.dx_out))
# Precompute directivity for the attenuation curves
dir_out = Rowshandel2013(
self.rupture_obj._origin,
self.rupture_obj,
self.atten_coords["lats"].reshape((1, -1)),
self.atten_coords["lons"].reshape((1, -1)),
np.zeros_like((len(self.atten_coords["lats"]), 1)),
dx=1.0,
T=Rowshandel2013.getPeriods(),
a_weight=0.5,
mtype=1,
)
self.dir_results.append((dir_out, self.atten_dx))
directivity_time = time.time() - time1
self.logger.debug(
f"Directivity prediction evaluation time: {directivity_time:f} sec"
)
else:
self.directivity = None
def _computeMVN(self, imtstr):
"""
Do the MVN computations
"""
self.logger.debug(f"computeMVN: doing IMT {imtstr}")
time1 = time.time()
#
# Get the index of the (pesudo-) period of the output IMT
#
outperiod_ix = self.imt_per_ix[imtstr]
#
# Get the predictions at the output points
#
oqimt = imt.from_string(imtstr)
if imtstr != "MMI":
gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)
else:
gmpe = self.ipe
pout_mean, pout_sd = self._gmas(
gmpe, self.sx_out, self.dx_out, oqimt, self.apply_gafs
)
if self.use_simulations:
if imtstr == "MMI":
pout_mean = self.gmice.getPreferredMI(
self.sim_df, dists=self.dx_out.rrup, mag=self.rx.mag
)
else:
pout_mean = self.sim_df[imtstr]
#
# While we have the gmpe for this IMT, we should make
# the attenuation curves
#
x_mean, x_sd = self._gmas(
gmpe, self.atten_sx_rock, self.atten_dx, oqimt, self.apply_gafs
)
self.atten_rock_mean[imtstr] = x_mean
self.atten_rock_sd[imtstr] = x_sd[0]
x_mean, x_sd = self._gmas(
gmpe, self.atten_sx_soil, self.atten_dx, oqimt, self.apply_gafs
)
self.atten_soil_mean[imtstr] = x_mean
self.atten_soil_sd[imtstr] = x_sd[0]
#
# Get an array of the within-event standard deviations for the
# output IMT at the output points
#
if imtstr != "MMI":
total_only = self.gmpe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter"]
else:
total_only = self.ipe_total_sd_only
tau_guess = SM_CONSTS["default_stddev_inter_mmi"]
if total_only:
self.tsd[imtstr] = tau_guess * pout_sd[0]
self.psd[imtstr] = np.sqrt(pout_sd[0] ** 2 - self.tsd[imtstr] ** 2)
self.psd_raw[imtstr] = np.sqrt(pout_sd[1] ** 2 - self.tsd[imtstr] ** 2)
else:
self.tsd[imtstr] = pout_sd[1]
self.psd[imtstr] = pout_sd[2]
self.psd_raw[imtstr] = pout_sd[5]
#
# If there are no data, just use the unbiased prediction
# and the stddev
#
nsta = np.size(self.sta_lons_rad[imtstr])
if nsta == 0:
self.outgrid[imtstr] = pout_mean
self.outsd[imtstr] = pout_sd[0]
self.outphi[imtstr] = self.psd[imtstr]
self.outtau[imtstr] = self.tsd[imtstr]
return
pout_sd2_phi = np.power(self.psd[imtstr], 2.0)
sta_per_ix = self.sta_per_ix[imtstr]
sta_phi = self.sta_phi[imtstr]
sta_lons_rad = self.sta_lons_rad[imtstr]
sta_lats_rad = self.sta_lats_rad[imtstr]
len_output = np.size(self.tsd[imtstr])
if self.no_native_flag[imtstr] is False:
T_Y0 = np.zeros((len_output, self.len_types[imtstr]))
T_Y0[:, np.where(outperiod_ix == self.imt_types[imtstr])[0][0]] = self.tsd[
imtstr
].ravel()
else:
T_Y0 = np.zeros((len_output, self.len_types[imtstr] + 1))
T_Y0[:, self.imt_Y_ind[imtstr]] = self.tsd[imtstr].ravel()
T_D = self.T_D[imtstr]
cov_WD_WD_inv = self.cov_WD_WD_inv[imtstr]
#
# Now do the MVN itself...
#
dtime = mtime = ddtime = ctime = stime = atime = 0
C = np.empty_like(T_Y0[0 : self.smnx, :])
C_tmp1 = np.empty_like(C)
C_tmp2 = np.empty_like(C)
s_tmp1 = np.empty((self.smnx), dtype=np.float64).reshape((-1, 1))
s_tmp2 = np.empty((self.smnx), dtype=np.float64).reshape((-1, 1))
s_tmp3 = np.empty((self.smnx), dtype=np.float64)
ampgrid = np.zeros_like(pout_mean)
cov_WY_WY_WD = np.zeros_like(pout_mean)
sdgrid_tau = np.zeros_like(pout_mean)
# Stuff that doesn't change within the loop:
lons_out_rad = self.lons_out_rad
lats_out_rad = self.lats_out_rad
d12_cols = self.smnx
ones = np.ones(d12_cols, dtype=np.long).reshape((-1, 1))
t1_12 = sta_per_ix.reshape((1, -1)) * ones
t2_12 = np.full((d12_cols, nsta), outperiod_ix, dtype=np.long)
# sdsta is the standard deviation of the stations
sdsta_phi = sta_phi.flatten()
matrix12_phi = np.empty(t2_12.shape, dtype=np.double)
rcmatrix_phi = np.empty(t2_12.shape, dtype=np.double)
for iy in range(self.smny):
ss = iy * self.smnx
se = (iy + 1) * self.smnx
time4 = time.time()
geodetic_distance_fast(
sta_lons_rad,
sta_lats_rad,
lons_out_rad[ss:se],
lats_out_rad[ss:se],
matrix12_phi,
)
ddtime += time.time() - time4
time4 = time.time()
self.ccf.getCorrelation(t1_12, t2_12, matrix12_phi)
ctime += time.time() - time4
time4 = time.time()
# sdarr_phi is the standard deviation of the within-event
# residuals at the output sites
sdarr_phi = self.psd[imtstr][iy, :]
make_sigma_matrix(matrix12_phi, sdsta_phi, sdarr_phi)
stime += time.time() - time4
time4 = time.time()
#
# Sigma12 * Sigma22^-1 is known as the 'regression
# coefficient' matrix (rcmatrix)
#
np.dot(matrix12_phi, cov_WD_WD_inv, out=rcmatrix_phi)
dtime += time.time() - time4
time4 = time.time()
#
# We only want the diagonal elements of the conditional
# covariance matrix, so there is no point in doing the
# full solution with the dot product, e.g.:
# sdgrid[ss:se] = pout_sd2[ss:se] -
# np.diag(rcmatrix.dot(sigma21))
#
# make_sd_array is a Cython function that is optimized to find
# the diagonal of the covariance matrix.
#
make_sd_array(cov_WY_WY_WD, pout_sd2_phi, iy, rcmatrix_phi, matrix12_phi)
#
# Equation B32 of Engler et al. (2021)
#
C = T_Y0[ss:se, :] - np.dot(rcmatrix_phi, T_D, out=C_tmp1)
#
# This is the MVN solution for the conditional mean
# It is an implementation of the equation just below
# equation B25 in Engler et al. (2021):
#
# mu_Y_yD = mu_Y + C mu_H_yD + cov_WY_WD cov_WD_WD^-1 zeta
#
# but we break it up for efficiency.
#
s_tmp1r = np.dot(C, self.mu_H_yD[imtstr], out=s_tmp1).reshape((-1,))
s_tmp2r = np.dot(rcmatrix_phi, self.sta_resids[imtstr], out=s_tmp2).reshape(
(-1,)
)
ampgrid[iy, :] = np.add(
np.add(pout_mean[iy, :], s_tmp1r, out=s_tmp1r), s_tmp2r, out=s_tmp2r
)
atime += time.time() - time4
time4 = time.time()
#
# We're doing this:
#
# sdgrid_tau[iy, :] = np.diag(
# C.dot(self.cov_HH_yD[imtstr].dot(C.T)))
#
# to find the between-event part of the diagonal of the conditional
# covariance. This is the second term of equation B27 of Engler
# et al. (2021). The code below is faster and uses less memory than
# actually implementing the above equation.
#
np.dot(C, self.cov_HH_yD[imtstr], C_tmp1)
sdgrid_tau[iy, :] = np.sum(
np.multiply(C_tmp1, C, out=C_tmp2), out=s_tmp3, axis=1
)
mtime += time.time() - time4
#
# This processing can result in MMI values that go beyond
# the 1 to 10 bounds of MMI, so we apply that constraint again
# here
#
if imtstr == "MMI":
ampgrid = np.clip(ampgrid, 1.0, 10.0)
#
# The conditional mean
#
self.outgrid[imtstr] = ampgrid
#
# The outputs are the conditional total stddev, the conditional
# between-event stddev (tau), and the prior within-event stddev (phi)
#
self.outsd[imtstr] = np.sqrt(
np.add(cov_WY_WY_WD, sdgrid_tau, out=cov_WY_WY_WD), out=cov_WY_WY_WD
)
# self.outphi[imtstr] = np.sqrt(cov_WY_WY_WD)
self.outphi[imtstr] = self.psd[imtstr]
self.outtau[imtstr] = np.sqrt(sdgrid_tau, out=sdgrid_tau)
self.logger.debug(f"\ttime for {imtstr} distance={ddtime:f}")
self.logger.debug(f"\ttime for {imtstr} correlation={ctime:f}")
self.logger.debug(f"\ttime for {imtstr} sigma={stime:f}")
self.logger.debug(f"\ttime for {imtstr} rcmatrix={dtime:f}")
self.logger.debug(f"\ttime for {imtstr} amp calc={atime:f}")
self.logger.debug(f"\ttime for {imtstr} sd calc={mtime:f}")
self.logger.debug(f"total time for {imtstr}={time.time() - time1:f}")
def _applyCustomMask(self):
"""Apply custom masks to IMT grid outputs."""
if self.mask_file:
mask = self._getMask(self.mask_file)
for grid in self.outgrid.values():
grid[~mask] = np.nan
def _getLandMask(self):
"""
Get the landmask for this map. Land will be False, water will
be True (because of the way masked arrays work).
"""
if "CALLED_FROM_PYTEST" in os.environ:
oceans = None
else:
oceans = shpreader.natural_earth(
category="physical", name="ocean", resolution="10m"
)
return self._getMask(oceans)
def _getMask(self, vector=None):
"""
Get a masked array for this map corresponding to the given vector
feature.
"""
if not self.do_grid:
return None
gd = GeoDict.createDictFromBox(
self.W, self.E, self.S, self.N, self.smdx, self.smdy
)
bbox = (gd.xmin, gd.ymin, gd.xmax, gd.ymax)
if vector is None:
return np.zeros((gd.ny, gd.nx), dtype=np.bool)
with fiona.open(vector) as c:
tshapes = list(c.items(bbox=bbox))
shapes = []
for tshp in tshapes:
shapes.append(shape(tshp[1]["geometry"]))
if len(shapes):
grid = Grid2D.rasterizeFromGeometry(shapes, gd, fillValue=0.0)
return grid.getData().astype(np.bool)
else:
return np.zeros((gd.ny, gd.nx), dtype=np.bool)
def _getMaskedGrids(self, bmask):
"""
For each grid in the output, generate a grid with the water areas
masked out.
"""
moutgrid = {}
if not self.do_grid:
for imtout in self.imt_out_set:
moutgrid[imtout] = self.outgrid[imtout]
return moutgrid
for imtout in self.imt_out_set:
moutgrid[imtout] = ma.masked_array(self.outgrid[imtout], mask=bmask)
return moutgrid
def _getInfo(self, moutgrid):
"""
Create an info dictionary that can be made into the info.json file.
"""
#
# Get the map grade
#
mean_rat, mygrade = _get_map_grade(
self.do_grid, self.outsd, self.psd_raw, moutgrid
)
# ---------------------------------------------------------------------
# This is the metadata for creating info.json
# ---------------------------------------------------------------------
st = "strec"
ip = "input"
ei = "event_information"
op = "output"
gm = "ground_motions"
mi = "map_information"
un = "uncertainty"
pp = "processing"
gmm = "ground_motion_modules"
ms = "miscellaneous"
sv = "shakemap_versions"
sr = "site_response"
info = self._info
info[ip] = {}
info[ip][ei] = {}
info[ip][ei]["depth"] = str(self.rx.hypo_depth)
info[ip][ei]["event_id"] = self._eventid
# look for the presence of a strec_results file and read it in
_, data_path = get_config_paths()
datadir = os.path.join(data_path, self._eventid, "current")
strecfile = os.path.join(datadir, "strec_results.json")
if os.path.isfile(strecfile):
strec_results = json.load(open(strecfile, "rt"))
info[st] = strec_results
# the following items are primarily useful for PDL
origin = self.rupture_obj._origin
info[ip][ei]["eventsource"] = origin.netid
info[ip][ei]["netid"] = origin.netid
# The netid could be a valid part of the eventsourcecode, so we have
# to check here if it ***starts with*** the netid
if origin.id.startswith(origin.netid):
eventsourcecode = origin.id.replace(origin.netid, "", 1)
else:
eventsourcecode = origin.id
info[ip][ei]["eventsourcecode"] = eventsourcecode
info[ip][ei]["id"] = origin.id
info[ip][ei]["productcode"] = origin.productcode
info[ip][ei]["productsource"] = self.config["system"]["source_network"]
info[ip][ei]["producttype"] = self.config["system"]["product_type"]
info[ip][ei]["event_ref"] = getattr(origin, "reference", None)
info[ip][ei]["fault_ref"] = self.rupture_obj.getReference()
if "df2" in self.dataframes:
info[ip][ei]["intensity_observations"] = str(np.size(self.df2.df["lon"]))
else:
info[ip][ei]["intensity_observations"] = "0"
info[ip][ei]["latitude"] = str(self.rx.hypo_lat)
info[ip][ei]["longitude"] = str(self.rx.hypo_lon)
info[ip][ei]["location"] = origin.locstring
info[ip][ei]["magnitude"] = str(self.rx.mag)
info[ip][ei]["origin_time"] = origin.time.strftime(constants.TIMEFMT)
if "df1" in self.dataframes:
info[ip][ei]["seismic_stations"] = str(np.size(self.df1.df["lon"]))
else:
info[ip][ei]["seismic_stations"] = "0"
info[ip][ei]["src_mech"] = origin.mech
if self.config["system"]["source_description"] != "":
info[ip][ei]["event_description"] = self.config["system"][
"source_description"
]
else:
info[ip][ei]["event_description"] = origin.locstring
# This AND src_mech?
# look at the origin information for indications that this
# event is a scenario
condition1 = (
hasattr(origin, "event_type") and origin.event_type.lower() == "scenario"
)
condition2 = origin.id.endswith("_se")
if condition1 or condition2:
info[ip][ei]["event_type"] = "SCENARIO"
else:
info[ip][ei]["event_type"] = "ACTUAL"
info[op] = {}
info[op][gm] = {}
for myimt in self.imt_out_set:
info[op][gm][myimt] = {}
if myimt == "MMI":
units = "intensity"
elif myimt == "PGV":
units = "cms"
else:
units = "g"
info[op][gm][myimt]["units"] = units
if myimt in self.nominal_bias:
info[op][gm][myimt]["bias"] = _string_round(self.nominal_bias[myimt], 3)
else:
info[op][gm][myimt]["bias"] = None
if myimt == "MMI":
info[op][gm][myimt]["max_grid"] = _string_round(
np.max(self.outgrid[myimt]), 3
)
info[op][gm][myimt]["max"] = _string_round(np.max(moutgrid[myimt]), 3)
else:
info[op][gm][myimt]["max_grid"] = _string_round(
np.exp(np.max(self.outgrid[myimt])), 3
)
info[op][gm][myimt]["max"] = _string_round(
np.exp(np.max(moutgrid[myimt])), 3
)
info[op][mi] = {}
info[op][mi]["grid_points"] = {}
info[op][mi]["grid_points"]["longitude"] = str(self.smnx)
info[op][mi]["grid_points"]["latitude"] = str(self.smny)
info[op][mi]["grid_points"]["units"] = ""
info[op][mi]["grid_spacing"] = {}
info[op][mi]["grid_spacing"]["longitude"] = _string_round(self.smdx, 7)
info[op][mi]["grid_spacing"]["latitude"] = _string_round(self.smdy, 7)
info[op][mi]["grid_spacing"]["units"] = "degrees"
info[op][mi]["grid_span"] = {}
if self.E <= 0 and self.W >= 0:
info[op][mi]["grid_span"]["longitude"] = _string_round(
self.E + 360.0 - self.W, 3
)
else:
info[op][mi]["grid_span"]["longitude"] = _string_round(self.E - self.W, 3)
info[op][mi]["grid_span"]["latitude"] = _string_round(self.N - self.S, 3)
info[op][mi]["grid_span"]["units"] = "degrees"
info[op][mi]["min"] = {}
info[op][mi]["max"] = {}
min_long = self.W
max_long = self.E
if self.rx.hypo_lon < 0:
if min_long > 0: # Crossing the 180 from the negative side
min_long = min_long - 360
else:
if max_long < 0: # Crossing the 180 from the positive side
max_long = max_long + 360
info[op][mi]["min"]["longitude"] = _string_round(min_long, 3)
info[op][mi]["max"]["longitude"] = _string_round(max_long, 3)
info[op][mi]["min"]["latitude"] = _string_round(self.S, 3)
info[op][mi]["max"]["latitude"] = _string_round(self.N, 3)
info[op][mi]["min"]["units"] = "degrees"
info[op][mi]["max"]["units"] = "degrees"
info[op][un] = {}
info[op][un]["grade"] = mygrade
info[op][un]["mean_uncertainty_ratio"] = _string_round(mean_rat, 3)
if "df2" in self.dataframes:
info[op][un]["total_flagged_mi"] = str(
np.sum(self.df2.df["MMI_outliers"] | np.isnan(self.df2.df["MMI"]))
)
else:
info[op][un]["total_flagged_mi"] = "0"
if "df1" in self.dataframes:
all_flagged = np.full(self.df1.df["lon"].shape, False, dtype=np.bool)
for imtstr in self.df1.imts:
if "MMI" in imtstr:
continue
all_flagged |= self.df1.df[imtstr + "_outliers"] | np.isnan(
self.df1.df[imtstr]
)
all_flagged |= self.df1.df["flagged"]
info[op][un]["total_flagged_pgm"] = str(np.sum(all_flagged))
else:
info[op][un]["total_flagged_pgm"] = "0"
info[pp] = {}
info[pp][gmm] = {}
info[pp][gmm]["gmpe"] = {}
info[pp][gmm]["gmpe"]["module"] = str(self.config["modeling"]["gmpe"])
info[pp][gmm]["gmpe"]["reference"] = ""
info[pp][gmm]["ipe"] = {}
info[pp][gmm]["ipe"]["module"] = str(
self.config["ipe_modules"][self.config["modeling"]["ipe"]][0]
)
info[pp][gmm]["ipe"]["reference"] = ""
info[pp][gmm]["gmice"] = {}
info[pp][gmm]["gmice"]["module"] = str(
self.config["gmice_modules"][self.config["modeling"]["gmice"]][0]
)
info[pp][gmm]["gmice"]["reference"] = ""
info[pp][gmm]["ccf"] = {}
info[pp][gmm]["ccf"]["module"] = str(
self.config["ccf_modules"][self.config["modeling"]["ccf"]][0]
)
info[pp][gmm]["ccf"]["reference"] = ""
info[pp][gmm]["basin_correction"] = {}
info[pp][gmm]["basin_correction"]["module"] = "None"
info[pp][gmm]["basin_correction"]["reference"] = ""
info[pp][gmm]["directivity"] = {}
info[pp][gmm]["directivity"]["module"] = "None"
info[pp][gmm]["directivity"]["reference"] = ""
info[pp][ms] = {}
info[pp][ms]["bias_max_dsigma"] = str(self.bias_max_dsigma)
info[pp][ms]["bias_max_mag"] = str(self.bias_max_mag)
info[pp][ms]["bias_max_range"] = str(self.bias_max_range)
info[pp][ms]["median_dist"] = "True"
info[pp][ms]["do_outliers"] = self.do_outliers
info[pp][ms]["outlier_deviation_level"] = str(self.outlier_deviation_level)
info[pp][ms]["outlier_max_mag"] = str(self.outlier_max_mag)
info[pp][sv] = {}
info[pp][sv]["shakemap_revision"] = get_versions()["version"]
info[pp][sv]["shakemap_revision_id"] = get_versions()["full-revisionid"]
info[pp][sv]["process_time"] = strftime(constants.ALT_TIMEFMT, gmtime())
info[pp][sv]["map_version"] = self.ic.getVersionHistory()["history"][-1][2]
info[pp][sv]["map_comment"] = self.ic.getVersionHistory()["history"][-1][3]
info[pp][sv]["map_data_history"] = self.ic.getVersionHistory()["history"]
info[pp][sv]["map_status"] = self.config["system"]["map_status"]
info[pp][sr] = {}
info[pp][sr]["vs30default"] = str(self.vs30default)
info[pp][sr]["site_correction"] = "GMPE native"
return info
def _fillStationJSON(self):
"""
Get the station JSON dictionary and then add a bunch of stuff to it.
"""
if not hasattr(self, "stations") or self.stations is None:
return {"eventid": self._eventid, "features": []}
sjdict = {}
# ---------------------------------------------------------------------
# Compute a bias for all the output IMTs in the data frames
# ---------------------------------------------------------------------
for ndf in self.dataframes:
sdf = getattr(self, ndf).df
for myimt in self.imt_out_set:
if type(self.mu_H_yD[myimt]) is float:
mybias = sdf[myimt + "_pred_tau"] * self.mu_H_yD[myimt]
mybias_sig = np.sqrt(
sdf[myimt + "_pred_tau"] ** 2 * self.cov_HH_yD[myimt]
)
else:
mybias = sdf[myimt + "_pred_tau"] * self.mu_H_yD[myimt][0]
mybias_sig = np.sqrt(
sdf[myimt + "_pred_tau"] ** 2 * self.cov_HH_yD[myimt][0, 0]
)
sdf[myimt + "_bias"] = mybias.flatten()
sdf[myimt + "_bias_sigma"] = mybias_sig.flatten()
# ---------------------------------------------------------------------
# Add the station data. The stationlist object has the original
# data and produces a GeoJSON object (a dictionary, really), but
# we need to add peak values and flagging that has been done here.
# ---------------------------------------------------------------------
#
# First make a dictionary of distances
#
dist_dict = {"df1": {}, "df2": {}}
for ndf in self.dataframes:
dx = getattr(self, ndf).dx
for dm in get_distance_measures():
dm_arr = getattr(dx, dm, None)
if dm_arr is not None:
dist_dict[ndf][dm] = dm_arr
else:
continue
if dm in ("rrup", "rjb"):
dm_var = getattr(dx, dm + "_var", None)
if dm_var is not None:
dist_dict[ndf][dm + "_var"] = dm_var
else:
dist_dict[ndf][dm + "_var"] = np.zeros_like(dm_arr)
#
# Get the index for each station ID
#
sjdict = self.stations.getGeoJson()
sta_ix = {"df1": {}, "df2": {}}
for ndf in self.dataframes:
sdf = getattr(self, ndf).df
sta_ix[ndf] = dict(zip(sdf["id"], range(len(sdf["id"]))))
#
# Now go through the GeoJSON and add various properties and
# amps from the df_dict dictionaries
#
sjdict_copy = copy.copy(sjdict["features"])
for station in sjdict_copy:
if station["id"] in sta_ix["df1"]:
ndf = "df1"
station["properties"]["station_type"] = "seismic"
elif station["id"] in sta_ix["df2"]:
ndf = "df2"
station["properties"]["station_type"] = "macroseismic"
else:
# We're probably using --no_seismic or --no_macroseismic
if self.no_seismic or self.no_macroseismic:
sjdict["features"].remove(station)
continue
else:
raise ValueError(f"Unknown station {station['id']} in stationlist")
dfx = getattr(self, ndf)
sdf = dfx.df
six = sta_ix[ndf][station["id"]]
#
# Set the 'intensity', 'pga', and 'pga' peak properties
#
if (
"MMI" in sdf
and not sdf["MMI_outliers"][six]
and not np.isnan(sdf["MMI"][six])
):
station["properties"]["intensity"] = float(f"{sdf['MMI'][six]:.1f}")
station["properties"]["intensity_stddev"] = sdf["MMI_sd"][six]
if "MMI_nresp" in sdf:
station["properties"]["nresp"] = int(sdf["MMI_nresp"][six])
else:
station["properties"]["nresp"] = "null"
else:
station["properties"]["intensity"] = "null"
station["properties"]["intensity_stddev"] = "null"
station["properties"]["nresp"] = "null"
if (
"PGA" in sdf
and not sdf["PGA_outliers"][six]
and not np.isnan(sdf["PGA"][six])
and (ndf != "df1" or not sdf["flagged"][six])
):
station["properties"]["pga"] = _round_float(
np.exp(sdf["PGA"][six]) * 100, 4
)
else:
station["properties"]["pga"] = "null"
if (
"PGV" in sdf
and not sdf["PGV_outliers"][six]
and not np.isnan(sdf["PGV"][six])
and (ndf != "df1" or not sdf["flagged"][six])
):
station["properties"]["pgv"] = _round_float(np.exp(sdf["PGV"][six]), 4)
else:
station["properties"]["pgv"] = "null"
#
# Add vs30
#
station["properties"]["vs30"] = _round_float(dfx.sx.vs30[six], 2)
#
# Add the predictions so we can plot residuals
#
station["properties"]["predictions"] = []
for key in sdf.keys():
if not key.endswith("_pred"):
continue
myamp = sdf[key][six]
myamp_rock = sdf[key + "_rock"][six]
myamp_soil = sdf[key + "_soil"][six]
tau_str = "ln_tau"
phi_str = "ln_phi"
sigma_str = "ln_sigma"
sigma_str_rock = "ln_sigma_rock"
sigma_str_soil = "ln_sigma_soil"
bias_str = "ln_bias"
bias_sigma_str = "ln_bias_sigma"
if key.startswith("PGV"):
value = np.exp(myamp)
value_rock = np.exp(myamp_rock)
value_soil = np.exp(myamp_soil)
units = "cm/s"
elif key.startswith("MMI"):
value = myamp
value_rock = myamp_rock
value_soil = myamp_soil
units = "intensity"
tau_str = "tau"
phi_str = "phi"
sigma_str = "sigma"
sigma_str_rock = "sigma_rock"
sigma_str_soil = "sigma_soil"
bias_str = "bias"
bias_sigma_str = "bias_sigma"
else:
value = np.exp(myamp) * 100
value_rock = np.exp(myamp_rock) * 100
value_soil = np.exp(myamp_soil) * 100
units = "%g"
if self.gmpe_total_sd_only:
mytau = 0
else:
mytau = sdf[key + "_tau"][six]
myphi = sdf[key + "_phi"][six]
mysigma = np.sqrt(mytau ** 2 + myphi ** 2)
mysigma_rock = sdf[key + "_sigma_rock"][six]
mysigma_soil = sdf[key + "_sigma_soil"][six]
imt_name = key.lower().replace("_pred", "")
if imt_name.upper() in self.imt_out_set:
mybias = sdf[imt_name.upper() + "_bias"][six]
mybias_sigma = sdf[imt_name.upper() + "_bias_sigma"][six]
else:
mybias = "null"
mybias_sigma = "null"
station["properties"]["predictions"].append(
{
"name": imt_name,
"value": _round_float(value, 4),
"value_rock": _round_float(value_rock, 4),
"value_soil": _round_float(value_soil, 4),
"units": units,
tau_str: _round_float(mytau, 4),
phi_str: _round_float(myphi, 4),
sigma_str: _round_float(mysigma, 4),
sigma_str_rock: _round_float(mysigma_rock, 4),
sigma_str_soil: _round_float(mysigma_soil, 4),
bias_str: _round_float(mybias, 4),
bias_sigma_str: _round_float(mybias_sigma, 4),
}
)
#
# For df1 stations, add the MMIs comverted from PGM
#
if ndf == "df1":
station["properties"]["mmi_from_pgm"] = []
for myimt in getattr(self, ndf).imts:
if myimt == "MMI":
continue
dimtstr = "derived_MMI_from_" + myimt
if dimtstr not in sdf:
continue
imt_name = myimt.lower()
myamp = sdf[dimtstr][six]
mysd = sdf[dimtstr + "_sd"][six]
if np.isnan(myamp):
myamp = "null"
mysd = "null"
flag = "0"
else:
if sdf[myimt + "_outliers"][six] == 1:
flag = "Outlier"
else:
flag = "0"
station["properties"]["mmi_from_pgm"].append(
{
"name": imt_name,
"value": _round_float(myamp, 2),
"sigma": _round_float(mysd, 2),
"flag": flag,
}
)
#
# For df2 stations, add the PGMs converted from MMI
#
if ndf == "df2":
station["properties"]["pgm_from_mmi"] = []
for myimt in getattr(self, ndf).imts:
if myimt == "MMI":
continue
imt_name = myimt.lower()
myamp = sdf[myimt][six]
mysd = sdf[myimt + "_sd"][six]
if myimt == "PGV":
value = np.exp(myamp)
units = "cm/s"
else:
value = np.exp(myamp) * 100
units = "%g"
if np.isnan(value):
value = "null"
mysd = "null"
flag = "0"
else:
if sdf[myimt + "_outliers"][six] == 1:
flag = "Outlier"
else:
flag = "0"
station["properties"]["pgm_from_mmi"].append(
{
"name": imt_name,
"value": _round_float(value, 4),
"units": units,
"ln_sigma": _round_float(mysd, 4),
"flag": flag,
}
)
#
# Set the generic distance property (this is rrup)
#
station["properties"]["distance"] = _round_float(sdf["rrup"][six], 3)
station["properties"]["distance_stddev"] = _round_float(
np.sqrt(sdf["rrup_var"][six]), 3
)
#
# Set the specific distances properties
#
station["properties"]["distances"] = {}
for dm, dm_arr in dist_dict[ndf].items():
station["properties"]["distances"][dm] = _round_float(dm_arr[six], 3)
#
# Set the outlier flags
#
mflag = "0"
if ndf == "df1" and sdf["flagged"][six]:
mflag = "ManuallyFlagged"
for channel in station["properties"]["channels"]:
for amp in channel["amplitudes"]:
if amp["flag"] != "0":
amp["flag"] += "," + mflag
else:
amp["flag"] = mflag
Name = amp["name"].upper()
if sdf[Name + "_outliers"][six]:
if amp["flag"] == "0":
amp["flag"] = "Outlier"
else:
amp["flag"] += ",Outlier"
sjdict["metadata"] = {"eventid": self._eventid}
return sjdict
def _storeGriddedData(self, oc):
"""
Store gridded data in the output container.
"""
metadata = {}
min_long = self.W
max_long = self.E
if self.rx.hypo_lon < 0:
if min_long > 0: # Crossing the 180 from the negative side
min_long = min_long - 360
else:
if max_long < 0: # Crossing the 180 from the positive side
max_long = max_long + 360
metadata["xmin"] = min_long
metadata["xmax"] = max_long
metadata["ymin"] = self.S
metadata["ymax"] = self.N
metadata["nx"] = self.smnx
metadata["ny"] = self.smny
metadata["dx"] = self.smdx
metadata["dy"] = self.smdy
#
# Put the Vs30 grid in the output container
#
_, units, digits = _get_layer_info("vs30")
metadata["units"] = units
metadata["digits"] = digits
oc.setArray([], "vs30", self.sx_out.vs30, metadata=metadata)
#
# Now do the distance grids
#
metadata["units"] = "km"
metadata["digits"] = 4
for dm in get_distance_measures():
dm_arr = getattr(self.dx_out, dm, None)
if dm_arr is None:
continue
oc.setArray(["distances"], dm, dm_arr, metadata=metadata)
if dm in ("rrup", "rjb"):
dm_var = getattr(self.dx_out, dm + "_var", None)
if dm_var is None:
dm_var = np.zeros_like(dm_arr)
dm_std = np.sqrt(dm_var)
oc.setArray(["distances"], dm + "_std", dm_std, metadata=metadata)
#
# Output the data and uncertainty grids
#
component = self.config["interp"]["component"]
std_metadata = copy.copy(metadata)
for key, value in self.outgrid.items():
# set the data grid
_, units, digits = _get_layer_info(key)
metadata["units"] = units
metadata["digits"] = digits
# set the mean and uncertainty grids
std_layername, units, digits = _get_layer_info(key + "_sd")
std_metadata["units"] = units
std_metadata["digits"] = digits
oc.setIMTGrids(
key,
component,
value,
metadata,
self.outsd[key],
std_metadata,
self.outphi[key],
self.outtau[key],
)
#
# Directivity
#
del metadata["units"]
del metadata["digits"]
if self.do_directivity is True:
for k, v in self.dir_output.items():
imtstr, _, _ = _get_layer_info(k)
oc.setArray(["directivity"], imtstr, v, metadata=metadata)
def _storePointData(self, oc):
"""
Store point data in the output container.
"""
#
# Store the Vs30
#
vs30_metadata = {"units": "m/s", "digits": 4}
oc.setArray([], "vs30", self.sx_out.vs30.flatten(), metadata=vs30_metadata)
#
# Store the distances
#
distance_metadata = {"units": "km", "digits": 4}
for dm in get_distance_measures():
dm_arr = getattr(self.dx_out, dm, None)
if dm_arr is None:
continue
oc.setArray(["distances"], dm, dm_arr.flatten(), metadata=distance_metadata)
if dm in ("rrup", "rjb"):
dm_var = getattr(self.dx_out, dm + "_var", None)
if dm_var is None:
dm_var = np.zeros_like(dm_arr)
oc.setArray(
["distances"],
dm + "_std",
np.sqrt(dm_var).flatten(),
metadata=distance_metadata,
)
#
# Store the IMTs
#
ascii_ids = np.array(
[np.char.encode(x, encoding="ascii") for x in self.idents]
).flatten()
component = self.config["interp"]["component"]
for key, value in self.outgrid.items():
# set the data grid
_, units, digits = _get_layer_info(key)
mean_metadata = {"units": units, "digits": digits}
# set the uncertainty grid
std_layername, units, digits = _get_layer_info(key + "_sd")
std_metadata = {"units": units, "digits": digits}
oc.setIMTArrays(
key,
component,
self.sx_out.lons.flatten(),
self.sx_out.lats.flatten(),
ascii_ids,
value.flatten(),
mean_metadata,
self.outsd[key].flatten(),
std_metadata,
self.outphi[key].flatten(),
self.outtau[key].flatten(),
)
def _storeAttenuationData(self, oc):
"""
Output arrays of rock and soil attenuation curves
"""
for dist_type in ["repi", "rhypo", "rrup", "rjb"]:
oc.setArray(
["attenuation", "distances"],
dist_type,
getattr(self.atten_dx, dist_type, None),
)
imtstrs = self.atten_rock_mean.keys()
for imtstr in imtstrs:
oc.setArray(
["attenuation", "rock", imtstr], "mean", self.atten_rock_mean[imtstr]
)
oc.setArray(
["attenuation", "soil", imtstr], "mean", self.atten_soil_mean[imtstr]
)
oc.setArray(
["attenuation", "rock", imtstr], "std", self.atten_rock_sd[imtstr]
)
oc.setArray(
["attenuation", "soil", imtstr], "std", self.atten_soil_sd[imtstr]
)
return
#
# Helper function to call get_mean_and_stddevs for the
# appropriate object given the IMT and describe the
# MultiGMPE structure.
#
def _gmas(self, gmpe, sx, dx, oqimt, apply_gafs):
"""
This is a helper function to call get_mean_and_stddevs for the
appropriate object given the IMT.
Args:
gmpe:
A GMPE instance.
sx:
Sites context.
dx:
Distance context.
oqimt:
List of OpenQuake IMTs.
apply_gafs (boolean):
Whether or not to apply the generic
amplification factors to the GMPE output.
Returns:
tuple: Tuple of two items:
- Numpy array of means,
- List of numpy array of standard deviations corresponding to
therequested stddev_types.
"""
if "MMI" in oqimt:
pe = self.ipe
sd_types = self.ipe_stddev_types
if not self.use_simulations:
if not hasattr(self, "_info"):
self._info = {"multigmpe": {}}
else:
self._info = {}
else:
pe = gmpe
sd_types = self.gmpe_stddev_types
if not self.use_simulations:
# --------------------------------------------------------------------
# Describe the MultiGMPE
# --------------------------------------------------------------------
if not hasattr(self, "_info"):
self._info = {"multigmpe": {}}
self._info["multigmpe"][str(oqimt)] = gmpe.__describe__()
else:
self._info = {}
mean, stddevs = pe.get_mean_and_stddevs(
copy.deepcopy(sx), self.rx, copy.deepcopy(dx), oqimt, sd_types
)
# Include generic amp factors?
if apply_gafs:
gafs = get_generic_amp_factors(sx, str(oqimt))
if gafs is not None:
mean += gafs
# Does directivity apply to this imt?
row_pers = Rowshandel2013.getPeriods()
if oqimt.string == "PGA":
imt_ok = False
elif oqimt.string == "PGV" or oqimt.string == "MMI":
tper = 1.0
imt_ok = True
elif "SA" in oqimt.string:
tper = oqimt.period
min_per = np.min(row_pers)
max_per = np.max(row_pers)
if (tper >= min_per) and (tper <= max_per):
imt_ok = True
else:
imt_ok = False
else:
imt_ok = False
# Did we calculate directivity?
calc_dir = self.do_directivity
if calc_dir and imt_ok:
# Use distance context to figure out which directivity result
# we need to use.
all_fd = None
for dirdf, tmpdx in self.dir_results:
if dx == tmpdx:
all_fd = dirdf.getFd()
break
if all_fd is None:
raise RuntimeError(
"Failed to detect dataframe for directivity calculation."
)
# Does oqimt match any of those periods?
if tper in row_pers:
fd = all_fd[row_pers.index(tper)]
else:
# Log(period) interpolation.
apers = np.array(row_pers)
per_below = np.max(apers[apers < tper])
per_above = np.min(apers[apers > tper])
fd_below = all_fd[row_pers.index(per_below)]
fd_above = all_fd[row_pers.index(per_above)]
x1 = np.log(per_below)
x2 = np.log(per_above)
fd = fd_below + (np.log(tper) - x1) * (fd_above - fd_below) / (x2 - x1)
# Reshape to match the mean
fd = fd.reshape(mean.shape)
# Store the interpolated grid
imtstr = str(oqimt)
self.dir_output[imtstr] = fd
if oqimt.string == "MMI":
mean *= np.exp(fd)
else:
mean += fd
return mean, stddevs
def _adjustResolution(self):
"""
This is a helper function to adjust the resolution to be under
the maximum value specified in the config.
"""
# We want to only use resolutions that are multiples of 1 minute or
# an integer division of 1 minute.
one_minute = 1 / 60
multiples = np.arange(1, 11)
divisions = 1 / multiples
factors = np.sort(np.unique(np.concatenate((divisions, multiples))))
ok_res = one_minute * factors
latspan = self.N - self.S
# Deal with possible 180 longitude disontinuity
if self.E > self.W:
lonspan = self.E - self.W
else:
xmax = self.E + 360
lonspan = xmax - self.W
nx = np.floor(lonspan / self.smdx) + 1
ny = np.floor(latspan / self.smdy) + 1
ngrid = nx * ny
nmax = self.nmax
if ngrid > nmax:
self.logger.info(
"Extent and resolution of shakemap results in "
"too many grid points. Adjusting resolution..."
)
self.logger.info(f"Longitude span: {lonspan:f}")
self.logger.info(f"Latitude span: {latspan:f}")
self.logger.info(f"Current dx: {self.smdx:f}")
self.logger.info(f"Current dy: {self.smdy:f}")
self.logger.info("Current number of grid points: %i" % ngrid)
self.logger.info("Max grid points allowed: %i" % nmax)
target_res = (
-(latspan + lonspan)
- np.sqrt(
latspan ** 2 + lonspan ** 2 + 2 * latspan * lonspan * (2 * nmax - 1)
)
) / (2 * (1 - nmax))
if np.any(ok_res > target_res):
sel_res = np.min(ok_res[ok_res > target_res])
else:
sel_res = np.max(ok_res)
self.smdx = sel_res
self.smdy = sel_res
self.logger.info(f"Updated dx: {self.smdx:f}")
self.logger.info(f"Updatd dy: {self.smdy:f}")
nx = np.floor(lonspan / self.smdx) + 1
ny = np.floor(latspan / self.smdy) + 1
self.logger.info("Updated number of grid points: %i" % (nx * ny))
def _round_float(val, digits):
if ma.is_masked(val) or val == "--" or val == "null" or np.isnan(val):
return None
return float(("%." + str(digits) + "f") % val)
def _string_round(val, digits):
if ma.is_masked(val) or val == "--" or val == "null" or np.isnan(val):
return None
return str(_round_float(val, digits))
def _get_period_arrays(*args):
"""
Return 1) a sorted array of the periods represented by the IMT list(s)
in the input, and 2) a dictionary of the IMTs and their indices.
Args:
*args (list): One or more lists of IMTs.
Returns:
array, dict: Numpy array of the (sorted) periods represented by the
IMTs in the input list(s), and a dictionary of the IMTs and their
indices into the period array.
"""
imt_per = set()
imt_per_ix = {}
for imt_list in args:
if imt_list is None:
continue
for imtstr in imt_list:
if imtstr == "PGA":
period = 0.01
elif imtstr in ("PGV", "MMI"):
period = 1.0
else:
period = _get_period_from_imt(imtstr)
imt_per.add(period)
imt_per_ix[imtstr] = period
imt_per = sorted(imt_per)
for imtstr, period in imt_per_ix.items():
imt_per_ix[imtstr] = imt_per.index(period)
return np.array(imt_per), imt_per_ix
def _get_period_from_imt(imtstr):
"""
Return a float representing the period of the SA IMT in the input.
Args:
imtstr (str): A string representing an SA IMT.
Returns:
float: The period of the SA IMT as a float.
"""
return float(imtstr.replace("SA(", "").replace(")", ""))
def _get_nearest_imts(imtstr, imtset, saset):
"""
Return the input IMT, or it's closest surrogarte (or bracket) found
in imtset.
Args:
imtstr (str): An (OQ-style) IMT string.
imtset (list): A list of IMTs to search for imtstr or its closest
surrogate (or bracket).
saset (list): The SA IMTs found in imtset.
Returns:
tuple: The IMT, it's closest surrogate, or a bracket of SAs with
periods on either side of the IMT's period, from the IMTs in intset.
"""
if imtstr in imtset:
return (imtstr,)
#
# If we're here, then we know that IMT isn't in the inputs. Try
# some alternatives.
#
if imtstr == "PGA":
#
# Use the highest frequency in the inputs
#
if len(saset):
return (sorted(saset, key=_get_period_from_imt)[0],)
else:
return ()
elif imtstr == "PGV":
#
# PGV has no surrogate
#
return ()
elif imtstr == "MMI":
#
# MMI has no surrogate
#
return ()
elif imtstr.startswith("SA("):
#
# We know the actual IMT isn't here, so get the bracket
#
return _get_sa_bracket(imtstr, saset)
else:
raise ValueError(f"Unknown IMT {imtstr} in get_imt_bracket")
def _get_sa_bracket(myimt, saset):
"""
For a given SA IMT, look through the input SAs and return a tuple of
a) a pair of IMT strings representing the periods bracketing the given
period; or b) the single IMT representing the first or last period in
the input list if the given period is off the end of the list.
Args:
myper (float): The period to search for in the input lists.
saset (list): A list of SA IMTs.
Returns:
tuple: One or two strings representing the IMTs closest to or
bracketing the input IMT.
"""
if not len(saset):
return ()
#
# Stick the target IMT into a copy of the list of SAs, then sort
# the list by period.
#
ss = saset.copy()
ss.append(myimt)
tmplist = sorted(ss, key=_get_period_from_imt)
nimt = len(tmplist)
#
# Get the index of the target IMT in the sorted list
#
myix = tmplist.index(myimt)
#
# If the target IMT is off the end of the list, return the
# appropriate endpoint; else return the pair of IMTs that
# bracket the target.
#
if myix == 0:
return (tmplist[1],)
elif myix == nimt - 1:
return (tmplist[-2],)
else:
return (tmplist[myix - 1], tmplist[myix + 1])
def _get_imt_lists(df):
"""
Given a data frame, return a list of lists of valid IMTS for
each station in the dataframe; also return a list of the valid
SA IMTs for each station.
Args:
df (DataFrame): A DataFrame.
Returns:
list, list: Two lists of lists: each list contains lists
corresponding to the stations in the data frame: the first
list contains all of the valid IMTs for that station, the
second list contains just the valid SA IMTs for the station.
"""
imtlist = []
salist = []
nlist = np.size(df.df["lon"])
for ix in range(nlist):
valid_imts = []
sa_imts = []
if "flagged" not in df.df or not df.df["flagged"][ix]:
for this_imt in df.imts:
if (
not np.isnan(df.df[this_imt + "_residual"][ix])
and not df.df[this_imt + "_outliers"][ix]
):
valid_imts.append(this_imt)
if this_imt.startswith("SA("):
sa_imts.append(this_imt)
imtlist.append(valid_imts)
salist.append(sa_imts)
return imtlist, salist
def _get_map_grade(do_grid, outsd, psd, moutgrid):
"""
Computes a 'grade' for the map. Essentially looks at the ratio of
the computed PGA uncertainty to the predicted PGA uncertainty for
the area inside the MMI 6 contour. If the maximum MMI is less than
6, or the map is not a grid, the grade and mean ratio are set to '--'.
Args:
do_grid (bool): Is the map a grid (True) or a list of points
(False)?
outsd (dict): A dictionary of computed uncertainty arrays.
psd (dict): A dictionary of predicted uncertainty arrays.
moutgrid (dict): A dictionary of landmasked output ground
motion arrays.
Returns:
tuple: The mean uncertainty ratio and the letter grade.
"""
mean_rat = "--"
mygrade = "--"
if not do_grid or "PGA" not in outsd or "PGA" not in psd or "MMI" not in moutgrid:
return mean_rat, mygrade
sd_rat = outsd["PGA"] / psd["PGA"]
mmimasked = ma.masked_less(moutgrid["MMI"], 6.0)
mpgasd_rat = ma.masked_array(sd_rat, mask=mmimasked.mask)
if not np.all(mpgasd_rat.mask):
gvals = [0.96, 0.98, 1.05, 1.25]
grades = ["A", "B", "C", "D", "F"]
mean_rat = mpgasd_rat.mean()
for ix, val in enumerate(gvals):
if mean_rat <= val:
mygrade = grades[ix]
break
if mygrade == "--":
mygrade = "F"
return mean_rat, mygrade
def _get_layer_info(layer):
"""
We need a way to get units information about intensity measure types
and translate between OpenQuake naming convention and ShakeMap grid naming
convention.
Args:
layer (str): ShakeMap grid name.
Returns:
tuple: Tuple including:
- OpenQuake naming convention,
- units,
- significant digits.
"""
layer_out = layer
layer_units = ""
layer_digits = 4 # number of significant digits
if layer.endswith("_sd"):
layer_out = oq_to_file(layer.replace("_sd", ""))
layer_out = layer_out + "_sd"
else:
layer_out = oq_to_file(layer)
if layer.startswith("SA"):
layer_units = "ln(g)"
elif layer.startswith("PGA"):
layer_units = "ln(g)"
elif layer.startswith("PGV"):
layer_units = "ln(cm/s)"
elif layer.startswith("MMI"):
layer_units = "intensity"
layer_digits = 2
elif layer.startswith("vs30"):
layer_units = "m/s"
else:
raise ValueError(f"Unknown layer type: {layer}")
return (layer_out, layer_units, layer_digits)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
djangoapi/asgi.py
|
"""
ASGI config for djangoapi project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoapi.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
ReverseGame.py
|
#!/bin/python3
import math
import os
import random
import re
import sys
def reversal(n,k):
lt = list(range(n))
lt.reverse()
for i in range(1,n):
lt_ = lt[i:]
lt_.reverse()
lt = lt[0:i] + lt_
return (lt.index(k))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for n_iter in range(t):
nk = input().split()
n = int(nk[0])
k = int(nk[1])
result = reversal(n,k)
fptr.write(str(result) + '\n')
fptr.close()
|
[] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
python
| 1 | 0 | |
sydent/sydent.py
|
# -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# 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 ConfigParser
import logging
import logging.handlers
import os
import twisted.internet.reactor
from twisted.python import log
from db.sqlitedb import SqliteDatabase
from http.httpcommon import SslComponents
from http.httpserver import ClientApiHttpServer, ReplicationHttpsServer
from http.httpsclient import ReplicationHttpsClient
from http.servlets.blindlysignstuffservlet import BlindlySignStuffServlet
from http.servlets.pubkeyservlets import EphemeralPubkeyIsValidServlet, PubkeyIsValidServlet
from validators.emailvalidator import EmailValidator
from validators.msisdnvalidator import MsisdnValidator
from hs_federation.verifier import Verifier
from sign.ed25519 import SydentEd25519
from http.servlets.emailservlet import EmailRequestCodeServlet, EmailValidateCodeServlet
from http.servlets.msisdnservlet import MsisdnRequestCodeServlet, MsisdnValidateCodeServlet
from http.servlets.lookupservlet import LookupServlet
from http.servlets.bulklookupservlet import BulkLookupServlet
from http.servlets.pubkeyservlets import Ed25519Servlet
from http.servlets.threepidbindservlet import ThreePidBindServlet
from http.servlets.threepidunbindservlet import ThreePidUnbindServlet
from http.servlets.replication import ReplicationPushServlet
from http.servlets.getvalidated3pidservlet import GetValidated3pidServlet
from http.servlets.store_invite_servlet import StoreInviteServlet
from threepid.bind import ThreepidBinder
from replication.pusher import Pusher
logger = logging.getLogger(__name__)
class Sydent:
CONFIG_SECTIONS = ['general', 'db', 'http', 'email', 'crypto', 'sms']
CONFIG_DEFAULTS = {
# general
'server.name': '',
'log.path': '',
'pidfile.path': 'sydent.pid',
# db
'db.file': 'sydent.db',
# http
'clientapi.http.port': '8090',
'replication.https.certfile': '',
'replication.https.cacert': '', # This should only be used for testing
'replication.https.port': '4434',
'obey_x_forwarded_for': False,
# email
'email.template': 'res/email.template',
'email.from': 'Sydent Validation <noreply@{hostname}>',
'email.subject': 'Your Validation Token',
'email.invite.subject': '%(sender_display_name)s has invited you to chat',
'email.smtphost': 'localhost',
'email.smtpport': '25',
'email.smtpusername': '',
'email.smtppassword': '',
'email.hostname': '',
'email.tlsmode': '0',
# sms
'bodyTemplate': 'Your code is {token}',
# crypto
'ed25519.signingkey': '',
}
def __init__(self):
self.parse_config()
log_format = (
"%(asctime)s - %(name)s - %(lineno)d - %(levelname)s"
" - %(message)s"
)
formatter = logging.Formatter(log_format)
logPath = self.cfg.get('general', "log.path")
if logPath != '':
handler = logging.handlers.TimedRotatingFileHandler(
logPath, when='midnight', backupCount=365
)
handler.setFormatter(formatter)
def sighup(signum, stack):
logger.info("Closing log file due to SIGHUP")
handler.doRollover()
logger.info("Opened new log file due to SIGHUP")
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.INFO)
rootLogger.addHandler(handler)
logger.info("Starting Sydent server")
self.pidfile = self.cfg.get('general', "pidfile.path");
observer = log.PythonLoggingObserver()
observer.start()
self.db = SqliteDatabase(self).db
self.server_name = self.cfg.get('general', 'server.name')
if self.server_name == '':
self.server_name = os.uname()[1]
logger.warn(("You had not specified a server name. I have guessed that this server is called '%s' "
+ " and saved this in the config file. If this is incorrect, you should edit server.name in "
+ "the config file.") % (self.server_name,))
self.cfg.set('general', 'server.name', self.server_name)
self.save_config()
self.validators = Validators()
self.validators.email = EmailValidator(self)
self.validators.msisdn = MsisdnValidator(self)
self.keyring = Keyring()
self.keyring.ed25519 = SydentEd25519(self).signing_key
self.keyring.ed25519.alg = 'ed25519'
self.sig_verifier = Verifier(self)
self.servlets = Servlets()
self.servlets.emailRequestCode = EmailRequestCodeServlet(self)
self.servlets.emailValidate = EmailValidateCodeServlet(self)
self.servlets.msisdnRequestCode = MsisdnRequestCodeServlet(self)
self.servlets.msisdnValidate = MsisdnValidateCodeServlet(self)
self.servlets.lookup = LookupServlet(self)
self.servlets.bulk_lookup = BulkLookupServlet(self)
self.servlets.pubkey_ed25519 = Ed25519Servlet(self)
self.servlets.pubkeyIsValid = PubkeyIsValidServlet(self)
self.servlets.ephemeralPubkeyIsValid = EphemeralPubkeyIsValidServlet(self)
self.servlets.threepidBind = ThreePidBindServlet(self)
self.servlets.threepidUnbind = ThreePidUnbindServlet(self)
self.servlets.replicationPush = ReplicationPushServlet(self)
self.servlets.getValidated3pid = GetValidated3pidServlet(self)
self.servlets.storeInviteServlet = StoreInviteServlet(self)
self.servlets.blindlySignStuffServlet = BlindlySignStuffServlet(self)
self.threepidBinder = ThreepidBinder(self)
self.sslComponents = SslComponents(self)
self.clientApiHttpServer = ClientApiHttpServer(self)
self.replicationHttpsServer = ReplicationHttpsServer(self)
self.replicationHttpsClient = ReplicationHttpsClient(self)
self.pusher = Pusher(self)
def parse_config(self):
self.cfg = ConfigParser.SafeConfigParser(Sydent.CONFIG_DEFAULTS)
for sect in Sydent.CONFIG_SECTIONS:
try:
self.cfg.add_section(sect)
except ConfigParser.DuplicateSectionError:
pass
self.cfg.read(os.environ.get('SYDENT_CONF', "sydent.conf"))
def save_config(self):
fp = open("sydent.conf", 'w')
self.cfg.write(fp)
fp.close()
def run(self):
self.clientApiHttpServer.setup()
self.replicationHttpsServer.setup()
self.pusher.setup()
if self.pidfile:
with open(self.pidfile, 'w') as pidfile:
pidfile.write(str(os.getpid()) + "\n")
twisted.internet.reactor.run()
def ip_from_request(self, request):
if (self.cfg.get('http', 'obey_x_forwarded_for') and
request.requestHeaders.hasHeader("X-Forwarded-For")):
return request.requestHeaders.getRawHeaders("X-Forwarded-For")[0]
return request.getClientIP()
class Validators:
pass
class Servlets:
pass
class Keyring:
pass
if __name__ == '__main__':
syd = Sydent()
syd.run()
|
[] |
[] |
[
"SYDENT_CONF"
] |
[]
|
["SYDENT_CONF"]
|
python
| 1 | 0 | |
app/__init__.py
|
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_sslify import SSLify
import config
db = SQLAlchemy()
login_manager = LoginManager()
def create_app() -> Flask:
"""Create an application factory with SQLAlchemy, Login, and
SSLify
Returns:
Flask -- A Flask application object
"""
app = Flask(__name__)
app.secret_key = os.urandom(24)
env = os.getenv('FLASK_ENV', 'development')
if env == 'production':
SQL_ALCHEMY_DATABASE_URI = (
config.ProductionConfig.SQL_ALCHEMY_DATABASE_URI
)
elif env == 'testing':
SQL_ALCHEMY_DATABASE_URI = (
config.TestConfig.SQL_ALCHEMY_DATABASE_URI
)
else:
SQL_ALCHEMY_DATABASE_URI = config.Config.SQL_ALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = SQL_ALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
if 'DYNO' in os.environ:
SSLify(app)
from .models import User
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
from .routes import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
with app.app_context():
from . import routes
db.create_all()
return app
|
[] |
[] |
[
"FLASK_ENV"
] |
[]
|
["FLASK_ENV"]
|
python
| 1 | 0 | |
src/testproject/helpers/confighelper.py
|
# Copyright 2020 TestProject (https://testproject.io)
#
# 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 logging
from src.testproject import definitions
from src.testproject.sdk.exceptions import SdkException
class ConfigHelper:
"""Contains helper methods for SDK configuration"""
@staticmethod
def get_agent_service_address() -> str:
"""Returns the Agent service address as defined in the TP_AGENT_URL environment variable.
Defaults to http://127.0.0.1:8585 (localhost)
Returns:
str: the Agent service address
"""
address = os.getenv("TP_AGENT_URL")
if address is None:
logging.info(
"No Agent service address found in TP_AGENT_URL environment variable, "
"defaulting to http://127.0.0.1:8585 (localhost)"
)
return "http://127.0.0.1:8585"
# Replace 'localhost' with '127.0.0.1' to prevent delays as a result of DNS lookups
address = address.replace("localhost", "127.0.0.1")
logging.info(f"Using {address} as the Agent URL")
return address
@staticmethod
def get_developer_token() -> str:
"""Returns the TestProject developer token as defined in the TP_DEV_TOKEN environment variable
Returns:
str: the developer token
"""
token = os.getenv("TP_DEV_TOKEN")
if token is None:
logging.error("No developer token was found, did you set it in the TP_DEV_TOKEN environment variable?")
logging.error(
"You can get a developer token from https://app.testproject.io/#/integrations/sdk?lang=Python"
)
raise SdkException("No development token defined in TP_DEV_TOKEN environment variable")
return token
@staticmethod
def get_sdk_version() -> str:
"""Returns the SDK version as defined in the definitions module
Returns:
str: the current SDK version
"""
return definitions.get_sdk_version()
|
[] |
[] |
[
"TP_AGENT_URL",
"TP_DEV_TOKEN"
] |
[]
|
["TP_AGENT_URL", "TP_DEV_TOKEN"]
|
python
| 2 | 0 | |
vendor/github.com/itchio/wharf/pwr/bowl/bowl_overlay.go
|
package bowl
import (
"encoding/gob"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"github.com/itchio/savior/filesource"
"github.com/itchio/wharf/pwr/overlay"
"github.com/itchio/wharf/pools/fspool"
"github.com/itchio/wharf/tlc"
"github.com/itchio/wharf/wsync"
"github.com/pkg/errors"
)
var debugBrokenRename = os.Getenv("BOWL_DEBUG_BROKEN_RENAME") == "1"
var overlayVerbose = os.Getenv("BOWL_OVERLAY_VERBOSE") == "1"
func debugf(format string, args ...interface{}) {
if overlayVerbose {
fmt.Printf("[overlayBowl] %s\n", fmt.Sprintf(format, args...))
}
}
type overlayBowl struct {
TargetContainer *tlc.Container
TargetPool wsync.Pool
SourceContainer *tlc.Container
OutputFolder string
StageFolder string
stagePool *fspool.FsPool
targetFilesByPath map[string]int64
// files we'll have to move
transpositions []Transposition
// files we'll have to patch using an overlay
overlayFiles []int64
// files we'll have to move from the staging folder to the dest
moveFiles []int64
}
type OverlayBowlCheckpoint struct {
Transpositions []Transposition
OverlayFiles []int64
MoveFiles []int64
}
var _ Bowl = (*overlayBowl)(nil)
type OverlayBowlParams struct {
TargetContainer *tlc.Container
SourceContainer *tlc.Container
OutputFolder string
StageFolder string
}
func NewOverlayBowl(params *OverlayBowlParams) (Bowl, error) {
// input validation
if params.TargetContainer == nil {
return nil, errors.New("overlaybowl: TargetContainer must not be nil")
}
if params.SourceContainer == nil {
return nil, errors.New("overlaybowl: SourceContainer must not be nil")
}
{
if params.OutputFolder == "" {
return nil, errors.New("overlaybowl: OutputFolder must not be nil")
}
stats, err := os.Stat(params.OutputFolder)
if err != nil {
return nil, errors.New("overlaybowl: OutputFolder must exist")
}
if !stats.IsDir() {
return nil, errors.New("overlaybowl: OutputFolder must exist and be a directory")
}
}
if params.StageFolder == "" {
return nil, errors.New("overlaybowl: StageFolder must not be nil")
}
var err error
err = os.MkdirAll(params.StageFolder, 0755)
if err != nil {
return nil, errors.WithStack(err)
}
targetPool := fspool.New(params.TargetContainer, params.OutputFolder)
stagePool := fspool.New(params.SourceContainer, params.StageFolder)
targetFilesByPath := make(map[string]int64)
for index, tf := range params.TargetContainer.Files {
targetFilesByPath[tf.Path] = int64(index)
}
return &overlayBowl{
TargetContainer: params.TargetContainer,
TargetPool: targetPool,
SourceContainer: params.SourceContainer,
OutputFolder: params.OutputFolder,
StageFolder: params.StageFolder,
stagePool: stagePool,
targetFilesByPath: targetFilesByPath,
}, nil
}
func (b *overlayBowl) Save() (*BowlCheckpoint, error) {
c := &BowlCheckpoint{
Data: &OverlayBowlCheckpoint{
MoveFiles: b.moveFiles,
OverlayFiles: b.overlayFiles,
Transpositions: b.transpositions,
},
}
return c, nil
}
func (b *overlayBowl) Resume(c *BowlCheckpoint) error {
if c == nil {
return nil
}
if cc, ok := c.Data.(*OverlayBowlCheckpoint); ok {
b.transpositions = cc.Transpositions
b.moveFiles = cc.MoveFiles
b.overlayFiles = cc.OverlayFiles
}
return nil
}
func (b *overlayBowl) GetWriter(index int64) (EntryWriter, error) {
sourceFile := b.SourceContainer.Files[index]
if sourceFile == nil {
return nil, errors.Errorf("overlayBowl: unknown source file %d", index)
}
if targetIndex, ok := b.targetFilesByPath[sourceFile.Path]; ok {
debugf("returning overlay writer for '%s'", sourceFile.Path)
// oh damn, that file already exists in the output - let's make an overlay
b.markOverlay(index)
r, err := b.TargetPool.GetReadSeeker(targetIndex)
if err != nil {
return nil, errors.WithStack(err)
}
wPath := b.stagePool.GetPath(index)
return &overlayEntryWriter{path: wPath, readSeeker: r}, nil
}
// guess it's a new file! let's write it to staging anyway
b.markMove(index)
debugf("returning move writer for '%s'", sourceFile.Path)
wPath := b.stagePool.GetPath(index)
return &freshEntryWriter{path: wPath}, nil
}
func (b *overlayBowl) markOverlay(index int64) {
// make sure we don't double mark it
for _, i := range b.overlayFiles {
if i == index {
// oh cool it's already marked
return
}
}
// mark it
b.overlayFiles = append(b.overlayFiles, index)
}
func (b *overlayBowl) markMove(index int64) {
// make sure we don't double mark it
for _, i := range b.moveFiles {
if i == index {
// oh cool it's already marked
return
}
}
// mark it
b.moveFiles = append(b.moveFiles, index)
}
func (b *overlayBowl) Transpose(t Transposition) error {
// ok, say we resumed, maybe we already have a transposition for this source file?
for i, tt := range b.transpositions {
if tt.SourceIndex == t.SourceIndex {
// and so we do! let's replace it.
b.transpositions[i] = t
return nil
}
}
// if we didn't already have one, let's record it for when we commit
b.transpositions = append(b.transpositions, t)
return nil
}
func (b *overlayBowl) Commit() error {
// oy, do we have work to do!
var err error
// - close the target pool, in case it still has a reader open!
err = b.TargetPool.Close()
if err != nil {
return errors.WithStack(err)
}
// - ensure dirs and symlinks
err = b.ensureDirsAndSymlinks()
if err != nil {
return errors.WithStack(err)
}
// - apply transpositions
err = b.applyTranspositions()
if err != nil {
return errors.WithStack(err)
}
// - move files we need to move
err = b.applyMoves()
if err != nil {
return errors.WithStack(err)
}
// - merge overlays
err = b.applyOverlays()
if err != nil {
return errors.WithStack(err)
}
// - delete ghosts
err = b.deleteGhosts()
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (b *overlayBowl) ensureDirsAndSymlinks() error {
outputPath := b.OutputFolder
for _, dir := range b.SourceContainer.Dirs {
path := filepath.Join(outputPath, filepath.FromSlash(dir.Path))
err := os.MkdirAll(path, 0755)
if err != nil {
// If path is already a directory, MkdirAll does nothing and returns nil.
// so if we get a non-nil error, we know it's serious business (permissions, etc.)
return err
}
}
// TODO: behave like github.com/itchio/savior for symlinks on windows ?
for _, symlink := range b.SourceContainer.Symlinks {
path := filepath.Join(outputPath, filepath.FromSlash(symlink.Path))
dest, err := os.Readlink(path)
if err != nil {
if os.IsNotExist(err) {
// symlink was missing
err = os.Symlink(filepath.FromSlash(symlink.Dest), path)
if err != nil {
return err
}
} else {
return err
}
}
// symlink is there
if dest != filepath.FromSlash(symlink.Dest) {
// wrong dest, fixing that
err = os.Remove(path)
if err != nil {
return err
}
err = os.Symlink(filepath.FromSlash(symlink.Dest), path)
if err != nil {
return err
}
return nil
}
}
return nil
}
type pathTranspo struct {
TargetPath string
OutputPath string
}
type mkdirBehavior int
const (
mkdirBehaviorNever mkdirBehavior = 0xf8792 + iota
mkdirBehaviorIfNeeded
)
func (b *overlayBowl) applyTranspositions() error {
transpositions := make(map[string][]*pathTranspo)
outputPath := b.OutputFolder
for _, t := range b.transpositions {
targetFile := b.TargetContainer.Files[t.TargetIndex]
sourceFile := b.SourceContainer.Files[t.SourceIndex]
transpositions[targetFile.Path] = append(transpositions[targetFile.Path], &pathTranspo{
TargetPath: targetFile.Path,
OutputPath: sourceFile.Path,
})
}
applyMultipleTranspositions := func(targetPath string, group []*pathTranspo) error {
// a file got duplicated!
var noop *pathTranspo
for _, transpo := range group {
if targetPath == transpo.OutputPath {
noop = transpo
break
}
}
for i, transpo := range group {
if noop == nil {
if i == 0 {
// arbitrary pick first transposition as being the rename - do
// all the others as copies first
continue
}
} else if transpo == noop {
// no need to copy for the noop
continue
}
oldAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(targetPath))
newAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(transpo.OutputPath))
err := b.copy(oldAbsolutePath, newAbsolutePath, mkdirBehaviorIfNeeded)
if err != nil {
return errors.WithStack(err)
}
}
if noop == nil {
// we treated the first transpo as being the rename, gotta do it now
transpo := group[0]
oldAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(targetPath))
newAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(transpo.OutputPath))
err := b.move(oldAbsolutePath, newAbsolutePath)
if err != nil {
return errors.WithStack(err)
}
} else {
// muffin!
}
return nil
}
var cleanupRenames []*pathTranspo
alreadyDone := make(map[string]bool)
renameSeed := int64(0)
for _, group := range transpositions {
for _, transpo := range group {
if transpo.TargetPath == transpo.OutputPath {
// no-ops can't clash
continue
}
if _, ok := transpositions[transpo.OutputPath]; ok {
// transpo is writing to the source of swapBuddy, this will blow shit up
// make it write to a safe path instead, then rename it to the correct path
renameSeed++
safePath := transpo.OutputPath + fmt.Sprintf(".butler-rename-%d", renameSeed)
cleanupRenames = append(cleanupRenames, &pathTranspo{
TargetPath: safePath,
OutputPath: transpo.OutputPath,
})
transpo.OutputPath = safePath
}
}
}
for groupTargetPath, group := range transpositions {
if alreadyDone[groupTargetPath] {
continue
}
alreadyDone[groupTargetPath] = true
if len(group) == 1 {
transpo := group[0]
if transpo.TargetPath == transpo.OutputPath {
// file wasn't touched at all
} else {
// file was renamed
oldAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(transpo.TargetPath))
newAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(transpo.OutputPath))
err := b.move(oldAbsolutePath, newAbsolutePath)
if err != nil {
return errors.WithStack(err)
}
}
} else {
err := applyMultipleTranspositions(groupTargetPath, group)
if err != nil {
return errors.WithStack(err)
}
}
}
for _, rename := range cleanupRenames {
oldAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(rename.TargetPath))
newAbsolutePath := filepath.Join(outputPath, filepath.FromSlash(rename.OutputPath))
err := b.move(oldAbsolutePath, newAbsolutePath)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (b *overlayBowl) copy(oldAbsolutePath string, newAbsolutePath string, mkdirBehavior mkdirBehavior) error {
debugf("cp '%s' '%s'", oldAbsolutePath, newAbsolutePath)
if mkdirBehavior == mkdirBehaviorIfNeeded {
err := os.MkdirAll(filepath.Dir(newAbsolutePath), os.FileMode(0755))
if err != nil {
return errors.WithStack(err)
}
}
// fall back to copy + remove
reader, err := os.Open(oldAbsolutePath)
if err != nil {
return errors.WithStack(err)
}
defer reader.Close()
stats, err := reader.Stat()
if err != nil {
return errors.WithStack(err)
}
writer, err := os.OpenFile(newAbsolutePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, stats.Mode()|tlc.ModeMask)
if err != nil {
return errors.WithStack(err)
}
defer writer.Close()
_, err = io.Copy(writer, reader)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (b *overlayBowl) move(oldAbsolutePath string, newAbsolutePath string) error {
debugf("mv '%s' '%s'", oldAbsolutePath, newAbsolutePath)
err := os.Remove(newAbsolutePath)
if err != nil {
if !os.IsNotExist(err) {
return errors.WithStack(err)
}
}
err = os.MkdirAll(filepath.Dir(newAbsolutePath), os.FileMode(0755))
if err != nil {
return errors.WithStack(err)
}
if debugBrokenRename {
err = &os.PathError{}
} else {
err = os.Rename(oldAbsolutePath, newAbsolutePath)
}
if err != nil {
debugf("falling back to copy because of %s", err.Error())
if os.IsNotExist(err) {
debugf("mhh our rename error was that old does not exist")
}
cErr := b.copy(oldAbsolutePath, newAbsolutePath, mkdirBehaviorNever)
if cErr != nil {
return cErr
}
cErr = os.Remove(oldAbsolutePath)
if cErr != nil {
return cErr
}
}
return nil
}
func (b *overlayBowl) applyMoves() error {
for _, moveIndex := range b.moveFiles {
file := b.SourceContainer.Files[moveIndex]
if file == nil {
return errors.Errorf("overlaybowl: applyMoves: no such file %d", moveIndex)
}
debugf("applying move '%s'", file.Path)
nativePath := filepath.FromSlash(file.Path)
stagePath := filepath.Join(b.StageFolder, nativePath)
outputPath := filepath.Join(b.OutputFolder, nativePath)
err := b.move(stagePath, outputPath)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (b *overlayBowl) applyOverlays() error {
ctx := &overlay.OverlayPatchContext{}
handleOverlay := func(overlayIndex int64) error {
file := b.SourceContainer.Files[overlayIndex]
if file == nil {
return errors.Errorf("overlaybowl: applyOverlays: no such file %d", overlayIndex)
}
debugf("applying overlay '%s'", file.Path)
nativePath := filepath.FromSlash(file.Path)
stagePath := filepath.Join(b.StageFolder, nativePath)
r, err := filesource.Open(stagePath)
if err != nil {
return errors.WithStack(err)
}
defer r.Close()
outputPath := filepath.Join(b.OutputFolder, nativePath)
w, err := os.OpenFile(outputPath, os.O_WRONLY, 0644)
if err != nil {
return errors.WithStack(err)
}
defer w.Close()
err = ctx.Patch(r, w)
if err != nil {
return errors.WithStack(err)
}
finalSize, err := w.Seek(0, io.SeekCurrent)
if err != nil {
return errors.WithStack(err)
}
err = w.Truncate(finalSize)
if err != nil {
return errors.WithStack(err)
}
return nil
}
for _, overlayIndex := range b.overlayFiles {
err := handleOverlay(overlayIndex)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
// ghosts
// GhostKind determines what went missing: a file, a directory, or a symlink
type GhostKind int
const (
// GhostKindDir indicates that a directory has disappeared between two containers
GhostKindDir GhostKind = iota + 0xfaf0
// GhostKindFile indicates that a file has disappeared between two containers
GhostKindFile
// GhostKindSymlink indicates that a symbolic link has disappeared between two containers
GhostKindSymlink
)
// A Ghost is a file, directory, or symlink, that has disappeared from one
// container (target) to the next (source)
type Ghost struct {
Kind GhostKind
Path string
}
func detectGhosts(sourceContainer *tlc.Container, targetContainer *tlc.Container) []Ghost {
// first make a map of all the file paths in source, for later lookup
sourceFileMap := make(map[string]bool)
for _, f := range sourceContainer.Files {
sourceFileMap[f.Path] = true
}
for _, s := range sourceContainer.Symlinks {
sourceFileMap[s.Path] = true
}
for _, d := range sourceContainer.Dirs {
sourceFileMap[d.Path] = true
}
// then walk through target container paths, if they're not in source, they were deleted
var ghosts []Ghost
for _, f := range targetContainer.Files {
if !sourceFileMap[f.Path] {
ghosts = append(ghosts, Ghost{
Kind: GhostKindFile,
Path: f.Path,
})
}
}
for _, s := range targetContainer.Symlinks {
if !sourceFileMap[s.Path] {
ghosts = append(ghosts, Ghost{
Kind: GhostKindSymlink,
Path: s.Path,
})
}
}
for _, d := range targetContainer.Dirs {
if !sourceFileMap[d.Path] {
ghosts = append(ghosts, Ghost{
Kind: GhostKindDir,
Path: d.Path,
})
}
}
return ghosts
}
type byDecreasingLength []Ghost
func (s byDecreasingLength) Len() int {
return len(s)
}
func (s byDecreasingLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byDecreasingLength) Less(i, j int) bool {
return len(s[j].Path) < len(s[i].Path)
}
func (b *overlayBowl) deleteGhosts() error {
ghosts := detectGhosts(b.SourceContainer, b.TargetContainer)
debugf("%d total ghosts", len(ghosts))
sort.Sort(byDecreasingLength(ghosts))
for _, ghost := range ghosts {
debugf("ghost: %v", ghost)
op := filepath.Join(b.OutputFolder, filepath.FromSlash(ghost.Path))
err := os.Remove(op)
if err == nil || os.IsNotExist(err) {
// removed or already removed, good
debugf("ghost removed or already gone '%s'", ghost.Path)
} else {
if ghost.Kind == GhostKindDir {
// sometimes we can't delete directories, it's okay
debugf("ghost dir left behind '%s'", ghost.Path)
} else {
return errors.WithStack(err)
}
}
}
return nil
}
// notifyWriteCloser
type onCloseFunc func() error
type notifyWriteCloser struct {
w io.WriteCloser
onClose onCloseFunc
}
var _ io.WriteCloser = (*notifyWriteCloser)(nil)
func (nwc *notifyWriteCloser) Write(buf []byte) (int, error) {
return nwc.w.Write(buf)
}
func (nwc *notifyWriteCloser) Close() (rErr error) {
defer func() {
if nwc.onClose != nil {
cErr := nwc.onClose()
if cErr != nil && rErr == nil {
rErr = cErr
}
}
}()
err := nwc.w.Close()
if err != nil {
rErr = errors.WithStack(err)
return
}
return
}
// overlayEntryWriter
type overlayEntryWriter struct {
path string
readSeeker io.ReadSeeker
file *os.File
overlay overlay.OverlayWriter
// this is how far into the source (new) file we are.
// it doesn't correspond with `OverlayOffset`, which is
// how many bytes of output the OverlayWriter has produced.
sourceOffset int64
}
type OverlayEntryWriterCheckpoint struct {
// This offset is how many bytes we've written into the
// overlay, not how many bytes into the new file we are.
OverlayOffset int64
// This offset is how many bytes we've read from the target (old) file
ReadOffset int64
}
func (w *overlayEntryWriter) Tell() int64 {
return w.sourceOffset
}
func (w *overlayEntryWriter) Save() (*WriterCheckpoint, error) {
err := w.overlay.Flush()
if err != nil {
return nil, errors.WithStack(err)
}
err = w.file.Sync()
if err != nil {
return nil, errors.WithStack(err)
}
debugf("saving checkpoint: Offset = %d, ReadOffset = %d, OverlayOffset = %d",
w.sourceOffset, w.overlay.ReadOffset(), w.overlay.OverlayOffset())
c := &WriterCheckpoint{
Offset: w.sourceOffset,
Data: &OverlayEntryWriterCheckpoint{
ReadOffset: w.overlay.ReadOffset(),
OverlayOffset: w.overlay.OverlayOffset(),
},
}
return c, nil
}
func (w *overlayEntryWriter) Resume(c *WriterCheckpoint) (int64, error) {
err := os.MkdirAll(filepath.Dir(w.path), 0755)
if err != nil {
return 0, errors.WithStack(err)
}
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY, os.FileMode(0644))
if err != nil {
return 0, errors.WithStack(err)
}
w.file = f
if c != nil {
// we might need to seek y'all
cc, ok := c.Data.(*OverlayEntryWriterCheckpoint)
if !ok {
return 0, errors.New("invalid checkpoint for overlayEntryWriter")
}
// seek the reader first
r := w.readSeeker
_, err = r.Seek(cc.ReadOffset, io.SeekStart)
if err != nil {
return 0, errors.WithStack(err)
}
// now the writer
_, err = f.Seek(cc.OverlayOffset, io.SeekStart)
if err != nil {
return 0, errors.WithStack(err)
}
w.sourceOffset = c.Offset
debugf("making overlaywriter with ReadOffset %d, OverlayOffset %d", cc.ReadOffset, cc.OverlayOffset)
w.overlay, err = overlay.NewOverlayWriter(r, cc.ReadOffset, f, cc.OverlayOffset)
if err != nil {
return 0, errors.WithStack(err)
}
} else {
// the pool we got the readSeeker from doesn't need to give us a reader from 0,
// so we need to seek here
_, err = w.readSeeker.Seek(0, io.SeekStart)
if err != nil {
return 0, errors.WithStack(err)
}
r := w.readSeeker
debugf("making overlaywriter with 0 ReadOffset and OverlayOffset")
w.overlay, err = overlay.NewOverlayWriter(r, 0, f, 0)
if err != nil {
return 0, errors.WithStack(err)
}
}
return w.sourceOffset, nil
}
func (w *overlayEntryWriter) Write(buf []byte) (int, error) {
if w.overlay == nil {
return 0, ErrUninitializedWriter
}
n, err := w.overlay.Write(buf)
w.sourceOffset += int64(n)
return n, err
}
func (w *overlayEntryWriter) Finalize() error {
if w.overlay != nil {
err := w.overlay.Finalize()
if err != nil {
return errors.WithMessage(err, "finalizing overlay writer")
}
w.overlay = nil
}
err := w.file.Sync()
if err != nil {
return errors.WithMessage(err, "syncing overlay patch file")
}
return nil
}
func (w *overlayEntryWriter) Close() error {
return w.file.Close()
}
func init() {
gob.Register(&OverlayEntryWriterCheckpoint{})
gob.Register(&OverlayBowlCheckpoint{})
}
|
[
"\"BOWL_DEBUG_BROKEN_RENAME\"",
"\"BOWL_OVERLAY_VERBOSE\""
] |
[] |
[
"BOWL_DEBUG_BROKEN_RENAME",
"BOWL_OVERLAY_VERBOSE"
] |
[]
|
["BOWL_DEBUG_BROKEN_RENAME", "BOWL_OVERLAY_VERBOSE"]
|
go
| 2 | 0 | |
src/sagemaker_mxnet_container/training.py
|
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'license' file accompanying this file. This file is
# distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from __future__ import absolute_import
import logging
import os
import socket
import subprocess
from retrying import retry
import sagemaker_containers.beta.framework as framework
from sagemaker_mxnet_container.training_utils import scheduler_host
LAUNCH_PS_ENV_NAME = 'sagemaker_parameter_server_enabled'
ROLES = ['worker', 'scheduler', 'server']
logger = logging.getLogger(__name__)
def _env_vars_for_role(role, hosts, ps_port, ps_verbose):
if role in ROLES:
return {
'DMLC_NUM_WORKER': str(len(hosts)),
'DMLC_NUM_SERVER': str(len(hosts)),
'DMLC_ROLE': role,
'DMLC_PS_ROOT_URI': _host_lookup(scheduler_host(hosts)),
'DMLC_PS_ROOT_PORT': ps_port,
'PS_VERBOSE': ps_verbose,
}
raise ValueError('Unexpected role: {}'.format(role))
def _run_mxnet_process(role, hosts, ps_port, ps_verbose):
role_env = os.environ.copy()
role_env.update(_env_vars_for_role(role, hosts, ps_port, ps_verbose))
subprocess.Popen("python -c 'import mxnet'", shell=True, env=role_env).pid
@retry(stop_max_delay=1000 * 60 * 15, wait_exponential_multiplier=100,
wait_exponential_max=30000)
def _host_lookup(host):
return socket.gethostbyname(host)
def _verify_hosts(hosts):
for host in hosts:
_host_lookup(host)
def train(env):
logger.info('MXNet training environment: {}'.format(env.to_env_vars()))
if env.additional_framework_parameters.get(LAUNCH_PS_ENV_NAME, False):
_verify_hosts(env.hosts)
ps_port = env.hyperparameters.get('_ps_port', '8000')
ps_verbose = env.hyperparameters.get('_ps_verbose', '0')
logger.info('Starting distributed training task')
if scheduler_host(env.hosts) == env.current_host:
_run_mxnet_process('scheduler', env.hosts, ps_port, ps_verbose)
_run_mxnet_process('server', env.hosts, ps_port, ps_verbose)
os.environ.update(_env_vars_for_role('worker', env.hosts, ps_port, ps_verbose))
framework.modules.run_module(env.module_dir, env.to_cmd_args(),
env.to_env_vars(), env.module_name)
def main():
train(framework.training_env())
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
dnssvcsinstancesv2/dns_svcs_instances_v2_integration_test.go
|
// +build integration
/**
* (C) Copyright IBM Corp. 2020.
*
* 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 dnssvcsinstancesv2_test
import (
"os"
"github.com/IBM/dns-svcs-go-sdk/dnssvcsinstancesv2"
"github.com/IBM/go-sdk-core/v3/core"
"github.com/joho/godotenv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe(`DnsSvcsInstancesV2`, func() {
err := godotenv.Load("../.env")
It(`Successfully loading .env file`, func() {
Expect(err).To(BeNil())
})
authenticator := &core.IamAuthenticator{
ApiKey: os.Getenv("IAMAPIKEY"),
}
options := &dnssvcsinstancesv2.DnsSvcsInstancesV2Options{
ServiceName: "DnsSvcsInstancesV2_Mokcing",
Authenticator: authenticator,
}
service, err := dnssvcsinstancesv2.NewDnsSvcsInstancesV2UsingExternalConfig(options)
It(`Successfully created DnsSvcsInstancesV2 service instance`, func() {
Expect(err).To(BeNil())
})
Describe(`ListResourceInstances(listResourceInstancesOptions *ListResourceInstancesOptions)`, func() {
Context(`Successfully list resource by resourceID and type`, func() {
header := map[string]string{
"Content-type": "application/json",
}
resourceID := os.Getenv("RESOURCE_ID")
resourceType := dnssvcsinstancesv2.ListResourceInstancesOptions_Type_ServiceInstance
listResourceInstancesOptions := service.NewListResourceInstancesOptions(resourceID, resourceType).
SetLimit("2").
SetHeaders(header)
It(`Successfully list all resources`, func() {
result, detailedResponse, err := service.ListResourceInstances(listResourceInstancesOptions)
Expect(err).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(200))
firstResource := result.Resources[0]
Expect(*firstResource.ResourceID).To(Equal(resourceID))
Expect(*firstResource.Name).ToNot(BeNil())
secondResource := result.Resources[1]
Expect(*secondResource.ResourceID).To(Equal(resourceID))
Expect(*secondResource.Name).ToNot(BeNil())
})
})
Context(`Failed to list resource by resourceID and type`, func() {
resourceID := os.Getenv("RESOURCE_ID")
resourceType := dnssvcsinstancesv2.ListResourceInstancesOptions_Type_ServiceInstance
listResourceInstancesOptions := &dnssvcsinstancesv2.ListResourceInstancesOptions{}
listResourceInstancesOptions.SetResourceID(resourceID)
listResourceInstancesOptions.SetType(resourceType)
listResourceInstancesOptions.SetName("testString")
listResourceInstancesOptions.SetGuid("testString")
listResourceInstancesOptions.SetResourceGroupID("testString")
listResourceInstancesOptions.SetResourcePlanID("testString")
listResourceInstancesOptions.SetUpdatedFrom("testString")
listResourceInstancesOptions.SetUpdatedTo("testString")
It(`Failed to list all resouces`, func() {
_, _, err := service.ListResourceInstances(listResourceInstancesOptions)
Expect(err).Should(HaveOccurred())
})
})
})
Describe(`CreateResourceInstance(createResourceInstanceOptions *CreateResourceInstanceOptions)`, func() {
Context(`Successfully create resource instance`, func() {
name := "To Kill a Mockingbird"
target := os.Getenv("TARGET")
resourceGroup := os.Getenv("RESOURCE_GROUP")
resourcePlanID := os.Getenv("RESOURCE_PLAN_ID")
createResourceInstanceOptions := service.NewCreateResourceInstanceOptions(name, target, resourceGroup, resourcePlanID)
It(`Successfully create new resource`, func() {
result, detailedResponse, err := service.CreateResourceInstance(createResourceInstanceOptions)
Expect(err).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(201))
Expect(*result.Name).To(Equal("To Kill a Mockingbird"))
Expect(*result.ResourceGroupID).To(Equal(resourceGroup))
})
})
Context(`Fail to create resource instance`, func() {
header := map[string]string{
"Content-type": "application/json",
}
createResourceInstanceOptions := &dnssvcsinstancesv2.CreateResourceInstanceOptions{}
createResourceInstanceOptions.SetAllowCleanup(false)
createResourceInstanceOptions.SetName("testString")
createResourceInstanceOptions.SetResourceGroup("testString")
createResourceInstanceOptions.SetResourcePlanID("testString")
createResourceInstanceOptions.SetTarget("testString")
createResourceInstanceOptions.SetHeaders(header)
It(`Fail to create new resource`, func() {
result, detailedResponse, err := service.CreateResourceInstance(createResourceInstanceOptions)
Expect(result).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(400))
Expect(err).Should(HaveOccurred())
})
})
})
Describe(`UpdateResourceInstance(updateResourceInstanceOptions *UpdateResourceInstanceOptions)`, func() {
Context(`Successfully update resource by instanceID`, func() {
instanceID := os.Getenv("INSTANCE_ID")
instanceName := "To Update a Mockingbird"
updateResourceInstanceOptions := service.NewUpdateResourceInstanceOptions(instanceID).
SetName(instanceName).
SetAllowCleanup(true)
It(`Successfully update resource by instanceID`, func() {
result, detailedResponse, err := service.UpdateResourceInstance(updateResourceInstanceOptions)
Expect(err).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(200))
Expect(*result.Guid).To(Equal(instanceID))
})
})
Context(`Failed to update resource by instanceID`, func() {
header := map[string]string{
"Content-type": "application/json",
}
badinstanceID := "111"
instanceName := "To Update a Mockingbird"
updateResourceInstanceOptions := &dnssvcsinstancesv2.UpdateResourceInstanceOptions{}
updateResourceInstanceOptions.SetID(badinstanceID)
updateResourceInstanceOptions.SetName(instanceName)
updateResourceInstanceOptions.SetResourcePlanID("testString")
updateResourceInstanceOptions.SetHeaders(header)
It(`Failed to update resource by instanceID`, func() {
result, detailedResponse, err := service.UpdateResourceInstance(updateResourceInstanceOptions)
Expect(result).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(404))
Expect(err).Should(HaveOccurred())
})
})
})
Describe(`GetResourceInstance(getResourceInstanceOptions *GetResourceInstanceOptions)`, func() {
Context(`Successfully get resource by instanceID`, func() {
instanceID := os.Getenv("INSTANCE_ID")
getResourceInstanceOptions := service.NewGetResourceInstanceOptions(instanceID)
It(`Successfully get resource by instanceID`, func() {
result, detailedResponse, err := service.GetResourceInstance(getResourceInstanceOptions)
Expect(err).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(200))
Expect(*result.Guid).To(Equal(instanceID))
})
})
Context(`Failed to get resource by instanceID`, func() {
header := map[string]string{
"Content-type": "application/json",
}
badinstanceID := "111"
getResourceInstanceOptions := &dnssvcsinstancesv2.GetResourceInstanceOptions{}
getResourceInstanceOptions.SetID(badinstanceID)
getResourceInstanceOptions.SetHeaders(header)
It(`Failed to get resource by instanceID`, func() {
result, detailedResponse, err := service.GetResourceInstance(getResourceInstanceOptions)
Expect(result).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(404))
Expect(err).Should(HaveOccurred())
})
})
})
Describe(`DeleteResourceInstance(deleteResourceInstanceOptions *DeleteResourceInstanceOptions)`, func() {
Context(`Successfully delete resource by instanceID`, func() {
instanceID := os.Getenv("INSTANCE_ID")
deleteResourceInstanceOptions := service.NewDeleteResourceInstanceOptions(instanceID)
It(`Successfully delete resource by instanceID`, func() {
detailedResponse, err := service.DeleteResourceInstance(deleteResourceInstanceOptions)
Expect(err).To(BeNil())
Expect(detailedResponse.StatusCode).To(Equal(204))
})
})
Context(`Failed to delete resource by instanceID`, func() {
header := map[string]string{
"Content-type": "application/json",
}
badinstanceID := "111"
deleteResourceInstanceOptions := &dnssvcsinstancesv2.DeleteResourceInstanceOptions{}
deleteResourceInstanceOptions.SetID(badinstanceID)
deleteResourceInstanceOptions.SetHeaders(header)
It(`Failed to delete resource by instanceID`, func() {
detailedResponse, err := service.DeleteResourceInstance(deleteResourceInstanceOptions)
Expect(detailedResponse.StatusCode).To(Equal(404))
Expect(err).Should(HaveOccurred())
})
})
})
})
|
[
"\"IAMAPIKEY\"",
"\"RESOURCE_ID\"",
"\"RESOURCE_ID\"",
"\"TARGET\"",
"\"RESOURCE_GROUP\"",
"\"RESOURCE_PLAN_ID\"",
"\"INSTANCE_ID\"",
"\"INSTANCE_ID\"",
"\"INSTANCE_ID\""
] |
[] |
[
"RESOURCE_ID",
"RESOURCE_GROUP",
"INSTANCE_ID",
"RESOURCE_PLAN_ID",
"IAMAPIKEY",
"TARGET"
] |
[]
|
["RESOURCE_ID", "RESOURCE_GROUP", "INSTANCE_ID", "RESOURCE_PLAN_ID", "IAMAPIKEY", "TARGET"]
|
go
| 6 | 0 | |
server/router.go
|
package server
import (
"os"
"singo/api"
"singo/middleware"
"github.com/gin-gonic/gin"
)
// NewRouter 路由配置
func NewRouter() *gin.Engine {
r := gin.Default()
// 中间件, 顺序不能改
r.Use(middleware.Session(os.Getenv("SESSION_SECRET")))
r.Use(middleware.Cors())
// 路由
v1 := r.Group("/api/v1")
{
// 用户注册
v1.POST("user/register", api.UserRegister)
// 用户登录
v1.POST("user/login", api.UserLogin)
//用户通过token获取用户的信息
v1.GET("user/user_info", middleware.JWTAuth(), api.User_info_Find)
//修改头像的路径
v1.POST("user/update_picurl", middleware.JWTAuth(), api.Update_pic)
//修改用户的密码
v1.POST("user/update_password", middleware.JWTAuth(), api.Update_Password)
//修改用户的基本信息
v1.POST("user/update_info", middleware.JWTAuth(), api.Update_userinfo)
//创建歌曲
v1.POST("music/creat_music", api.Creat_Musics)
//轮播图展示传入num,num不是必须传入的,传入的num意思是需要多少条数据,默认为4
v1.GET("lunbo/show", api.Find_lun_bo)
//用户喜欢状态的修改
v1.GET("music_love/change", middleware.JWTAuth(), api.Creat_user_love_music)
//展示用户的喜欢歌曲
v1.GET("music_love/show_love", middleware.JWTAuth(), api.Show_Love_Music)
//展示新歌
v1.GET("music_new/show", api.Find_new_music)
}
//设备相关操作
return r
}
|
[
"\"SESSION_SECRET\""
] |
[] |
[
"SESSION_SECRET"
] |
[]
|
["SESSION_SECRET"]
|
go
| 1 | 0 | |
nixui/tests/test_api.py
|
import os
import pytest
from nixui.options import api
SAMPLES_PATH = 'tests/sample'
@pytest.mark.datafiles(SAMPLES_PATH)
def test_get_option_tree():
os.environ['CONFIGURATION_PATH'] = os.path.abspath(os.path.join(SAMPLES_PATH, 'configuration.nix'))
assert api.get_option_tree()
|
[] |
[] |
[
"CONFIGURATION_PATH"
] |
[]
|
["CONFIGURATION_PATH"]
|
python
| 1 | 0 | |
hello.py
|
#!/usr/bin/env python3
import templates
import cgi
import secret
import os
# import json
# Print environment as json
# print("Content-Type: application/json")
# print()
# print(json.dumps(dict(os.environ), indent=2))
# Print query parameter data in html
# print("Content-Type: text/html")
# print()
# print(f"<p>QUERY_STRING={os.environ.get('QUERY_STRING')}</p>")
# Print browser data in html
# print("Content-Type: text/html")
# print()
# print(f"<p>HTTP_USER_AGENT={os.environ.get('HTTP_USER_AGENT')}</p>")
USER_COOKIE = "user=" + secret.username
PASS_COOKIE = "pass=" + secret.password
cookie_string = os.environ.get('HTTP_COOKIE')
if (cookie_string and USER_COOKIE in cookie_string and PASS_COOKIE in cookie_string):
print(templates.secret_page(secret.username, secret.password))
else:
fieldStorage = cgi.FieldStorage()
if (fieldStorage and fieldStorage['username'] and fieldStorage['password']):
username = fieldStorage['username'].value
password = fieldStorage['password'].value
print('Set-Cookie: user=' + username)
print('Set-Cookie: pass=' + password)
if (username == secret.username and password == secret.password):
isLoggedIn = True
else:
print(templates.after_login_incorrect())
else:
print(templates.login_page())
print()
|
[] |
[] |
[
"HTTP_COOKIE",
"QUERY_STRING",
"HTTP_USER_AGENT"
] |
[]
|
["HTTP_COOKIE", "QUERY_STRING", "HTTP_USER_AGENT"]
|
python
| 3 | 0 | |
main.go
|
/*
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 (
"flag"
"fmt"
"os"
"runtime"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metal3iov1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
metal3iocontroller "github.com/metal3-io/baremetal-operator/controllers/metal3.io"
"github.com/metal3-io/baremetal-operator/pkg/bmc"
"github.com/metal3-io/baremetal-operator/pkg/provisioner"
"github.com/metal3-io/baremetal-operator/pkg/provisioner/demo"
"github.com/metal3-io/baremetal-operator/pkg/provisioner/empty"
"github.com/metal3-io/baremetal-operator/pkg/provisioner/fixture"
"github.com/metal3-io/baremetal-operator/pkg/provisioner/ironic"
"github.com/metal3-io/baremetal-operator/pkg/version"
// +kubebuilder:scaffold:imports
)
var (
scheme = k8sruntime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
healthAddr string
)
func init() {
_ = clientgoscheme.AddToScheme(scheme)
_ = metal3iov1alpha1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
}
func printVersion() {
setupLog.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
setupLog.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
setupLog.Info(fmt.Sprintf("baremetal-operator version: %s", version.String))
}
func setupChecks(mgr ctrl.Manager) {
if err := mgr.AddReadyzCheck("ping", healthz.Ping); err != nil {
setupLog.Error(err, "unable to create ready check")
os.Exit(1)
}
if err := mgr.AddHealthzCheck("ping", healthz.Ping); err != nil {
setupLog.Error(err, "unable to create health check")
os.Exit(1)
}
}
func main() {
var watchNamespace string
var metricsAddr string
var enableLeaderElection bool
var devLogging bool
var runInTestMode bool
var runInDemoMode bool
// From CAPI point of view, BMO should be able to watch all namespaces
// in case of a deployment that is not multi-tenant. If the deployment
// is for multi-tenancy, then the BMO should watch only the provided
// namespace.
flag.StringVar(&watchNamespace, "namespace", os.Getenv("WATCH_NAMESPACE"),
"Namespace that the controller watches to reconcile host resources.")
flag.StringVar(&metricsAddr, "metrics-addr", "127.0.0.1:8085",
"The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.BoolVar(&devLogging, "dev", false, "enable developer logging")
flag.BoolVar(&runInTestMode, "test-mode", false, "disable ironic communication")
flag.BoolVar(&runInDemoMode, "demo-mode", false,
"use the demo provisioner to set host states")
flag.StringVar(&healthAddr, "health-addr", ":9440",
"The address the health endpoint binds to.")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(devLogging)))
printVersion()
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 0, // Add flag with default of 9443 when adding webhooks
LeaderElection: enableLeaderElection,
LeaderElectionID: "baremetal-operator",
LeaderElectionNamespace: watchNamespace,
Namespace: watchNamespace,
HealthProbeBindAddress: healthAddr,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
provisionerFactory := func(host *metal3iov1alpha1.BareMetalHost, bmcCreds bmc.Credentials, publish provisioner.EventPublisher) (provisioner.Provisioner, error) {
isUnmanaged := host.Spec.ExternallyProvisioned && !host.HasBMCDetails()
if runInTestMode {
ctrl.Log.Info("using test provisioner")
return fixture.New(host, bmcCreds, publish)
} else if runInDemoMode {
ctrl.Log.Info("using demo provisioner")
return demo.New(host, bmcCreds, publish)
} else if isUnmanaged {
ctrl.Log.Info("using empty provisioner")
return empty.New(host, bmcCreds, publish)
}
ironic.LogStartup()
return ironic.New(host, bmcCreds, publish)
}
if err = (&metal3iocontroller.BareMetalHostReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("BareMetalHost"),
Scheme: mgr.GetScheme(),
ProvisionerFactory: provisionerFactory,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "BareMetalHost")
os.Exit(1)
}
setupChecks(mgr)
// +kubebuilder:scaffold:builder
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
|
[
"\"WATCH_NAMESPACE\""
] |
[] |
[
"WATCH_NAMESPACE"
] |
[]
|
["WATCH_NAMESPACE"]
|
go
| 1 | 0 | |
mackerel-plugin-aws-elb/aws-elb.go
|
package main
import (
"errors"
"flag"
"log"
"os"
"time"
"github.com/crowdmob/goamz/aws"
"github.com/crowdmob/goamz/cloudwatch"
mp "github.com/mackerelio/go-mackerel-plugin"
)
var graphdef = map[string](mp.Graphs){
"elb.latency": mp.Graphs{
Label: "Whole ELB Latency",
Unit: "float",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "Latency", Label: "Latency"},
},
},
"elb.http_backend": mp.Graphs{
Label: "Whole ELB HTTP Backend Count",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "HTTPCode_Backend_2XX", Label: "2XX", Stacked: true},
mp.Metrics{Name: "HTTPCode_Backend_3XX", Label: "3XX", Stacked: true},
mp.Metrics{Name: "HTTPCode_Backend_4XX", Label: "4XX", Stacked: true},
mp.Metrics{Name: "HTTPCode_Backend_5XX", Label: "5XX", Stacked: true},
},
},
// "elb.healthy_host_count", "elb.unhealthy_host_count" will be generated dynamically
}
type statType int
const (
stAve statType = iota
stSum
)
func (s statType) String() string {
switch s {
case stAve:
return "Average"
case stSum:
return "Sum"
}
return ""
}
// ELBPlugin elb plugin for mackerel
type ELBPlugin struct {
Region string
AccessKeyID string
SecretAccessKey string
AZs []string
CloudWatch *cloudwatch.CloudWatch
Lbname string
}
func (p *ELBPlugin) prepare() error {
auth, err := aws.GetAuth(p.AccessKeyID, p.SecretAccessKey, "", time.Now())
if err != nil {
return err
}
p.CloudWatch, err = cloudwatch.NewCloudWatch(auth, aws.Regions[p.Region].CloudWatchServicepoint)
if err != nil {
return err
}
ret, err := p.CloudWatch.ListMetrics(&cloudwatch.ListMetricsRequest{
Namespace: "AWS/ELB",
Dimensions: []cloudwatch.Dimension{
cloudwatch.Dimension{
Name: "AvailabilityZone",
},
},
MetricName: "HealthyHostCount",
})
if err != nil {
return err
}
p.AZs = make([]string, 0, len(ret.ListMetricsResult.Metrics))
for _, met := range ret.ListMetricsResult.Metrics {
if len(met.Dimensions) > 1 {
continue
} else if met.Dimensions[0].Name != "AvailabilityZone" {
continue
}
p.AZs = append(p.AZs, met.Dimensions[0].Value)
}
return nil
}
func (p ELBPlugin) getLastPoint(dimensions *[]cloudwatch.Dimension, metricName string, sTyp statType) (float64, error) {
now := time.Now()
response, err := p.CloudWatch.GetMetricStatistics(&cloudwatch.GetMetricStatisticsRequest{
Dimensions: *dimensions,
StartTime: now.Add(time.Duration(120) * time.Second * -1), // 2 min (to fetch at least 1 data-point)
EndTime: now,
MetricName: metricName,
Period: 60,
Statistics: []string{sTyp.String()},
Namespace: "AWS/ELB",
})
if err != nil {
return 0, err
}
datapoints := response.GetMetricStatisticsResult.Datapoints
if len(datapoints) == 0 {
return 0, errors.New("fetched no datapoints")
}
latest := time.Unix(0, 0)
var latestVal float64
for _, dp := range datapoints {
if dp.Timestamp.Before(latest) {
continue
}
latest = dp.Timestamp
switch sTyp {
case stAve:
latestVal = dp.Average
case stSum:
latestVal = dp.Sum
}
}
return latestVal, nil
}
// FetchMetrics fetch elb metrics
func (p ELBPlugin) FetchMetrics() (map[string]float64, error) {
stat := make(map[string]float64)
// HostCount per AZ
for _, az := range p.AZs {
d := []cloudwatch.Dimension{
cloudwatch.Dimension{
Name: "AvailabilityZone",
Value: az,
},
}
if p.Lbname != "" {
d2 := cloudwatch.Dimension{
Name: "LoadBalancerName",
Value: p.Lbname,
}
d = append(d, d2)
}
for _, met := range []string{"HealthyHostCount", "UnHealthyHostCount"} {
v, err := p.getLastPoint(&d, met, stAve)
if err == nil {
stat[met+"_"+az] = v
}
}
}
glb := []cloudwatch.Dimension{
cloudwatch.Dimension{
Name: "Service",
Value: "ELB",
},
}
if p.Lbname != "" {
g2 := cloudwatch.Dimension{
Name: "LoadBalancerName",
Value: p.Lbname,
}
glb = append(glb, g2)
}
v, err := p.getLastPoint(&glb, "Latency", stAve)
if err == nil {
stat["Latency"] = v
}
for _, met := range [...]string{"HTTPCode_Backend_2XX", "HTTPCode_Backend_3XX", "HTTPCode_Backend_4XX", "HTTPCode_Backend_5XX"} {
v, err := p.getLastPoint(&glb, met, stSum)
if err == nil {
stat[met] = v
}
}
return stat, nil
}
// GraphDefinition for Mackerel
func (p ELBPlugin) GraphDefinition() map[string](mp.Graphs) {
for _, grp := range [...]string{"elb.healthy_host_count", "elb.unhealthy_host_count"} {
var namePre string
var label string
switch grp {
case "elb.healthy_host_count":
namePre = "HealthyHostCount_"
label = "ELB Healthy Host Count"
case "elb.unhealthy_host_count":
namePre = "UnHealthyHostCount_"
label = "ELB Unhealthy Host Count"
}
var metrics [](mp.Metrics)
for _, az := range p.AZs {
metrics = append(metrics, mp.Metrics{Name: namePre + az, Label: az, Stacked: true})
}
graphdef[grp] = mp.Graphs{
Label: label,
Unit: "integer",
Metrics: metrics,
}
}
return graphdef
}
func main() {
optRegion := flag.String("region", "", "AWS Region")
optLbname := flag.String("lbname", "", "ELB Name")
optAccessKeyID := flag.String("access-key-id", "", "AWS Access Key ID")
optSecretAccessKey := flag.String("secret-access-key", "", "AWS Secret Access Key")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
var elb ELBPlugin
if *optRegion == "" {
elb.Region = aws.InstanceRegion()
} else {
elb.Region = *optRegion
}
elb.AccessKeyID = *optAccessKeyID
elb.SecretAccessKey = *optSecretAccessKey
elb.Lbname = *optLbname
err := elb.prepare()
if err != nil {
log.Fatalln(err)
}
helper := mp.NewMackerelPlugin(elb)
if *optTempfile != "" {
helper.Tempfile = *optTempfile
} else {
helper.Tempfile = "/tmp/mackerel-plugin-elb"
}
if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
helper.OutputDefinitions()
} else {
helper.OutputValues()
}
}
|
[
"\"MACKEREL_AGENT_PLUGIN_META\""
] |
[] |
[
"MACKEREL_AGENT_PLUGIN_META"
] |
[]
|
["MACKEREL_AGENT_PLUGIN_META"]
|
go
| 1 | 0 | |
plugins/inputs/prometheus_scraper/start.go
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
// The following code is based on Prometheus project https://github.com/prometheus/prometheus/blob/master/cmd/prometheus/main.go
// and we did modification to remove the logic related to flag handling, Rule manager, TSDB, Web handler, and Notifier.
// Copyright 2015 The Prometheus 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 prometheus_scraper
import (
"context"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/oklog/run"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/version"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery"
sdConfig "github.com/prometheus/prometheus/discovery/config"
"github.com/prometheus/prometheus/pkg/relabel"
promRuntime "github.com/prometheus/prometheus/pkg/runtime"
"github.com/prometheus/prometheus/scrape"
"github.com/prometheus/prometheus/storage"
"k8s.io/klog"
)
var (
configSuccess = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "prometheus_config_last_reload_successful",
Help: "Whether the last configuration reload attempt was successful.",
})
configSuccessTime = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "prometheus_config_last_reload_success_timestamp_seconds",
Help: "Timestamp of the last successful configuration reload.",
})
)
func init() {
prometheus.MustRegister(version.NewCollector("prometheus"))
}
func Start(configFilePath string, receiver storage.Appendable, shutDownChan chan interface{}, wg *sync.WaitGroup, mth *metricsTypeHandler) {
infoLevel := &promlog.AllowedLevel{}
_ = infoLevel.Set("info")
if os.Getenv("DEBUG") != "" {
runtime.SetBlockProfileRate(20)
runtime.SetMutexProfileFraction(20)
_ = infoLevel.Set("debug")
}
logFormat := &promlog.AllowedFormat{}
_ = logFormat.Set("logfmt")
cfg := struct {
configFile string
promlogConfig promlog.Config
}{
promlogConfig: promlog.Config{Level: infoLevel, Format: logFormat},
}
cfg.configFile = configFilePath
logger := promlog.New(&cfg.promlogConfig)
//stdlog.SetOutput(log.NewStdlibAdapter(logger))
//stdlog.Println("redirect std log")
// Above level 6, the k8s client would log bearer tokens in clear-text.
klog.ClampLevel(6)
klog.SetLogger(log.With(logger, "component", "k8s_client_runtime"))
level.Info(logger).Log("msg", "Starting Prometheus", "version", version.Info())
level.Info(logger).Log("build_context", version.BuildContext())
level.Info(logger).Log("host_details", promRuntime.Uname())
level.Info(logger).Log("fd_limits", promRuntime.FdLimits())
level.Info(logger).Log("vm_limits", promRuntime.VmLimits())
var (
ctxScrape, cancelScrape = context.WithCancel(context.Background())
discoveryManagerScrape = discovery.NewManager(ctxScrape, log.With(logger, "component", "discovery manager scrape"), discovery.Name("scrape"))
scrapeManager = scrape.NewManager(log.With(logger, "component", "scrape manager"), receiver)
)
mth.SetScrapeManager(scrapeManager)
var reloaders = []func(cfg *config.Config) error{
// The Scrape and notifier managers need to reload before the Discovery manager as
// they need to read the most updated config when receiving the new targets list.
scrapeManager.ApplyConfig,
func(cfg *config.Config) error {
c := make(map[string]sdConfig.ServiceDiscoveryConfig)
for _, v := range cfg.ScrapeConfigs {
c[v.JobName] = v.ServiceDiscoveryConfig
}
return discoveryManagerScrape.ApplyConfig(c)
},
}
prometheus.MustRegister(configSuccess)
prometheus.MustRegister(configSuccessTime)
// sync.Once is used to make sure we can close the channel at different execution stages(SIGTERM or when the config is loaded).
type closeOnce struct {
C chan struct{}
once sync.Once
Close func()
}
// Wait until the server is ready to handle reloading.
reloadReady := &closeOnce{
C: make(chan struct{}),
}
reloadReady.Close = func() {
reloadReady.once.Do(func() {
close(reloadReady.C)
})
}
var g run.Group
{
// Termination handler.
cancel := make(chan struct{})
g.Add(
func() error {
// Don't forget to release the reloadReady channel so that waiting blocks can exit normally.
select {
case <-shutDownChan:
level.Warn(logger).Log("msg", "Received ShutDown, exiting gracefully...")
reloadReady.Close()
case <-cancel:
reloadReady.Close()
break
}
return nil
},
func(err error) {
close(cancel)
},
)
}
{
// Scrape discovery manager.
g.Add(
func() error {
err := discoveryManagerScrape.Run()
level.Info(logger).Log("msg", "Scrape discovery manager stopped")
return err
},
func(err error) {
level.Info(logger).Log("msg", "Stopping scrape discovery manager...")
cancelScrape()
},
)
}
{
// Scrape manager.
g.Add(
func() error {
// When the scrape manager receives a new targets list
// it needs to read a valid config for each job.
// It depends on the config being in sync with the discovery manager so
// we wait until the config is fully loaded.
<-reloadReady.C
level.Info(logger).Log("msg", "start discovery")
err := scrapeManager.Run(discoveryManagerScrape.SyncCh())
level.Info(logger).Log("msg", "Scrape manager stopped")
return err
},
func(err error) {
// Scrape manager needs to be stopped before closing the local TSDB
// so that it doesn't try to write samples to a closed storage.
level.Info(logger).Log("msg", "Stopping scrape manager...")
scrapeManager.Stop()
},
)
}
{
// Reload handler.
// Make sure that sighup handler is registered with a redirect to the channel before the potentially
// long and synchronous tsdb init.
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
cancel := make(chan struct{})
g.Add(
func() error {
<-reloadReady.C
for {
select {
case <-hup:
if err := reloadConfig(cfg.configFile, logger, reloaders...); err != nil {
level.Error(logger).Log("msg", "Error reloading config", "err", err)
}
case <-cancel:
return nil
}
}
},
func(err error) {
// Wait for any in-progress reloads to complete to avoid
// reloading things after they have been shutdown.
cancel <- struct{}{}
},
)
}
{
// Initial configuration loading.
cancel := make(chan struct{})
g.Add(
func() error {
select {
// In case a shutdown is initiated before the dbOpen is released
case <-cancel:
reloadReady.Close()
return nil
default:
}
level.Info(logger).Log("msg", "handling config file")
if err := reloadConfig(cfg.configFile, logger, reloaders...); err != nil {
return errors.Wrapf(err, "error loading config from %q", cfg.configFile)
}
level.Info(logger).Log("msg", "finish handling config file")
reloadReady.Close()
<-cancel
return nil
},
func(err error) {
close(cancel)
},
)
}
if err := g.Run(); err != nil {
level.Error(logger).Log("err", err)
}
level.Info(logger).Log("msg", "See you next time!")
wg.Done()
}
const (
savedScrapeJobLabel = "cwagent_saved_scrape_job"
savedScrapeInstanceLabel = "cwagent_saved_scrape_instance"
savedScrapeNameLabel = "cwagent_saved_scrape_name" // just arbitrary name that end user won't override in relabel config
)
func reloadConfig(filename string, logger log.Logger, rls ...func(*config.Config) error) (err error) {
level.Info(logger).Log("msg", "Loading configuration file", "filename", filename)
defer func() {
if err == nil {
configSuccess.Set(1)
configSuccessTime.SetToCurrentTime()
} else {
configSuccess.Set(0)
}
}()
conf, err := config.LoadFile(filename)
if err != nil {
return errors.Wrapf(err, "couldn't load configuration (--config.file=%q)", filename)
}
// For saving name before relabel
// - __name__ https://github.com/aws/amazon-cloudwatch-agent/issues/190
// - job and instance https://github.com/aws/amazon-cloudwatch-agent/issues/193
for _, scrapeConfig := range conf.ScrapeConfigs {
relabelConfigs := []*relabel.Config{
// job
{
Action: relabel.Replace,
Regex: relabel.MustNewRegexp(".*"), // __address__ is always there, so we will find a match for every job
Replacement: scrapeConfig.JobName, // value is hard coded job name
SourceLabels: model.LabelNames{"__address__"},
TargetLabel: savedScrapeJobLabel, // creates a new magic label
},
// instance
{
Action: relabel.Replace,
Regex: relabel.MustNewRegexp("(.*)"),
Replacement: "$1", // value is actual __address__, i.e. instance if you don't relabel it.
SourceLabels: model.LabelNames{"__address__"},
TargetLabel: savedScrapeInstanceLabel, // creates a new magic label
},
}
// We only got __name__ after scrape, so it's in metric_relabel_configs instead of relabel_configs.
metricRelabelConfigs := []*relabel.Config{
// __name__
{
Action: relabel.Replace,
Regex: relabel.MustNewRegexp("(.*)"),
Replacement: "$1",
TargetLabel: savedScrapeNameLabel,
SourceLabels: model.LabelNames{"__name__"},
},
}
level.Info(logger).Log("msg", "Add extra relabel_configs and metric_relabel_configs to save job, instance and __name__ before user relabel")
// prepend so our relabel rule comes first
scrapeConfig.RelabelConfigs = append(relabelConfigs, scrapeConfig.RelabelConfigs...)
scrapeConfig.MetricRelabelConfigs = append(metricRelabelConfigs, scrapeConfig.MetricRelabelConfigs...)
}
failed := false
for _, rl := range rls {
if err := rl(conf); err != nil {
level.Error(logger).Log("msg", "Failed to apply configuration", "err", err)
failed = true
}
}
if failed {
return errors.Errorf("one or more errors occurred while applying the new configuration (--config.file=%q)", filename)
}
level.Info(logger).Log("msg", "Completed loading of configuration file", "filename", filename)
return nil
}
|
[
"\"DEBUG\""
] |
[] |
[
"DEBUG"
] |
[]
|
["DEBUG"]
|
go
| 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.