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 |
---|---|---|---|---|---|---|---|---|---|---|
cmd/rtr7-safe-update/safeupdate.go
|
// Copyright 2018 Google 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.
// Binary rtr7-safe-update safely updates a router.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"go/build"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/rtr7/tools/internal/updater"
)
var (
updatesDir = flag.String("updates_dir",
"/home/michael/router7/updates/",
"Directory in which a subdirectory with backups, logs, boot/root file system images will be stored")
buildCommand = flag.String("build_command",
`GOARCH=amd64 gokr-packer \
-hostname=router7 \
-overwrite_boot=${GOKR_DIR}/boot.img \
-overwrite_mbr=${GOKR_DIR}/mbr.img \
-overwrite_root=${GOKR_DIR}/root.img \
-kernel_package=github.com/rtr7/kernel \
-firmware_package=github.com/rtr7/kernel \
-gokrazy_pkgs=github.com/gokrazy/gokrazy/cmd/ntp,github.com/gokrazy/gokrazy/cmd/randomd \
-serial_console=ttyS0,115200n8 \
github.com/rtr7/router7/cmd/...`,
"gokr-packer invocation to run (via /bin/sh -c). The GOKR_DIR environment variable is set to the destination directory.")
hostname = flag.String("hostname",
"router7",
"Hostname or IP address to update")
keepOnlyN = flag.Int("keep_only_n",
5,
"Keep only the last N (default 5) updates to conserve disk space. Setting this to -1 keeps all updates forever.")
)
func verifyHealthy() error {
ctx, canc := context.WithTimeout(context.Background(), 2*time.Second)
defer canc()
url := "http://" + *hostname + ":7733/health.json"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if got, want := resp.StatusCode, http.StatusOK; got != want {
return fmt.Errorf("%s: unexpected HTTP status code: got %v, want %v", url, got, want)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("%s: reading body: %v", url, err)
}
var reply struct {
FirstError string `json:"first_error"`
}
if err := json.Unmarshal(b, &reply); err != nil {
return fmt.Errorf("%s: parsing JSON: %v", url, err)
}
if reply.FirstError != "" {
return fmt.Errorf("unhealthy: %v", reply.FirstError)
}
return nil // healthy
}
func latestImage() (string, error) {
f, err := os.Open(*updatesDir)
if err != nil {
return "", err
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return "", err
}
if len(names) < 2 {
return "", fmt.Errorf("no images found in -image_dir=%q", *updatesDir)
}
sort.Slice(names, func(i, j int) bool { return names[i] > names[j] })
for _, name := range names {
if fi, err := os.Stat(filepath.Join(*updatesDir, name, "boot.img")); err != nil || fi.Size() == 0 {
continue
}
if fi, err := os.Stat(filepath.Join(*updatesDir, name, "root.img")); err != nil || fi.Size() == 0 {
continue
}
return name, nil
}
return "", fmt.Errorf("no subdirectory with non-empty boot.img and root.img found in %q", *updatesDir)
}
func keepOnly(n int) error {
if n == -1 {
return nil
}
f, err := os.Open(*updatesDir)
if err != nil {
return err
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return err
}
if len(names) == 0 {
return fmt.Errorf("no images found in -image_dir=%q", *updatesDir)
}
sort.Strings(names)
if len(names) <= n {
return nil // nothing to do
}
for _, name := range names[:len(names)-n] {
fn := filepath.Join(*updatesDir, name)
log.Printf("deleting %s (keeping only the most recent %d updates)", fn, n)
if err := os.RemoveAll(fn); err != nil {
return err
}
}
return nil
}
func storeBackup(dir string) error {
backupfn := filepath.Join(dir, "backup.tar.gz")
log.Printf("downloading backup to %s", backupfn)
url := "http://" + *hostname + ":8077/backup.tar.gz"
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if got, want := resp.StatusCode, http.StatusOK; got != want {
return fmt.Errorf("%s: unexpected HTTP status code: got %v, want %v", url, got, want)
}
f, err := os.Create(backupfn)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, resp.Body); err != nil {
return err
}
return f.Close()
}
func buildImage(dir string) error {
build := exec.Command("/bin/sh", "-c", *buildCommand)
build.Env = append(os.Environ(), "GOKR_DIR="+dir)
build.Stderr = os.Stderr
if err := build.Run(); err != nil {
return fmt.Errorf("%v: %v", build.Args, err)
}
return nil
}
func update(dir string) error {
pwb, err := ioutil.ReadFile(filepath.Join(os.Getenv("HOME"), ".config", "gokrazy", "http-password.txt"))
if err != nil {
return err
}
pw := strings.TrimSpace(string(pwb))
root, err := os.Open(filepath.Join(dir, "root.img"))
if err != nil {
return err
}
defer root.Close()
boot, err := os.Open(filepath.Join(dir, "boot.img"))
if err != nil {
return err
}
defer boot.Close()
mbr, err := os.Open(filepath.Join(dir, "mbr.img"))
if err != nil {
return err
}
defer mbr.Close()
baseUrl := "http://gokrazy:" + pw + "@" + *hostname + "/"
// Start with the root file system because writing to the non-active
// partition cannot break the currently running system.
if err := updater.UpdateRoot(baseUrl, root); err != nil {
return fmt.Errorf("updating root file system: %v", err)
}
if err := updater.UpdateBoot(baseUrl, boot); err != nil {
return fmt.Errorf("updating boot file system: %v", err)
}
if err := updater.UpdateMBR(baseUrl, mbr); err != nil {
return fmt.Errorf("updating MBR: %v", err)
}
if err := updater.Switch(baseUrl); err != nil {
return fmt.Errorf("switching to non-active partition: %v", err)
}
if err := updater.Reboot(baseUrl); err != nil {
return fmt.Errorf("reboot: %v", err)
}
return nil
}
func rollback(latest string) error {
if latest == "" {
return fmt.Errorf("no latest image found")
}
// Figure out the full path so that we can construct a sudo command line
path, err := exec.LookPath("rtr7-recover")
if err != nil {
return err
}
recover := exec.Command("sudo",
"--preserve-env=GOPATH",
path,
"-boot="+filepath.Join(*updatesDir, latest, "boot.img"),
"-root="+filepath.Join(*updatesDir, latest, "root.img"),
"-mbr="+filepath.Join(*updatesDir, latest, "mbr.img"))
recover.Env = append(os.Environ(), "GOPATH="+build.Default.GOPATH)
recover.Stdout = os.Stdout
recover.Stderr = os.Stderr
if err := recover.Run(); err != nil {
return fmt.Errorf("%v: %v", recover.Args, err)
}
return nil
}
func logic() error {
if _, err := os.Stat(*updatesDir); err != nil {
return fmt.Errorf("stat(-updates_dir): %v", err)
}
var buildTimestamp, dir string
if e := os.Getenv("RTR7_SAFE_UPDATE_REEXEC"); e != "" {
buildTimestamp = e
dir = filepath.Join(*updatesDir, buildTimestamp)
} else {
buildTimestamp = time.Now().Format(time.RFC3339) // TODO: pass to gokr-packer
dir = filepath.Join(*updatesDir, buildTimestamp)
if err := os.Mkdir(dir, 0755); err != nil {
return err
}
}
if os.Getenv("RTR7_SAFE_UPDATE_REEXEC") == "" {
log.Printf("redirecting output to %s/{stdout,stderr}.log", dir)
stdout, err := os.Create(filepath.Join(dir, "stdout.log"))
if err != nil {
return err
}
defer stdout.Close()
stderr, err := os.Create(filepath.Join(dir, "stderr.log"))
if err != nil {
return err
}
defer stderr.Close()
reexec := exec.Command(os.Args[0], os.Args[1:]...)
reexec.Env = append(os.Environ(), "RTR7_SAFE_UPDATE_REEXEC="+buildTimestamp)
reexec.Stderr = io.MultiWriter(stderr, os.Stderr)
reexec.Stdout = io.MultiWriter(stdout, os.Stdout)
return reexec.Run()
}
log.Printf("flags are set to:")
log.Printf("-updates_dir=%q", *updatesDir)
log.Printf("verifying healthiness")
if err := verifyHealthy(); err != nil {
return err
}
log.Printf("router healthy, proceeding with update")
latest, err := latestImage()
if err != nil {
log.Printf("rollback will not be possible: %v", err)
} else {
log.Printf("latest image: %v", latest)
}
// TODO(later): print a warning if the router is running a different image
// (detect by requesting and comparing a checksum)
if err := storeBackup(dir); err != nil {
return err
}
log.Printf("building images using %s", *buildCommand)
if err := buildImage(dir); err != nil {
return err
}
log.Printf("updating")
if err := update(dir); err != nil {
return err
}
// Wait until gokrazy triggered a reboot and the device actually stops
// responding to health queries. This can take a little while thanks to the
// kernel flushing the cache etc.
log.Printf("awaiting unhealthiness")
start := time.Now()
for time.Since(start) < 30*time.Second {
if err := verifyHealthy(); err != nil {
log.Printf("became unhealthy after %v: %v", time.Since(start), err)
break
}
time.Sleep(1 * time.Second)
continue
}
log.Printf("awaiting healthiness")
start = time.Now()
for time.Since(start) < 2*time.Minute {
if err := verifyHealthy(); err != nil {
log.Printf("unhealthy after %v: %v", time.Since(start), err)
} else {
log.Printf("became healthy after %v", time.Since(start))
break
}
time.Sleep(1 * time.Second)
}
if err := verifyHealthy(); err != nil {
return rollback(latest)
}
recoverFn := filepath.Join(dir, "recover.bash")
recoverScript := fmt.Sprintf(`#!/bin/bash
GOPATH=$(go env GOPATH) sudo --preserve-env=GOPATH $(which rtr7-recover) -boot=boot.img -root=root.img -mbr=mbr.img
`)
if err := ioutil.WriteFile(recoverFn, []byte(recoverScript), 0755); err != nil {
return err
}
log.Printf("recovery script stored in %s", recoverFn)
if err := keepOnly(*keepOnlyN); err != nil {
return err
}
return nil
}
func main() {
flag.Parse()
if err := logic(); err != nil {
log.Fatal(err)
}
}
|
[
"\"HOME\"",
"\"RTR7_SAFE_UPDATE_REEXEC\"",
"\"RTR7_SAFE_UPDATE_REEXEC\""
] |
[] |
[
"RTR7_SAFE_UPDATE_REEXEC",
"HOME"
] |
[]
|
["RTR7_SAFE_UPDATE_REEXEC", "HOME"]
|
go
| 2 | 0 | |
agent/scripts/selfupdate_server/updateVersionAgent.py
|
#!/usr/bin/env python
"""This demonstrates a minimal http upload cgi.
This allows a user to upload up to three files at once.
It is trivial to change the number of files uploaded.
This script has security risks. A user could attempt to fill
a disk partition with endless uploads.
If you have a system open to the public you would obviously want
to limit the size and number of files written to the disk.
"""
import cgi
import cgitb; cgitb.enable()
import os
import json
import sys
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
UPLOAD_DIR = "/domain/apache2/htdocs/agent_updates"
HTML_TEMPLATE = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head><body><h1>File Upload</h1>
<form action="%(SCRIPT_NAME)s" method="POST" enctype="multipart/form-data">
Version: <input name="agent_version" type="text"><br>
Agent Cronus Package: <input name="agent_cronus" type="file"><br>
Agent Cronus Prop: <input name="agent_prop" type="file"><br>
Agent Config Cronus Package: <input name="agent_config_cronus" type="file"><br>
Agent Config Cronus Prop: <input name="agent_config_prop" type="file"><br>
<input name="submit" type="submit">
</form>
</body>
</html>"""
def print_html_form (description = None):
"""This prints out the html form. Note that the action is set to
the name of the script which makes this is a self-posting form.
In other words, this cgi both displays a form and processes it.
"""
print "content-type: text/html\n"
if description: print "%s" % description
print HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']}
def save_uploaded_file (form_fields, upload_dir):
"""This saves a file uploaded by an HTML form.
The form_field is the name of the file input field from the form.
For example, the following form_field would be "file_1":
<input name="file_1" type="file">
The upload_dir is the directory where the file will be written.
If no file was uploaded or if the field does not exist then
this does nothing.
"""
description = None
form = cgi.FieldStorage()
if not form.has_key('agent_version'): return description
version = form['agent_version'].value
path = os.path.join(UPLOAD_DIR, version)
if not os.path.exists(path):
os.mkdir(path, 0755)
for form_field in form_fields:
if not form.has_key(form_field): continue
fileitem = form[form_field]
if not fileitem.file: continue
if not fileitem.filename: continue
with file (os.path.join(path, fileitem.filename), 'wb') as fout:
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
description = '%s%s uploaded\n' % (description, fileitem.filename)
return description
description = save_uploaded_file (["agent_cronus","agent_prop","agent_config_cronus","agent_config_prop"], UPLOAD_DIR)
print_html_form (description)
|
[] |
[] |
[
"SCRIPT_NAME"
] |
[]
|
["SCRIPT_NAME"]
|
python
| 1 | 0 | |
scripts/import.py
|
from api.db import PostgresPoolWrapper, update_course_sections
import os
import sys
from api.parser.sis import SIS
from api.parser.registrar import Registrar
if len(sys.argv) == 1:
print("Pass semester ids to import as command line arguments")
exit(1)
postgres_pool = PostgresPoolWrapper(
postgres_dsn=os.environ["POSTGRES_DSN"])
postgres_pool.init()
conn = next(postgres_pool.get_conn())
sis = SIS(os.environ["SIS_RIN"], os.environ["SIS_PIN"], )
if sis.login():
print("Logged in to SIS")
for semester_id in sys.argv[1:]:
period_types = Registrar.parse_period_types(semester_id)
print("Importing schedule for", semester_id)
course_sections = sis.fetch_course_sections(
semester_id, period_types=period_types)
update_course_sections(conn, semester_id, course_sections)
else:
print("Failed to log into SIS")
exit(1)
|
[] |
[] |
[
"SIS_RIN",
"SIS_PIN",
"POSTGRES_DSN"
] |
[]
|
["SIS_RIN", "SIS_PIN", "POSTGRES_DSN"]
|
python
| 3 | 0 | |
src/test/python/apache/aurora/executor/test_thermos_task_runner.py
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import contextlib
import getpass
import os
import subprocess
import sys
import tempfile
import time
from twitter.common import log
from twitter.common.contextutil import temporary_dir
from twitter.common.dirutil import safe_rmtree
from twitter.common.log.options import LogOptions
from twitter.common.quantity import Amount, Time
from apache.aurora.config.schema.base import MB, MesosTaskInstance, Process, Resources, Task
from apache.aurora.executor.common.sandbox import DirectorySandbox
from apache.aurora.executor.common.status_checker import ExitState
from apache.aurora.executor.thermos_task_runner import ThermosTaskRunner
TASK = MesosTaskInstance(
instance=0,
role=getpass.getuser(),
task=Task(
resources=Resources(cpu=1.0, ram=16 * MB, disk=32 * MB),
name='hello_world',
processes=[
Process(name='hello_world', cmdline='{{command}}')
],
)
)
class TestThermosTaskRunnerIntegration(object):
PANTS_BUILT = False
LOG_DIR = None
@classmethod
def setup_class(cls):
cls.LOG_DIR = tempfile.mkdtemp()
LogOptions.set_log_dir(cls.LOG_DIR)
LogOptions.set_disk_log_level('DEBUG')
log.init('executor_logger')
if not cls.PANTS_BUILT and 'SKIP_PANTS_BUILD' not in os.environ:
assert subprocess.call(["./pants",
"src/main/python/apache/aurora/executor/bin:thermos_runner"]) == 0
cls.PANTS_BUILT = True
@classmethod
def teardown_class(cls):
if 'THERMOS_DEBUG' not in os.environ:
safe_rmtree(cls.LOG_DIR)
else:
print('Saving executor logs in %s' % cls.LOG_DIR)
@contextlib.contextmanager
def yield_runner(self, runner_class, **bindings):
with contextlib.nested(temporary_dir(), temporary_dir()) as (td1, td2):
sandbox = DirectorySandbox(td1)
checkpoint_root = td2
task_runner = runner_class(
runner_pex=os.path.join('dist', 'thermos_runner.pex'),
task_id='hello_world',
task=TASK.bind(**bindings).task(),
role=getpass.getuser(),
portmap={},
sandbox=sandbox,
checkpoint_root=checkpoint_root,
)
yield task_runner
def yield_sleepy(self, runner_class, sleep, exit_code):
return self.yield_runner(
runner_class,
command='sleep {{__sleep}} && exit {{__exit_code}}',
__sleep=sleep,
__exit_code=exit_code)
def run_to_completion(self, runner, max_wait=Amount(10, Time.SECONDS)):
poll_interval = Amount(100, Time.MILLISECONDS)
total_time = Amount(0, Time.SECONDS)
while runner.status is None and total_time < max_wait:
total_time += poll_interval
time.sleep(poll_interval.as_(Time.SECONDS))
def test_integration_success(self):
with self.yield_sleepy(ThermosTaskRunner, sleep=0, exit_code=0) as task_runner:
task_runner.start()
task_runner.forked.wait()
self.run_to_completion(task_runner)
assert task_runner.status is not None
assert task_runner.status.status == ExitState.FINISHED
# no-op
task_runner.stop()
assert task_runner.status is not None
assert task_runner.status.status == ExitState.FINISHED
def test_integration_failed(self):
with self.yield_sleepy(ThermosTaskRunner, sleep=0, exit_code=1) as task_runner:
task_runner.start()
task_runner.forked.wait()
self.run_to_completion(task_runner)
assert task_runner.status is not None
assert task_runner.status.status == ExitState.FAILED
# no-op
task_runner.stop()
assert task_runner.status is not None
assert task_runner.status.status == ExitState.FAILED
def test_integration_stop(self):
with self.yield_sleepy(ThermosTaskRunner, sleep=1000, exit_code=0) as task_runner:
task_runner.start()
task_runner.forked.wait()
assert task_runner.status is None
task_runner.stop()
assert task_runner.status is not None
assert task_runner.status.status == ExitState.KILLED
def test_integration_lose(self):
with self.yield_sleepy(ThermosTaskRunner, sleep=1000, exit_code=0) as task_runner:
task_runner.start()
task_runner.forked.wait()
assert task_runner.status is None
task_runner.lose()
task_runner.stop()
assert task_runner.status is not None
assert task_runner.status.status == ExitState.LOST
def test_integration_quitquitquit(self):
ignorant_script = ';'.join([
'import time, signal',
'signal.signal(signal.SIGTERM, signal.SIG_IGN)',
'time.sleep(1000)'
])
class ShortPreemptionThermosTaskRunner(ThermosTaskRunner):
THERMOS_PREEMPTION_WAIT = Amount(1, Time.SECONDS)
with self.yield_runner(
ShortPreemptionThermosTaskRunner,
command="%s -c '%s'" % (sys.executable, ignorant_script)) as task_runner:
task_runner.start()
task_runner.forked.wait()
task_runner.stop(timeout=Amount(5, Time.SECONDS))
assert task_runner.status is not None
assert task_runner.status.status == ExitState.KILLED
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
models/base.go
|
package models
import (
"context"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"os"
"time"
)
var db *mongo.Database
func init() {
e := godotenv.Load()
if e != nil {
fmt.Print(e)
}
dbAddress := os.Getenv("database_url")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, _ := mongo.Connect(ctx, options.Client().ApplyURI(dbAddress))
db = client.Database("testing")
}
func GetDB() *mongo.Database {
return db
}
|
[
"\"database_url\""
] |
[] |
[
"database_url"
] |
[]
|
["database_url"]
|
go
| 1 | 0 | |
setup/authorization.py
|
import urllib.parse
from urllib.parse import parse_qs
from dotenv import load_dotenv, find_dotenv
import requests
import base64
import os
load_dotenv(find_dotenv())
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
REDIRECT_URI = os.environ.get("REDIRECT_URI")
OAUTH_AUTHORIZE_URL = "https://accounts.spotify.com/authorize"
OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
SCOPE = "user-library-read playlist-modify-public playlist-modify-private playlist-read-private playlist-read-collaborative"
def get_auth_url():
payload = {
"client_id": CLIENT_ID,
"response_type": "code",
"redirect_uri": REDIRECT_URI,
"scope": SCOPE
}
urlparams = urllib.parse.urlencode(payload)
return ("%s?%s" % (OAUTH_AUTHORIZE_URL, urlparams))
def get_refresh_token(code):
payload = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI
}
encoded_client = base64.b64encode((CLIENT_ID + ":" + CLIENT_SECRET).encode('ascii'))
headers = {"Authorization": "Basic %s" % encoded_client.decode('ascii')}
response = requests.post(OAUTH_TOKEN_URL, data=payload, headers=headers)
return response.json()['refresh_token']
def authorization():
if CLIENT_ID is None or CLIENT_SECRET is None or REDIRECT_URI is None:
print("Environment variables have not been loaded!")
return
print("Open this link in your browser: %s \n" % get_auth_url() )
redirected_url = input("Enter URL you was redirected to (after accepting authorization): ")
parsed_url = urllib.parse.urlparse(redirected_url)
code = parse_qs(parsed_url.query)['code'][0]
refresh_token = get_refresh_token(code)
print("\n Your refresh token is: %s" % refresh_token)
authorization()
|
[] |
[] |
[
"REDIRECT_URI",
"CLIENT_SECRET",
"CLIENT_ID"
] |
[]
|
["REDIRECT_URI", "CLIENT_SECRET", "CLIENT_ID"]
|
python
| 3 | 0 | |
cmd/pk4-replace/main.go
|
// Program pk4-replace builds the sources in the current directory using sbuild,
// then replaces the subset of currently installed binary packages with the
// newly built packages.
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"pault.ag/go/debian/changelog"
"pault.ag/go/debian/control"
)
// errDryRun is a sentinel used when regular control flow is aborted because a
// dry-run was requested.
var errDryRun = errors.New("dry run requested")
type invocation struct {
configDir string
buildCommand []string
dist string
dryRun bool
}
func (i *invocation) build() (changesFile string, _ error) {
pr, pw, err := os.Pipe()
if err != nil {
return "", err
}
sbuild := exec.Command(i.buildCommand[0], i.buildCommand[1:]...)
if i.dist != "" {
sbuild.Args = append(sbuild.Args, "-d", i.dist)
}
log.Printf("Building package using %q", sbuild.Args)
if i.dryRun {
return "", errDryRun
}
ts := time.Now().UTC().Format("2006-01-02T15:04:05Z") // like sbuild
latest, err := changelog.ParseFileOne("debian/changelog")
if err != nil {
return "", err
}
prefix := fmt.Sprintf("%s_%s", latest.Source, latest.Version)
stderr, err := os.Create("../" + prefix + "-" + ts + ".stderr")
if err != nil {
return "", err
}
defer stderr.Close()
sbuild.Stderr = stderr
stdout, err := os.Create("../" + prefix + "-" + ts + ".stdout")
if err != nil {
return "", err
}
defer stdout.Close()
sbuild.Stdout = stdout
sbuild.ExtraFiles = []*os.File{pw} // populates fd 3
if err := sbuild.Run(); err != nil {
return "", err
}
if err := pw.Close(); err != nil {
return "", err
}
// NOTE: we can only do the read this late because we assume the pipe never
// fills its buffer. Given that we are just printing a file path to it,
// filling the buffer seems very unlikely.
b, err := ioutil.ReadAll(pr)
return strings.TrimSpace(string(b)), err
}
// packagesToReplace finds out which binary packages of the just-built binary
// packages are currently installed on the system and returns the paths to their
// intended replacement .deb files.
func (i *invocation) packagesToReplace(changesFile string) ([]string, error) {
changes, err := control.ParseChangesFile(changesFile)
if err != nil {
return nil, err
}
args := []string{"-f", "${db:Status-Status} ${Package}_\n", "--show"}
query := exec.Command("dpkg-query", append(args, changes.Binaries...)...)
out, err := query.Output()
if err != nil {
if _, ok := err.(*exec.ExitError); !ok {
return nil, err
}
// exec.ExitError is okay, dpkg-query still returns partial output.
}
var prefixes []string
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if strings.HasPrefix(line, "installed ") {
prefixes = append(prefixes, strings.TrimPrefix(line, "installed "))
}
}
filenames := make([]string, 0, len(changes.Files))
// This approach is O(n²), but n is small.
for _, f := range changes.Files {
if !strings.HasSuffix(f.Filename, ".deb") {
continue
}
for _, prefix := range prefixes {
if !strings.HasPrefix(f.Filename, prefix) {
continue
}
filenames = append(filenames, f.Filename)
break
}
}
return filenames, nil
}
func (i *invocation) logic() error {
changesFile, err := i.build()
if err != nil {
if err == errDryRun {
return nil
}
return err
}
pkgs, err := i.packagesToReplace(changesFile)
if err != nil {
return err
}
dir := filepath.Dir(changesFile)
args := make([]string, len(pkgs))
for i, pkg := range pkgs {
args[i] = filepath.Join(dir, pkg)
}
install := exec.Command("sudo", append([]string{"dpkg", "-i"}, args...)...)
log.Printf("Installing replacement packages using %q", install.Args)
install.Stdout = os.Stdout
install.Stderr = os.Stderr
return install.Run()
}
func (i *invocation) readConfig(configPath string) error {
b, err := ioutil.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
var config struct {
BuildCommand []string `control:"Build-Command" delim:"\n" strip:"\n\r\t "`
Dist string `control:"Dist"`
}
if err := control.Unmarshal(&config, bytes.NewReader(b)); err != nil {
return err
}
log.Printf("read config from %s: %+v", configPath, config)
if len(config.BuildCommand) > 0 {
i.buildCommand = config.BuildCommand
}
if config.Dist != "" {
i.dist = config.Dist
}
return nil
}
func resolveTilde(s string) string {
if !strings.HasPrefix(s, "~") {
return s
}
// We need logic to resolve paths with a tilde prefix: bash passes such
// paths unexpanded.
homedir := os.Getenv("HOME")
if homedir == "" {
log.Fatalf("Cannot resolve path %q: environment variable $HOME empty", s)
}
return filepath.Join(homedir, strings.TrimPrefix(s, "~"))
}
func main() {
i := invocation{
buildCommand: []string{
"sbuild",
"--post-build-commands",
"echo %SBUILD_CHANGES > /proc/self/fd/3",
"-A",
"--no-clean-source",
"--dpkg-source-opt=--auto-commit",
},
}
flag.BoolVar(&i.dryRun, "dry_run",
false,
"Print the build command and exit")
flag.StringVar(&i.dist, "dist",
"",
"Distribution for the package build. If non-empty, will be passed to sbuild -d")
i.configDir = resolveTilde("~/.config/pk4")
configPath := filepath.Join(i.configDir, "pk4.deb822")
if err := i.readConfig(configPath); err != nil {
log.Fatal(err)
}
flag.Parse()
if err := i.logic(); err != nil {
log.Fatal(err)
}
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
values_test.go
|
package pgx_test
import (
"bytes"
"context"
"net"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDateTranscode(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
dates := []time.Time{
time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1600, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1700, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1800, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(1999, 12, 31, 0, 0, 0, 0, time.UTC),
time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(2001, 1, 2, 0, 0, 0, 0, time.UTC),
time.Date(2004, 2, 29, 0, 0, 0, 0, time.UTC),
time.Date(2013, 7, 4, 0, 0, 0, 0, time.UTC),
time.Date(2013, 12, 25, 0, 0, 0, 0, time.UTC),
time.Date(2029, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(2081, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(2096, 2, 29, 0, 0, 0, 0, time.UTC),
time.Date(2550, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(9999, 12, 31, 0, 0, 0, 0, time.UTC),
}
for _, actualDate := range dates {
var d time.Time
err := conn.QueryRow(context.Background(), "select $1::date", actualDate).Scan(&d)
if err != nil {
t.Fatalf("Unexpected failure on QueryRow Scan: %v", err)
}
if !actualDate.Equal(d) {
t.Errorf("Did not transcode date successfully: %v is not %v", d, actualDate)
}
}
})
}
func TestTimestampTzTranscode(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
inputTime := time.Date(2013, 1, 2, 3, 4, 5, 6000, time.Local)
var outputTime time.Time
err := conn.QueryRow(context.Background(), "select $1::timestamptz", inputTime).Scan(&outputTime)
if err != nil {
t.Fatalf("QueryRow Scan failed: %v", err)
}
if !inputTime.Equal(outputTime) {
t.Errorf("Did not transcode time successfully: %v is not %v", outputTime, inputTime)
}
})
}
// TODO - move these tests to pgtype
func TestJSONAndJSONBTranscode(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
for _, typename := range []string{"json", "jsonb"} {
if _, ok := conn.ConnInfo().DataTypeForName(typename); !ok {
continue // No JSON/JSONB type -- must be running against old PostgreSQL
}
testJSONString(t, conn, typename)
testJSONStringPointer(t, conn, typename)
}
})
}
func TestJSONAndJSONBTranscodeExtendedOnly(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
for _, typename := range []string{"json", "jsonb"} {
if _, ok := conn.ConnInfo().DataTypeForName(typename); !ok {
continue // No JSON/JSONB type -- must be running against old PostgreSQL
}
testJSONSingleLevelStringMap(t, conn, typename)
testJSONNestedMap(t, conn, typename)
testJSONStringArray(t, conn, typename)
testJSONInt64Array(t, conn, typename)
testJSONInt16ArrayFailureDueToOverflow(t, conn, typename)
testJSONStruct(t, conn, typename)
}
}
func testJSONString(t *testing.T, conn *pgx.Conn, typename string) {
input := `{"key": "value"}`
expectedOutput := map[string]string{"key": "value"}
var output map[string]string
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
return
}
if !reflect.DeepEqual(expectedOutput, output) {
t.Errorf("%s: Did not transcode map[string]string successfully: %v is not %v", typename, expectedOutput, output)
return
}
}
func testJSONStringPointer(t *testing.T, conn *pgx.Conn, typename string) {
input := `{"key": "value"}`
expectedOutput := map[string]string{"key": "value"}
var output map[string]string
err := conn.QueryRow(context.Background(), "select $1::"+typename, &input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
return
}
if !reflect.DeepEqual(expectedOutput, output) {
t.Errorf("%s: Did not transcode map[string]string successfully: %v is not %v", typename, expectedOutput, output)
return
}
}
func testJSONSingleLevelStringMap(t *testing.T, conn *pgx.Conn, typename string) {
input := map[string]string{"key": "value"}
var output map[string]string
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
return
}
if !reflect.DeepEqual(input, output) {
t.Errorf("%s: Did not transcode map[string]string successfully: %v is not %v", typename, input, output)
return
}
}
func testJSONNestedMap(t *testing.T, conn *pgx.Conn, typename string) {
input := map[string]interface{}{
"name": "Uncanny",
"stats": map[string]interface{}{"hp": float64(107), "maxhp": float64(150)},
"inventory": []interface{}{"phone", "key"},
}
var output map[string]interface{}
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
return
}
if !reflect.DeepEqual(input, output) {
t.Errorf("%s: Did not transcode map[string]interface{} successfully: %v is not %v", typename, input, output)
return
}
}
func testJSONStringArray(t *testing.T, conn *pgx.Conn, typename string) {
input := []string{"foo", "bar", "baz"}
var output []string
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
}
if !reflect.DeepEqual(input, output) {
t.Errorf("%s: Did not transcode []string successfully: %v is not %v", typename, input, output)
}
}
func testJSONInt64Array(t *testing.T, conn *pgx.Conn, typename string) {
input := []int64{1, 2, 234432}
var output []int64
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
}
if !reflect.DeepEqual(input, output) {
t.Errorf("%s: Did not transcode []int64 successfully: %v is not %v", typename, input, output)
}
}
func testJSONInt16ArrayFailureDueToOverflow(t *testing.T, conn *pgx.Conn, typename string) {
input := []int{1, 2, 234432}
var output []int16
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err == nil || err.Error() != "can't scan into dest[0]: json: cannot unmarshal number 234432 into Go value of type int16" {
t.Errorf("%s: Expected *json.UnmarkalTypeError, but got %v", typename, err)
}
}
func testJSONStruct(t *testing.T, conn *pgx.Conn, typename string) {
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
input := person{
Name: "John",
Age: 42,
}
var output person
err := conn.QueryRow(context.Background(), "select $1::"+typename, input).Scan(&output)
if err != nil {
t.Errorf("%s: QueryRow Scan failed: %v", typename, err)
}
if !reflect.DeepEqual(input, output) {
t.Errorf("%s: Did not transcode struct successfully: %v is not %v", typename, input, output)
}
}
func mustParseCIDR(t *testing.T, s string) *net.IPNet {
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
t.Fatal(err)
}
return ipnet
}
func TestStringToNotTextTypeTranscode(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
input := "01086ee0-4963-4e35-9116-30c173a8d0bd"
var output string
err := conn.QueryRow(context.Background(), "select $1::uuid", input).Scan(&output)
if err != nil {
t.Fatal(err)
}
if input != output {
t.Errorf("uuid: Did not transcode string successfully: %s is not %s", input, output)
}
err = conn.QueryRow(context.Background(), "select $1::uuid", &input).Scan(&output)
if err != nil {
t.Fatal(err)
}
if input != output {
t.Errorf("uuid: Did not transcode pointer to string successfully: %s is not %s", input, output)
}
})
}
func TestInetCIDRTranscodeIPNet(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
value *net.IPNet
}{
{"select $1::inet", mustParseCIDR(t, "0.0.0.0/32")},
{"select $1::inet", mustParseCIDR(t, "127.0.0.1/32")},
{"select $1::inet", mustParseCIDR(t, "12.34.56.0/32")},
{"select $1::inet", mustParseCIDR(t, "192.168.1.0/24")},
{"select $1::inet", mustParseCIDR(t, "255.0.0.0/8")},
{"select $1::inet", mustParseCIDR(t, "255.255.255.255/32")},
{"select $1::inet", mustParseCIDR(t, "::/128")},
{"select $1::inet", mustParseCIDR(t, "::/0")},
{"select $1::inet", mustParseCIDR(t, "::1/128")},
{"select $1::inet", mustParseCIDR(t, "2607:f8b0:4009:80b::200e/128")},
{"select $1::cidr", mustParseCIDR(t, "0.0.0.0/32")},
{"select $1::cidr", mustParseCIDR(t, "127.0.0.1/32")},
{"select $1::cidr", mustParseCIDR(t, "12.34.56.0/32")},
{"select $1::cidr", mustParseCIDR(t, "192.168.1.0/24")},
{"select $1::cidr", mustParseCIDR(t, "255.0.0.0/8")},
{"select $1::cidr", mustParseCIDR(t, "255.255.255.255/32")},
{"select $1::cidr", mustParseCIDR(t, "::/128")},
{"select $1::cidr", mustParseCIDR(t, "::/0")},
{"select $1::cidr", mustParseCIDR(t, "::1/128")},
{"select $1::cidr", mustParseCIDR(t, "2607:f8b0:4009:80b::200e/128")},
}
for i, tt := range tests {
if conn.PgConn().ParameterStatus("crdb_version") != "" && strings.Contains(tt.sql, "cidr") {
t.Log("Server does not support cidr type (https://github.com/cockroachdb/cockroach/issues/18846)")
continue
}
var actual net.IPNet
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
if actual.String() != tt.value.String() {
t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.value, actual, tt.sql)
}
}
})
}
func TestInetCIDRTranscodeIP(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
value net.IP
}{
{"select $1::inet", net.ParseIP("0.0.0.0")},
{"select $1::inet", net.ParseIP("127.0.0.1")},
{"select $1::inet", net.ParseIP("12.34.56.0")},
{"select $1::inet", net.ParseIP("255.255.255.255")},
{"select $1::inet", net.ParseIP("::1")},
{"select $1::inet", net.ParseIP("2607:f8b0:4009:80b::200e")},
{"select $1::cidr", net.ParseIP("0.0.0.0")},
{"select $1::cidr", net.ParseIP("127.0.0.1")},
{"select $1::cidr", net.ParseIP("12.34.56.0")},
{"select $1::cidr", net.ParseIP("255.255.255.255")},
{"select $1::cidr", net.ParseIP("::1")},
{"select $1::cidr", net.ParseIP("2607:f8b0:4009:80b::200e")},
}
for i, tt := range tests {
if conn.PgConn().ParameterStatus("crdb_version") != "" && strings.Contains(tt.sql, "cidr") {
t.Log("Server does not support cidr type (https://github.com/cockroachdb/cockroach/issues/18846)")
continue
}
var actual net.IP
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
if !actual.Equal(tt.value) {
t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.value, actual, tt.sql)
}
ensureConnValid(t, conn)
}
failTests := []struct {
sql string
value *net.IPNet
}{
{"select $1::inet", mustParseCIDR(t, "192.168.1.0/24")},
{"select $1::cidr", mustParseCIDR(t, "192.168.1.0/24")},
}
for i, tt := range failTests {
var actual net.IP
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err == nil {
t.Errorf("%d. Expected failure but got none", i)
continue
}
ensureConnValid(t, conn)
}
})
}
func TestInetCIDRArrayTranscodeIPNet(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
value []*net.IPNet
}{
{
"select $1::inet[]",
[]*net.IPNet{
mustParseCIDR(t, "0.0.0.0/32"),
mustParseCIDR(t, "127.0.0.1/32"),
mustParseCIDR(t, "12.34.56.0/32"),
mustParseCIDR(t, "192.168.1.0/24"),
mustParseCIDR(t, "255.0.0.0/8"),
mustParseCIDR(t, "255.255.255.255/32"),
mustParseCIDR(t, "::/128"),
mustParseCIDR(t, "::/0"),
mustParseCIDR(t, "::1/128"),
mustParseCIDR(t, "2607:f8b0:4009:80b::200e/128"),
},
},
{
"select $1::cidr[]",
[]*net.IPNet{
mustParseCIDR(t, "0.0.0.0/32"),
mustParseCIDR(t, "127.0.0.1/32"),
mustParseCIDR(t, "12.34.56.0/32"),
mustParseCIDR(t, "192.168.1.0/24"),
mustParseCIDR(t, "255.0.0.0/8"),
mustParseCIDR(t, "255.255.255.255/32"),
mustParseCIDR(t, "::/128"),
mustParseCIDR(t, "::/0"),
mustParseCIDR(t, "::1/128"),
mustParseCIDR(t, "2607:f8b0:4009:80b::200e/128"),
},
},
}
for i, tt := range tests {
if conn.PgConn().ParameterStatus("crdb_version") != "" && strings.Contains(tt.sql, "cidr") {
t.Log("Server does not support cidr type (https://github.com/cockroachdb/cockroach/issues/18846)")
continue
}
var actual []*net.IPNet
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
if !reflect.DeepEqual(actual, tt.value) {
t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.value, actual, tt.sql)
}
ensureConnValid(t, conn)
}
})
}
func TestInetCIDRArrayTranscodeIP(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
value []net.IP
}{
{
"select $1::inet[]",
[]net.IP{
net.ParseIP("0.0.0.0"),
net.ParseIP("127.0.0.1"),
net.ParseIP("12.34.56.0"),
net.ParseIP("255.255.255.255"),
net.ParseIP("2607:f8b0:4009:80b::200e"),
},
},
{
"select $1::cidr[]",
[]net.IP{
net.ParseIP("0.0.0.0"),
net.ParseIP("127.0.0.1"),
net.ParseIP("12.34.56.0"),
net.ParseIP("255.255.255.255"),
net.ParseIP("2607:f8b0:4009:80b::200e"),
},
},
}
for i, tt := range tests {
if conn.PgConn().ParameterStatus("crdb_version") != "" && strings.Contains(tt.sql, "cidr") {
t.Log("Server does not support cidr type (https://github.com/cockroachdb/cockroach/issues/18846)")
continue
}
var actual []net.IP
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
assert.Equal(t, len(tt.value), len(actual), "%d", i)
for j := range actual {
assert.True(t, actual[j].Equal(tt.value[j]), "%d", i)
}
ensureConnValid(t, conn)
}
failTests := []struct {
sql string
value []*net.IPNet
}{
{
"select $1::inet[]",
[]*net.IPNet{
mustParseCIDR(t, "12.34.56.0/32"),
mustParseCIDR(t, "192.168.1.0/24"),
},
},
{
"select $1::cidr[]",
[]*net.IPNet{
mustParseCIDR(t, "12.34.56.0/32"),
mustParseCIDR(t, "192.168.1.0/24"),
},
},
}
for i, tt := range failTests {
var actual []net.IP
err := conn.QueryRow(context.Background(), tt.sql, tt.value).Scan(&actual)
if err == nil {
t.Errorf("%d. Expected failure but got none", i)
continue
}
ensureConnValid(t, conn)
}
})
}
func TestInetCIDRTranscodeWithJustIP(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
value string
}{
{"select $1::inet", "0.0.0.0/32"},
{"select $1::inet", "127.0.0.1/32"},
{"select $1::inet", "12.34.56.0/32"},
{"select $1::inet", "255.255.255.255/32"},
{"select $1::inet", "::/128"},
{"select $1::inet", "2607:f8b0:4009:80b::200e/128"},
{"select $1::cidr", "0.0.0.0/32"},
{"select $1::cidr", "127.0.0.1/32"},
{"select $1::cidr", "12.34.56.0/32"},
{"select $1::cidr", "255.255.255.255/32"},
{"select $1::cidr", "::/128"},
{"select $1::cidr", "2607:f8b0:4009:80b::200e/128"},
}
for i, tt := range tests {
if conn.PgConn().ParameterStatus("crdb_version") != "" && strings.Contains(tt.sql, "cidr") {
t.Log("Server does not support cidr type (https://github.com/cockroachdb/cockroach/issues/18846)")
continue
}
expected := mustParseCIDR(t, tt.value)
var actual net.IPNet
err := conn.QueryRow(context.Background(), tt.sql, expected.IP).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
if actual.String() != expected.String() {
t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.value, actual, tt.sql)
}
ensureConnValid(t, conn)
}
})
}
func TestArrayDecoding(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
tests := []struct {
sql string
query interface{}
scan interface{}
assert func(*testing.T, interface{}, interface{})
}{
{
"select $1::bool[]", []bool{true, false, true}, &[]bool{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]bool))) {
t.Errorf("failed to encode bool[]")
}
},
},
{
"select $1::smallint[]", []int16{2, 4, 484, 32767}, &[]int16{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]int16))) {
t.Errorf("failed to encode smallint[]")
}
},
},
{
"select $1::smallint[]", []uint16{2, 4, 484, 32767}, &[]uint16{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]uint16))) {
t.Errorf("failed to encode smallint[]")
}
},
},
{
"select $1::int[]", []int32{2, 4, 484}, &[]int32{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]int32))) {
t.Errorf("failed to encode int[]")
}
},
},
{
"select $1::int[]", []uint32{2, 4, 484, 2147483647}, &[]uint32{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]uint32))) {
t.Errorf("failed to encode int[]")
}
},
},
{
"select $1::bigint[]", []int64{2, 4, 484, 9223372036854775807}, &[]int64{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]int64))) {
t.Errorf("failed to encode bigint[]")
}
},
},
{
"select $1::bigint[]", []uint64{2, 4, 484, 9223372036854775807}, &[]uint64{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]uint64))) {
t.Errorf("failed to encode bigint[]")
}
},
},
{
"select $1::text[]", []string{"it's", "over", "9000!"}, &[]string{},
func(t *testing.T, query, scan interface{}) {
if !reflect.DeepEqual(query, *(scan.(*[]string))) {
t.Errorf("failed to encode text[]")
}
},
},
{
"select $1::timestamptz[]", []time.Time{time.Unix(323232, 0), time.Unix(3239949334, 00)}, &[]time.Time{},
func(t *testing.T, query, scan interface{}) {
queryTimeSlice := query.([]time.Time)
scanTimeSlice := *(scan.(*[]time.Time))
require.Equal(t, len(queryTimeSlice), len(scanTimeSlice))
for i := range queryTimeSlice {
assert.Truef(t, queryTimeSlice[i].Equal(scanTimeSlice[i]), "%d", i)
}
},
},
{
"select $1::bytea[]", [][]byte{{0, 1, 2, 3}, {4, 5, 6, 7}}, &[][]byte{},
func(t *testing.T, query, scan interface{}) {
queryBytesSliceSlice := query.([][]byte)
scanBytesSliceSlice := *(scan.(*[][]byte))
if len(queryBytesSliceSlice) != len(scanBytesSliceSlice) {
t.Errorf("failed to encode byte[][] to bytea[]: expected %d to equal %d", len(queryBytesSliceSlice), len(scanBytesSliceSlice))
}
for i := range queryBytesSliceSlice {
qb := queryBytesSliceSlice[i]
sb := scanBytesSliceSlice[i]
if !bytes.Equal(qb, sb) {
t.Errorf("failed to encode byte[][] to bytea[]: expected %v to equal %v", qb, sb)
}
}
},
},
}
for i, tt := range tests {
err := conn.QueryRow(context.Background(), tt.sql, tt.query).Scan(tt.scan)
if err != nil {
t.Errorf(`%d. error reading array: %v`, i, err)
continue
}
tt.assert(t, tt.query, tt.scan)
ensureConnValid(t, conn)
}
})
}
func TestEmptyArrayDecoding(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
var val []string
err := conn.QueryRow(context.Background(), "select array[]::text[]").Scan(&val)
if err != nil {
t.Errorf(`error reading array: %v`, err)
}
if len(val) != 0 {
t.Errorf("Expected 0 values, got %d", len(val))
}
var n, m int32
err = conn.QueryRow(context.Background(), "select 1::integer, array[]::text[], 42::integer").Scan(&n, &val, &m)
if err != nil {
t.Errorf(`error reading array: %v`, err)
}
if len(val) != 0 {
t.Errorf("Expected 0 values, got %d", len(val))
}
if n != 1 {
t.Errorf("Expected n to be 1, but it was %d", n)
}
if m != 42 {
t.Errorf("Expected n to be 42, but it was %d", n)
}
rows, err := conn.Query(context.Background(), "select 1::integer, array['test']::text[] union select 2::integer, array[]::text[] union select 3::integer, array['test']::text[]")
if err != nil {
t.Errorf(`error retrieving rows with array: %v`, err)
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&n, &val)
if err != nil {
t.Errorf(`error reading array: %v`, err)
}
}
})
}
func TestPointerPointer(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
skipCockroachDB(t, conn, "Server auto converts ints to bigint and test relies on exact types")
type allTypes struct {
s *string
i16 *int16
i32 *int32
i64 *int64
f32 *float32
f64 *float64
b *bool
t *time.Time
}
var actual, zero, expected allTypes
{
s := "foo"
expected.s = &s
i16 := int16(1)
expected.i16 = &i16
i32 := int32(1)
expected.i32 = &i32
i64 := int64(1)
expected.i64 = &i64
f32 := float32(1.23)
expected.f32 = &f32
f64 := float64(1.23)
expected.f64 = &f64
b := true
expected.b = &b
t := time.Unix(123, 5000)
expected.t = &t
}
tests := []struct {
sql string
queryArgs []interface{}
scanArgs []interface{}
expected allTypes
}{
{"select $1::text", []interface{}{expected.s}, []interface{}{&actual.s}, allTypes{s: expected.s}},
{"select $1::text", []interface{}{zero.s}, []interface{}{&actual.s}, allTypes{}},
{"select $1::int2", []interface{}{expected.i16}, []interface{}{&actual.i16}, allTypes{i16: expected.i16}},
{"select $1::int2", []interface{}{zero.i16}, []interface{}{&actual.i16}, allTypes{}},
{"select $1::int4", []interface{}{expected.i32}, []interface{}{&actual.i32}, allTypes{i32: expected.i32}},
{"select $1::int4", []interface{}{zero.i32}, []interface{}{&actual.i32}, allTypes{}},
{"select $1::int8", []interface{}{expected.i64}, []interface{}{&actual.i64}, allTypes{i64: expected.i64}},
{"select $1::int8", []interface{}{zero.i64}, []interface{}{&actual.i64}, allTypes{}},
{"select $1::float4", []interface{}{expected.f32}, []interface{}{&actual.f32}, allTypes{f32: expected.f32}},
{"select $1::float4", []interface{}{zero.f32}, []interface{}{&actual.f32}, allTypes{}},
{"select $1::float8", []interface{}{expected.f64}, []interface{}{&actual.f64}, allTypes{f64: expected.f64}},
{"select $1::float8", []interface{}{zero.f64}, []interface{}{&actual.f64}, allTypes{}},
{"select $1::bool", []interface{}{expected.b}, []interface{}{&actual.b}, allTypes{b: expected.b}},
{"select $1::bool", []interface{}{zero.b}, []interface{}{&actual.b}, allTypes{}},
{"select $1::timestamptz", []interface{}{expected.t}, []interface{}{&actual.t}, allTypes{t: expected.t}},
{"select $1::timestamptz", []interface{}{zero.t}, []interface{}{&actual.t}, allTypes{}},
}
for i, tt := range tests {
actual = zero
err := conn.QueryRow(context.Background(), tt.sql, tt.queryArgs...).Scan(tt.scanArgs...)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, queryArgs -> %v)", i, err, tt.sql, tt.queryArgs)
}
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("%d. Expected %v, got %v (sql -> %v, queryArgs -> %v)", i, tt.expected, actual, tt.sql, tt.queryArgs)
}
ensureConnValid(t, conn)
}
})
}
func TestPointerPointerNonZero(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
f := "foo"
dest := &f
err := conn.QueryRow(context.Background(), "select $1::text", nil).Scan(&dest)
if err != nil {
t.Errorf("Unexpected failure scanning: %v", err)
}
if dest != nil {
t.Errorf("Expected dest to be nil, got %#v", dest)
}
})
}
func TestEncodeTypeRename(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
type _int int
inInt := _int(1)
var outInt _int
type _int8 int8
inInt8 := _int8(2)
var outInt8 _int8
type _int16 int16
inInt16 := _int16(3)
var outInt16 _int16
type _int32 int32
inInt32 := _int32(4)
var outInt32 _int32
type _int64 int64
inInt64 := _int64(5)
var outInt64 _int64
type _uint uint
inUint := _uint(6)
var outUint _uint
type _uint8 uint8
inUint8 := _uint8(7)
var outUint8 _uint8
type _uint16 uint16
inUint16 := _uint16(8)
var outUint16 _uint16
type _uint32 uint32
inUint32 := _uint32(9)
var outUint32 _uint32
type _uint64 uint64
inUint64 := _uint64(10)
var outUint64 _uint64
type _string string
inString := _string("foo")
var outString _string
err := conn.QueryRow(context.Background(), "select $1::int, $2::int, $3::int2, $4::int4, $5::int8, $6::int, $7::int, $8::int, $9::int, $10::int, $11::text",
inInt, inInt8, inInt16, inInt32, inInt64, inUint, inUint8, inUint16, inUint32, inUint64, inString,
).Scan(&outInt, &outInt8, &outInt16, &outInt32, &outInt64, &outUint, &outUint8, &outUint16, &outUint32, &outUint64, &outString)
if err != nil {
t.Fatalf("Failed with type rename: %v", err)
}
if inInt != outInt {
t.Errorf("int rename: expected %v, got %v", inInt, outInt)
}
if inInt8 != outInt8 {
t.Errorf("int8 rename: expected %v, got %v", inInt8, outInt8)
}
if inInt16 != outInt16 {
t.Errorf("int16 rename: expected %v, got %v", inInt16, outInt16)
}
if inInt32 != outInt32 {
t.Errorf("int32 rename: expected %v, got %v", inInt32, outInt32)
}
if inInt64 != outInt64 {
t.Errorf("int64 rename: expected %v, got %v", inInt64, outInt64)
}
if inUint != outUint {
t.Errorf("uint rename: expected %v, got %v", inUint, outUint)
}
if inUint8 != outUint8 {
t.Errorf("uint8 rename: expected %v, got %v", inUint8, outUint8)
}
if inUint16 != outUint16 {
t.Errorf("uint16 rename: expected %v, got %v", inUint16, outUint16)
}
if inUint32 != outUint32 {
t.Errorf("uint32 rename: expected %v, got %v", inUint32, outUint32)
}
if inUint64 != outUint64 {
t.Errorf("uint64 rename: expected %v, got %v", inUint64, outUint64)
}
if inString != outString {
t.Errorf("string rename: expected %v, got %v", inString, outString)
}
})
}
func TestRowDecodeBinary(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
tests := []struct {
sql string
expected []interface{}
}{
{
"select row(1, 'cat', '2015-01-01 08:12:42-00'::timestamptz)",
[]interface{}{
int32(1),
"cat",
time.Date(2015, 1, 1, 8, 12, 42, 0, time.UTC).Local(),
},
},
{
"select row(100.0::float, 1.09::float)",
[]interface{}{
float64(100),
float64(1.09),
},
},
}
for i, tt := range tests {
var actual []interface{}
err := conn.QueryRow(context.Background(), tt.sql).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v)", i, err, tt.sql)
continue
}
for j := range tt.expected {
assert.EqualValuesf(t, tt.expected[j], actual[j], "%d. [%d]", i, j)
}
ensureConnValid(t, conn)
}
}
// https://github.com/jackc/pgx/issues/810
func TestRowsScanNilThenScanValue(t *testing.T) {
t.Parallel()
testWithAndWithoutPreferSimpleProtocol(t, func(t *testing.T, conn *pgx.Conn) {
sql := `select null as a, null as b
union
select 1, 2
order by a nulls first
`
rows, err := conn.Query(context.Background(), sql)
require.NoError(t, err)
require.True(t, rows.Next())
err = rows.Scan(nil, nil)
require.NoError(t, err)
require.True(t, rows.Next())
var a int
var b int
err = rows.Scan(&a, &b)
require.NoError(t, err)
require.EqualValues(t, 1, a)
require.EqualValues(t, 2, b)
rows.Close()
require.NoError(t, rows.Err())
})
}
func TestScanIntoByteSlice(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
// Success cases
for _, tt := range []struct {
name string
sql string
resultFormatCode int16
output []byte
}{
{"int - text", "select 42", pgx.TextFormatCode, []byte("42")},
{"text - text", "select 'hi'", pgx.TextFormatCode, []byte("hi")},
{"text - binary", "select 'hi'", pgx.BinaryFormatCode, []byte("hi")},
{"json - text", "select '{}'::json", pgx.TextFormatCode, []byte("{}")},
{"json - binary", "select '{}'::json", pgx.BinaryFormatCode, []byte("{}")},
{"jsonb - text", "select '{}'::jsonb", pgx.TextFormatCode, []byte("{}")},
{"jsonb - binary", "select '{}'::jsonb", pgx.BinaryFormatCode, []byte("{}")},
} {
t.Run(tt.name, func(t *testing.T) {
var buf []byte
err := conn.QueryRow(context.Background(), tt.sql, pgx.QueryResultFormats{tt.resultFormatCode}).Scan(&buf)
require.NoError(t, err)
require.Equal(t, tt.output, buf)
})
}
// Failure cases
for _, tt := range []struct {
name string
sql string
err string
}{
{"int binary", "select 42", "can't scan into dest[0]: cannot assign 42 into *[]uint8"},
} {
t.Run(tt.name, func(t *testing.T) {
var buf []byte
err := conn.QueryRow(context.Background(), tt.sql, pgx.QueryResultFormats{pgx.BinaryFormatCode}).Scan(&buf)
require.EqualError(t, err, tt.err)
})
}
}
|
[
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\""
] |
[] |
[
"PGX_TEST_DATABASE"
] |
[]
|
["PGX_TEST_DATABASE"]
|
go
| 1 | 0 | |
core/chaincode/shim/mockstub_test.go
|
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package shim
import (
"encoding/json"
"fmt"
"reflect"
"testing"
"github.com/spf13/viper"
)
func TestMockStateRangeQueryIterator(t *testing.T) {
stub := NewMockStub("rangeTest", nil)
stub.MockTransactionStart("init")
stub.PutState("1", []byte{61})
stub.PutState("0", []byte{62})
stub.PutState("5", []byte{65})
stub.PutState("3", []byte{63})
stub.PutState("4", []byte{64})
stub.PutState("6", []byte{66})
stub.MockTransactionEnd("init")
expectKeys := []string{"3", "4"}
expectValues := [][]byte{{63}, {64}}
rqi := NewMockStateRangeQueryIterator(stub, "2", "4")
fmt.Println("Running loop")
for i := 0; i < 2; i++ {
key, value, err := rqi.Next()
fmt.Println("Loop", i, "got", key, value, err)
if expectKeys[i] != key {
fmt.Println("Expected key", expectKeys[i], "got", key)
t.FailNow()
}
if expectValues[i][0] != value[0] {
fmt.Println("Expected value", expectValues[i], "got", value)
}
}
}
// TestMockStateRangeQueryIterator_openEnded tests running an open-ended query
// for all keys on the MockStateRangeQueryIterator
func TestMockStateRangeQueryIterator_openEnded(t *testing.T) {
stub := NewMockStub("rangeTest", nil)
stub.MockTransactionStart("init")
stub.PutState("1", []byte{61})
stub.PutState("0", []byte{62})
stub.PutState("5", []byte{65})
stub.PutState("3", []byte{63})
stub.PutState("4", []byte{64})
stub.PutState("6", []byte{66})
stub.MockTransactionEnd("init")
rqi := NewMockStateRangeQueryIterator(stub, "", "")
count := 0
for rqi.HasNext() {
rqi.Next()
count++
}
if count != rqi.Stub.Keys.Len() {
t.FailNow()
}
}
// TestSetChaincodeLoggingLevel uses the utlity function defined in chaincode.go to
// set the chaincodeLogger's logging level
func TestSetChaincodeLoggingLevel(t *testing.T) {
// set log level to a non-default level
testLogLevelString := "debug"
viper.Set("logging.chaincode", testLogLevelString)
SetChaincodeLoggingLevel()
if !IsEnabledForLogLevel(testLogLevelString) {
t.FailNow()
}
}
type Marble struct {
ObjectType string `json:"docType"` //docType is used to distinguish the various types of objects in state database
Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around
Color string `json:"color"`
Size int `json:"size"`
Owner string `json:"owner"`
}
// JSONBytesEqual compares the JSON in two byte slices.
func jsonBytesEqual(expected []byte, actual []byte) bool {
var infExpected, infActual interface{}
if err := json.Unmarshal(expected, &infExpected); err != nil {
return false
}
if err := json.Unmarshal(actual, &infActual); err != nil {
return false
}
return reflect.DeepEqual(infActual, infExpected)
}
func TestGetStateByPartialCompositeKey(t *testing.T) {
stub := NewMockStub("GetStateByPartialCompositeKeyTest", nil)
stub.MockTransactionStart("init")
marble1 := &Marble{"marble", "set-1", "red", 5, "tom"}
// Convert marble1 to JSON with Color and Name as composite key
compositeKey1, _ := stub.CreateCompositeKey(marble1.ObjectType, []string{marble1.Name, marble1.Color})
marbleJSONBytes1, _ := json.Marshal(marble1)
// Add marble1 JSON to state
stub.PutState(compositeKey1, marbleJSONBytes1)
marble2 := &Marble{"marble", "set-1", "blue", 5, "jerry"}
compositeKey2, _ := stub.CreateCompositeKey(marble2.ObjectType, []string{marble2.Name, marble2.Color})
marbleJSONBytes2, _ := json.Marshal(marble2)
stub.PutState(compositeKey2, marbleJSONBytes2)
marble3 := &Marble{"marble", "set-2", "red", 5, "tom-jerry"}
compositeKey3, _ := stub.CreateCompositeKey(marble3.ObjectType, []string{marble3.Name, marble3.Color})
marbleJSONBytes3, _ := json.Marshal(marble3)
stub.PutState(compositeKey3, marbleJSONBytes3)
stub.MockTransactionEnd("init")
// should return in sorted order of attributes
expectKeys := []string{compositeKey2, compositeKey1}
expectKeysAttributes := [][]string{{"set-1", "blue"}, {"set-1", "red"}}
expectValues := [][]byte{marbleJSONBytes2, marbleJSONBytes1}
rqi, _ := stub.GetStateByPartialCompositeKey("marble", []string{"set-1"})
fmt.Println("Running loop")
for i := 0; i < 2; i++ {
key, value, err := rqi.Next()
fmt.Println("Loop", i, "got", key, value, err)
if expectKeys[i] != key {
fmt.Println("Expected key", expectKeys[i], "got", key)
t.FailNow()
}
objectType, attributes, _ := stub.SplitCompositeKey(key)
if objectType != "marble" {
fmt.Println("Expected objectType", "marble", "got", objectType)
t.FailNow()
}
fmt.Println(attributes)
for index, attr := range attributes {
if expectKeysAttributes[i][index] != attr {
fmt.Println("Expected keys attribute", expectKeysAttributes[index][i], "got", attr)
t.FailNow()
}
}
if jsonBytesEqual(expectValues[i], value) != true {
fmt.Println("Expected value", expectValues[i], "got", value)
t.FailNow()
}
}
}
func TestGetStateByPartialCompositeKeyCollision(t *testing.T) {
stub := NewMockStub("GetStateByPartialCompositeKeyCollisionTest", nil)
stub.MockTransactionStart("init")
vehicle1Bytes := []byte("vehicle1")
compositeKeyVehicle1, _ := stub.CreateCompositeKey("Vehicle", []string{"VIN_1234"})
stub.PutState(compositeKeyVehicle1, vehicle1Bytes)
vehicleListing1Bytes := []byte("vehicleListing1")
compositeKeyVehicleListing1, _ := stub.CreateCompositeKey("VehicleListing", []string{"LIST_1234"})
stub.PutState(compositeKeyVehicleListing1, vehicleListing1Bytes)
stub.MockTransactionEnd("init")
// Only the single "Vehicle" object should be returned, not the "VehicleListing" object
rqi, _ := stub.GetStateByPartialCompositeKey("Vehicle", []string{})
i := 0
fmt.Println("Running loop")
for rqi.HasNext() {
i++
key, value, err := rqi.Next()
fmt.Println("Loop", i, "got", key, value, err)
}
// Only the single "Vehicle" object should be returned, not the "VehicleListing" object
if i != 1 {
fmt.Println("Expected 1, got", i)
t.FailNow()
}
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
DMOJ/DMOPC/DMOPC_20_C1P2_Victors_Moral_Dilemma.py
|
N, D = map(int, input().split())
ppl = list(map(int, input().split()))
for i in range(D):
n = int(input())
F = sum(ppl[:n])
S = sum(ppl[n:])
if F >= S:
print(F)
ppl = ppl[n:]
elif F < S:
print(S)
ppl = ppl[:n]
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
contrib/spendfrom/spendfrom.py
|
#!/usr/bin/env python
#
# Use the raw transactions API to spend ULTREXs received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a ultrachaintd or ultrachaint-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the ultrachaint data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Ultrachaint/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Ultrachaint")
return os.path.expanduser("~/.ultrachaint")
def read_bitcoin_config(dbdir):
"""Read the ultrachaint.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "ultrachaint.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a ultrachaint JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 24755 if testnet else 23755
connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the ultrachaintd we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(ultrachaintd):
info = ultrachaintd.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
ultrachaintd.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = ultrachaintd.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(ultrachaintd):
address_summary = dict()
address_to_account = dict()
for info in ultrachaintd.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = ultrachaintd.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = ultrachaintd.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-ultrachaint-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(ultrachaintd, fromaddresses, toaddress, amount, fee):
all_coins = list_available(ultrachaintd)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to ultrachaintd.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = ultrachaintd.createrawtransaction(inputs, outputs)
signed_rawtx = ultrachaintd.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(ultrachaintd, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = ultrachaintd.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(ultrachaintd, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = ultrachaintd.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(ultrachaintd, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get ULTREXs from")
parser.add_option("--to", dest="to", default=None,
help="address to get send ULTREXs to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of ultrachaint.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
ultrachaintd = connect_JSON(config)
if options.amount is None:
address_summary = list_available(ultrachaintd)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(ultrachaintd) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(ultrachaintd, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(ultrachaintd, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = ultrachaintd.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
|
[] |
[] |
[
"APPDATA"
] |
[]
|
["APPDATA"]
|
python
| 1 | 0 | |
TranskribusDU/contentProcessing/taggerIEmerge.py
|
# -*- coding: utf-8 -*-
"""
taggerIEmerge.py
task: recognition of multi ouptuts classes
H. Déjean
copyright Naver labs Europe 2018
READ project
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation programme
under grant agreement No 674943.
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import sys,os
from io import open
from optparse import OptionParser
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import confusion_matrix
os.environ['KERAS_BACKEND'] = 'tensorflow'
from keras.models import Sequential, load_model, Model
from keras.layers import Bidirectional, Dropout, Input
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import LSTM
from keras.layers.core import Dense, Masking
from keras.regularizers import L1L2
import numpy as np
import pickle
import gzip
from contentProcessing.attentiondecoder import AttentionDecoder
class Transformer(BaseEstimator, TransformerMixin):
def __init__(self):
BaseEstimator.__init__(self)
TransformerMixin.__init__(self)
def fit(self, l, y=None):
return self
def transform(self, l):
assert False, "Specialize this method!"
class SparseToDense(Transformer):
def __init__(self):
Transformer.__init__(self)
def transform(self, o):
return o.toarray()
class NodeTransformerTextEnclosed(Transformer):
"""
we will get a list of block and need to send back what a textual feature extractor (TfidfVectorizer) needs.
So we return a list of strings
"""
def transform(self, lw):
return map(lambda x: x, lw)
class DeepTagger():
usage = ""
version = "v.01"
description = "description: keras/bilstm ner"
def __init__(self):
self.dirName = None
self.sModelName = None
self.sAux = "aux.pkl"
self.lnbClasses = None
self.max_sentence_len = 0
self.max_features = 100
self.maxngram = 3
self.nbEpochs = 10
self.batch_size = 50
self.hiddenSize= 32
self.bGridSearch = False
self.bTraining_multitype,self.bTraining, self.bTesting, self.bPredict = False,False,False, False
self.lTrain = []
self.lTest = []
self.lPredict= []
self.bAttentionLayer= False
self.bMultiType = False
# mapping vector
self.ltag_vector=[]
def setParams(self,dParams):
"""
"""
if dParams.dirname:
self.dirName = dParams.dirname
if dParams.name:
self.sModelName = dParams.name
if dParams.batchSize:
self.batch_size = dParams.batchSize
if dParams.nbEpochs:
self.nbEpochs = dParams.nbEpochs
if dParams.hidden:
self.hiddenSize = dParams.hidden
if dParams.nbfeatures:
self.max_features = dParams.nbfeatures
if dParams.ngram:
self.maxngram = dParams.ngram
self.bMultiType = dParams.multitype
if dParams.training:
self.lTrain = dParams.training
self.bTraining=True
if dParams.testing:
self.lTest = dParams.testing
self.bTesting=True
if dParams.predict:
self._sent =dParams.predict #.decode('latin-1')
self.bPredict=True
if dParams.attention:
self.bAttentionLayer=True
def initTransformeur(self):
# lowercase = False ?? True by default
self.cv= CountVectorizer( max_features = self.max_features
, analyzer = 'char' ,ngram_range = (1,self.maxngram)
, dtype=np.float64)
self.node_transformer = FeatureUnion([
("ngrams", Pipeline([
('selector', NodeTransformerTextEnclosed()),
('cv', self.cv),
('todense', SparseToDense())
])
)
])
def load_data_Multitype(self,lFName):
"""
load data as training data (x,y)
X Y1 Y2 Y3
Sa B_ABPGermanDateGenerator S_weekDayDateGenerator NoneM
"""
self.lnbClasses = []
self.lClasses = []
nbc = 3
for i in range(0,nbc):
self.lnbClasses.append(0)
self.lClasses.append([])
self.ltag_vector.append({})
lTmp=[]
for fname in lFName:
f=open(fname,encoding='utf-8')
x=[]
iseq = 0
for l in f:
iseq += 1
l = l.strip()
if l[:2] == '# ':continue # comments
if l =='EOS':
lTmp.append(x)
self.max_sentence_len = max(self.max_sentence_len,len(x))
x=[]
iseq = 0
else:
try:
la=l.split('\t')
b1=la[-1]
b2=la[-2]
b3=la[-3]
except ValueError:
#print 'cannot find value and label in: %s'%(l)
continue
assert len(la) != 0
if b1 not in self.lClasses[0]:
self.lClasses[0].append(b1)
if b2 not in self.lClasses[1]:
self.lClasses[1].append(b2)
if b3 not in self.lClasses[2]:
self.lClasses[2].append(b3)
x.append((la[0],(b1,b2,b3)))
if x != []:
lTmp.append(x)
f.close()
for i in [0,1,2]:
self.lnbClasses[i] = len(self.lClasses[i]) + 1
for tag_class_id,b in enumerate(self.lClasses[i]):
one_hot_vec = np.zeros(self.lnbClasses[i], dtype=np.int32)
one_hot_vec[tag_class_id] = 1
self.ltag_vector[i][b] = tuple(one_hot_vec)
self.ltag_vector[i][tuple(one_hot_vec)] = b
# Add nil class
if 'NIL' not in self.ltag_vector[i]:
self.lClasses[i].append('NIL')
one_hot_vec = np.zeros(self.lnbClasses[i], dtype=np.int32)
one_hot_vec[self.lnbClasses[i]-1] = 1
self.ltag_vector[i]['NIL'] = tuple(one_hot_vec)
self.ltag_vector[i][tuple(one_hot_vec)] = 'NIL'
# more than 1 sequence
assert len(lTmp) > 1
# shuffle(lTmp)
lX = []
lY = []
for sample in lTmp:
lX.append(list(map(lambda xy:xy[0],sample)))
lY.append(list(map(lambda xy:xy[1],sample)))
del lTmp
return lX,lY
# def load_data_for_testing_Multitype(self,lFName):
# """
# load data as training data (x,y)
# nbClasses must be known!
# loadModel first!
# """
#
# lTmp=[]
# for fname in lFName:
# f=open(fname,encoding='utf-8')
# x=[]
# for l in f:
# l = l.strip()
# if l[:2] == '# ':continue # comments
# if l =='EOS':
# if x!=[]:
# lTmp.append(x)
# x=[]
# else:
# try:
# la=l.split('\t')
# b1=la[-1].split('_')[0]
# b2=la[-1].split('_')[1]
# except ValueError:
# print('ml:cannot find value and label in: %s'%(l))
# sys.exit()
# assert len(la) != 0
# x.append((la[0],(b1,b2)))
#
# if x != []:
# lTmp.append(x)
# f.close()
#
# lX = []
# lY = []
# for sample in lTmp:
# lX.append(list(map(lambda xy:xy[0],sample)))
# lY.append(list(map(lambda xy:xy[1],sample)))
#
# del lTmp
#
# return lX,lY
def storeModel(self,model, aux):
"""
store model and auxillary data (transformer)
"""
model.save('%s/%s.hd5'%(self.dirName,self.sModelName))
print('model dumped in %s/%s.hd5' % (self.dirName,self.sModelName))
#max_features,max_sentence_len, self.nbClasses,self.tag_vector , node_transformer
pickle.dump((self.bMultiType,self.maxngram,self.max_features,self.max_sentence_len,self.lnbClasses,self.ltag_vector,self.node_transformer),gzip.open('%s/%s.%s'%(self.dirName,self.sModelName,self.sAux),'wb'))
print('aux data dumped in %s/%s.%s' % (self.dirName,self.sModelName,self.sAux))
def loadModels(self):
"""
load models and aux data
"""
if self.bAttentionLayer:
self.model = load_model(os.path.join(self.dirName,self.sModelName+'.hd5'),custom_objects={"AttentionDecoder": AttentionDecoder})
else:
self.model = load_model(os.path.join(self.dirName,self.sModelName+'.hd5'))
print('model loaded: %s/%s.hd5' % (self.dirName,self.sModelName))
try:
self.bMultiType,self.maxngram,self.max_features,self.max_sentence_len, self.lnbClasses,self.ltag_vector , self.node_transformer = pickle.load(gzip.open('%s/%s.%s'%(self.dirName,self.sModelName,self.sAux),'r'))
except:
self.maxngram,self.max_features,self.max_sentence_len, self.lnbClasses,self.ltag_vector , self.node_transformer = pickle.load(gzip.open('%s/%s.%s'%(self.dirName,self.sModelName,self.sAux),'r'))
self.bMultiType = False
print('aux data loaded: %s/%s.%s' % (self.dirName,self.sModelName,self.sAux))
print("ngram: %s\tmaxfea=%s\tpadding=%s\tnbclasses=%s" % (self.maxngram,self.max_features,self.max_sentence_len, self.lnbClasses))
print("multitype model:%s"%(self.bMultiType))
def training_multitype(self,traindata):
"""
training
"""
train_X,_ = traindata #self.load_data(self.lTrain)
self.initTransformeur()
fX= [item for sublist in train_X for item in sublist ]
self.node_transformer.fit(fX)
#
lX,(lY,lY2,lY3) = self.prepareTensor_multitype(traindata)
# print (lX.shape)
# print (lY.shape)
# print (lY2.shape)
inputs = Input(shape=(self.max_sentence_len, self.max_features))
x = Masking(mask_value=0)(inputs)
x = Bidirectional(LSTM(self.hiddenSize,return_sequences = True, dropout=0.5), merge_mode='concat')(x)
# x = TimeDistributed(Dense(self.lnbClasses[0], activation='softmax'))(x)
out1 = TimeDistributed(Dense(self.lnbClasses[0], activation='softmax'),name='M')(x)
out2 = TimeDistributed(Dense(self.lnbClasses[1], activation='softmax'),name='spec')(x)
out3 = TimeDistributed(Dense(self.lnbClasses[2], activation='softmax'),name='gen')(x)
model = Model(input = inputs,output = [out1,out2,out3])
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',metrics=['categorical_accuracy'] )
print (model.summary())
_ = model.fit(lX, [lY,lY2,lY3], epochs = self.nbEpochs,batch_size = self.batch_size, verbose = 1,validation_split = 0.1, shuffle=True)
del lX,lY,lY2,lY3
auxdata = self.max_features,self.max_sentence_len,self.lnbClasses,self.ltag_vector,self.node_transformer
return model, auxdata
def prepareTensor_multitype(self,annotated):
lx,ly = annotated
lX = list()
lY1 = list()
lY2 = list()
lY3 = list()
# = np.array()
for x,y in zip(lx,ly):
words = self.node_transformer.transform(x)
wordsvec = []
elem_tags1 = []
elem_tags2 = []
elem_tags3 = []
for ix,ss in enumerate(words):
wordsvec.append(ss)
elem_tags1.append(list(self.ltag_vector[0][y[ix][0]]))
elem_tags2.append(list(self.ltag_vector[1][y[ix][1]]))
elem_tags3.append(list(self.ltag_vector[2][y[ix][2]]))
nil_X = np.zeros(self.max_features)
nil_Y1 = np.array(self.ltag_vector[0]['NIL'])
nil_Y2 = np.array(self.ltag_vector[1]['NIL'])
nil_Y3 = np.array(self.ltag_vector[2]['NIL'])
pad_length = self.max_sentence_len - len(wordsvec)
lX.append( wordsvec +((pad_length)*[nil_X]) )
lY1.append( elem_tags1 + ((pad_length)*[nil_Y1]) )
lY2.append( elem_tags2 + ((pad_length)*[nil_Y2]) )
lY3.append( elem_tags3 + ((pad_length)*[nil_Y3]) )
del lx
del ly
lX=np.array(lX)
lY1=np.array(lY1)
lY2=np.array(lY2)
lY3=np.array(lY3)
return lX,(lY1,lY2,lY3)
def testModel_Multitype(self,testdata):
"""
test model
"""
lX,(lY,lY2,lY3) = self.prepareTensor_multitype(testdata)
scores = self.model.evaluate(lX,[lY,lY2,lY3],verbose=True)
#print(list(zip(self.model.metrics_names,scores)))
test_x, _ = testdata
y_pred1,y_pred2, y_pred3 = self.model.predict(lX)
for i,_ in enumerate(lX):
for iy,pred_seq in enumerate([y_pred1[i],y_pred2[i],y_pred3[i]]):
pred_tags = []
for class_prs in pred_seq:
class_vec = np.zeros(self.lnbClasses[iy], dtype=np.int32)
class_vec[ np.argmax(class_prs) ] = 1
# print class_prs[class_prs >0.1]
if tuple(class_vec.tolist()) in self.ltag_vector[iy]:
# print(self.tag_vector[tuple(class_vec.tolist())],class_prs[np.argmax(class_prs)])
pred_tags.append((self.tag_vector[tuple(class_vec.tolist())],class_prs[np.argmax(class_prs)]))
print(test_x[i],pred_tags[:len(test_x[i])])
def prepareOutput_multitype(self,lToken,lLTags):
"""
format final output with MultiType
"""
lRes= []
for itok,seq in enumerate(lToken):
print (seq,lLTags[0][itok],lLTags[1][itok],lLTags[2][itok])
tag1,tag2,tag3 = lLTags[0][itok],lLTags[1][itok],lLTags[2][itok]
lRes.append([((itok,itok),seq,tag1,tag2,tag3)])
# lRes.append((toffset,tok,label,list(lScore)))
return lRes
def predict_multiptype(self,lsent):
"""
predict over a set of sentences (unicode)
"""
lRes= []
for mysent in lsent :
if len(mysent.split())> self.max_sentence_len:
print ('max sent length: %s'%self.max_sentence_len)
continue
# allwords= self.node_transformer.transform(mysent.split())
allwords= self.node_transformer.transform(mysent.split())
# print mysent.split()
# n=len(mysent.split())
wordsvec = []
for w in allwords:
wordsvec.append(w)
lX = list()
nil_X = np.zeros(self.max_features)
pad_length = self.max_sentence_len - len(wordsvec)
lX.append( wordsvec +((pad_length)*[nil_X]) )
lX=np.array(lX)
# print(pad_length*[nil_X] + wordsvec, self.max_sentence_len)
# assert pad_length*[nil_X] + wordsvec >= self.max_sentence_len
y_pred1,y_pred2,y_pred3 = self.model.predict(lX)
for i,_ in enumerate(lX):
# pred_seq = y_pred[i]
l_multi_type_results = []
for iy,pred_seq in enumerate([y_pred1[i],y_pred2[i],y_pred3[i]]):
pred_tags = []
pad_length = self.max_sentence_len - len(allwords)
for class_prs in pred_seq:
class_vec = np.zeros(self.lnbClasses[iy], dtype=np.int32)
class_vec[ np.argmax(class_prs) ] = 1
if tuple(class_vec.tolist()) in self.ltag_vector[iy]:
# print (iy,tuple(class_vec.tolist()),self.ltag_vector[iy][tuple(class_vec.tolist())],class_prs[np.argmax(class_prs)])
pred_tags.append((self.ltag_vector[iy][tuple(class_vec.tolist())],class_prs[np.argmax(class_prs)]))
l_multi_type_results.append(pred_tags[:len(allwords)])
# print(mysent,l_multi_type_results)
lRes.append(self.prepareOutput_multitype(mysent.split(),l_multi_type_results))
return lRes
def run(self):
"""
"""
if self.bGridSearch:
pass
# self.gridSearch()
if self.bMultiType and self.bTraining:
lX, lY = self.load_data_Multitype(self.lTrain)
model, other = self.training_multitype((lX,lY))
# store
self.storeModel(model,other)
del lX, lY
del self.node_transformer
del model
if self.bTraining and not self.bMultiType:
lX, lY = self.load_data(self.lTrain)
model, other = self.training((lX,lY))
# store
self.storeModel(model,other)
del lX, lY
del self.node_transformer
del model
if self.bTesting:
self.loadModels()
if self.bMultiType:
lX,lY = self.load_data_for_testing_Multitype(self.lTest)
res = self.testModel_Multitype((lX,lY))
else:
lX,lY = self.load_data_for_testing(self.lTest)
res = self.testModel((lX,lY))
if self.bPredict:
# which input format: [unicode]
self.loadModels()
lsent = [self._sent]
print (lsent)
if self.bMultiType:
lres = self.predict_multiptype(lsent)
else:
lres = self.predict(lsent)
for r in lres:
print (r)
if __name__ == '__main__':
cmp = DeepTagger()
cmp.parser = OptionParser(usage="", version="0.1")
cmp.parser.description = "BiLSTM approach for NER"
cmp.parser.add_option("--name", dest="name", action="store", type="string", help="model name")
cmp.parser.add_option("--dir", dest="dirname", action="store", type="string", help="directory to store model")
cmp.parser.add_option("--training", dest="training", action="append", type="string", help="training data")
cmp.parser.add_option("--ml", dest="multitype", action="store_true",default=False, help="multi type version")
cmp.parser.add_option("--hidden", dest="hidden", action="store", type="int", help="hidden layer dimension")
cmp.parser.add_option("--batch", dest="batchSize", action="store", type="int", help="batch size")
cmp.parser.add_option("--epochs", dest="nbEpochs", action="store", type="int", default=2,help="nb epochs for training")
cmp.parser.add_option("--ngram", dest="ngram", action="store", type="int", default=2,help="ngram size")
cmp.parser.add_option("--nbfeatures", dest="nbfeatures", action="store", type="int",default=128, help="nb features")
cmp.parser.add_option("--testing", dest="testing", action="append", type="string", help="test data")
cmp.parser.add_option("--run", dest="predict", action="store", type="string", help="string to be categorized")
cmp.parser.add_option("--att", dest="attention", action="store_true", default=False, help="add attention layer")
(options, args) = cmp.parser.parse_args()
#Now we are back to the normal programmatic mode, we set the component parameters
cmp.setParams(options)
#This component is quite special since it does not take one XML as input but rather a series of files.
#doc = cmp.loadDom()
doc = cmp.run()
|
[] |
[] |
[
"KERAS_BACKEND"
] |
[]
|
["KERAS_BACKEND"]
|
python
| 1 | 0 | |
Session4/simple_queue_read.py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 1 08:49:12 2019
@author: chaulaic
"""
import pika
import os
cpt = 0
def simple_queue_read(concurrency):
def callback(ch, method, properties, body):
#Function callback call every time the channel received a message
#Display message
global cpt
print(" [x] Received %r" % body)
print(" [x] Message Processed, acknowledging")
ch.basic_ack(delivery_tag = method.delivery_tag)
cpt += 1
print("Cpt = " + str(cpt))
amqp_url='amqp://vqbglcjd:[email protected]/vqbglcjd'
url = os.environ.get('CLOUDAMQP_URL',amqp_url)
params = pika.URLParameters(url)
params.socket_timeout = 5
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue='presentation')
if (concurrency):
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='presentation',
on_message_callback=callback,
auto_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
else :
channel.basic_consume(queue='presentation',
on_message_callback=callback,
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
|
[] |
[] |
[
"CLOUDAMQP_URL"
] |
[]
|
["CLOUDAMQP_URL"]
|
python
| 1 | 0 | |
icloudpd/base.py
|
#!/usr/bin/env python
"""Main script that uses Click to parse command-line arguments"""
from __future__ import print_function
import os
import sys
import time
import datetime
import logging
import itertools
import subprocess
import json
import click
from future.moves.urllib.parse import urlencode
from tqdm import tqdm
from tzlocal import get_localzone
from pyicloud_ipd.exceptions import PyiCloudAPIResponseError
from icloudpd.logger import setup_logger
from icloudpd.authentication import authenticate, TwoStepAuthRequiredError
from icloudpd import download
from icloudpd.email_notifications import send_2sa_notification
from icloudpd.string_helpers import truncate_middle
from icloudpd.autodelete import autodelete_photos
from icloudpd.paths import local_download_path
from icloudpd import exif_datetime
# Must import the constants object so that we can mock values in tests.
from icloudpd import constants
from icloudpd.counter import Counter
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.command(context_settings=CONTEXT_SETTINGS, options_metavar="<options>")
# @click.argument(
@click.option(
"-d", "--directory",
help="Local directory that should be used for download",
type=click.Path(exists=True),
metavar="<directory>")
@click.option(
"-u", "--username",
help="Your iCloud username or email address",
metavar="<username>",
prompt="iCloud username/email",
)
@click.option(
"-p", "--password",
help="Your iCloud password "
"(default: use PyiCloud keyring or prompt for password)",
metavar="<password>",
)
@click.option(
"--cookie-directory",
help="Directory to store cookies for authentication "
"(default: ~/.pyicloud)",
metavar="</cookie/directory>",
default="~/.pyicloud",
)
@click.option(
"--size",
help="Image size to download (default: original)",
type=click.Choice(["original", "medium", "thumb"]),
default="original",
)
@click.option(
"--live-photo-size",
help="Live Photo video size to download (default: original)",
type=click.Choice(["original", "medium", "thumb"]),
default="original",
)
@click.option(
"--recent",
help="Number of recent photos to download (default: download all photos)",
type=click.IntRange(0),
)
@click.option(
"--until-found",
help="Download most recently added photos until we find x number of "
"previously downloaded consecutive photos (default: download all photos)",
type=click.IntRange(0),
)
@click.option(
"-a", "--album",
help="Album to download (default: All Photos)",
metavar="<album>",
default="All Photos",
)
@click.option(
"-l", "--list-albums",
help="Lists the avaliable albums",
is_flag=True,
)
@click.option(
"--skip-videos",
help="Don't download any videos (default: Download all photos and videos)",
is_flag=True,
)
@click.option(
"--skip-live-photos",
help="Don't download any live photos (default: Download live photos)",
is_flag=True,
)
@click.option(
"--force-size",
help="Only download the requested size "
+ "(default: download original if size is not available)",
is_flag=True,
)
@click.option(
"--auto-delete",
help='Scans the "Recently Deleted" folder and deletes any files found in there. '
+ "(If you restore the photo in iCloud, it will be downloaded again.)",
is_flag=True,
)
@click.option(
"--only-print-filenames",
help="Only prints the filenames of all files that will be downloaded "
"(not including files that are already downloaded.)"
+ "(Does not download or delete any files.)",
is_flag=True,
)
@click.option(
"--folder-structure",
help="Folder structure (default: {:%Y/%m/%d}). "
"If set to 'none' all photos will just be placed into the download directory",
metavar="<folder_structure>",
default="{:%Y%m - %B %Y}",
)
@click.option(
"--set-exif-datetime",
help="Write the DateTimeOriginal exif tag from file creation date, " +
"if it doesn't exist.",
is_flag=True,
)
@click.option(
"--smtp-username",
help="Your SMTP username, for sending email notifications when "
"two-step authentication expires.",
metavar="<smtp_username>",
)
@click.option(
"--smtp-password",
help="Your SMTP password, for sending email notifications when "
"two-step authentication expires.",
metavar="<smtp_password>",
)
@click.option(
"--smtp-host",
help="Your SMTP server host. Defaults to: smtp.gmail.com",
metavar="<smtp_host>",
default="smtp.gmail.com",
)
@click.option(
"--smtp-port",
help="Your SMTP server port. Default: 587 (Gmail)",
metavar="<smtp_port>",
type=click.IntRange(0),
default=587,
)
@click.option(
"--smtp-no-tls",
help="Pass this flag to disable TLS for SMTP (TLS is required for Gmail)",
metavar="<smtp_no_tls>",
is_flag=True,
)
@click.option(
"--notification-email",
help="Email address where you would like to receive email notifications. "
"Default: SMTP username",
metavar="<notification_email>",
)
@click.option(
"--notification-script",
type=click.Path(),
help="Runs an external script when two factor authentication expires. "
"(path required: /path/to/my/script.sh)",
)
@click.option(
"--log-level",
help="Log level (default: debug)",
type=click.Choice(["debug", "info", "error"]),
default="debug",
)
@click.option("--no-progress-bar",
help="Disables the one-line progress bar and prints log messages on separate lines "
"(Progress bar is disabled by default if there is no tty attached)",
is_flag=True,
)
@click.option(
"--threads-num",
help="Number of cpu threads -- deprecated. To be removed in future version",
type=click.IntRange(1),
default=1,
)
@click.option('--delete-if-downloaded',
help='Delete the file after downloading',
is_flag=False)
@click.option('--download-delete-age',
help='Specify the age of the file you want to delete in days.' + \
'(Only used if --delete-if-downloaded is set)',
type=click.IntRange(0),
default=30)
@click.option('--download-suffix',
help='Set the suffix of the download file',
default='')
@click.version_option()
# pylint: disable-msg=too-many-arguments,too-many-statements
# pylint: disable-msg=too-many-branches,too-many-locals
def main(
directory,
username,
password,
cookie_directory,
size,
live_photo_size,
recent,
until_found,
album,
list_albums,
skip_videos,
skip_live_photos,
force_size,
auto_delete,
only_print_filenames,
folder_structure,
set_exif_datetime,
smtp_username,
smtp_password,
smtp_host,
smtp_port,
smtp_no_tls,
notification_email,
log_level,
no_progress_bar,
notification_script,
threads_num, # pylint: disable=W0613
delete_if_downloaded,
download_delete_age,
download_suffix,
):
"""Download all iCloud photos to a local directory"""
logger = setup_logger()
if only_print_filenames:
logger.disabled = True
else:
# Need to make sure disabled is reset to the correct value,
# because the logger instance is shared between tests.
logger.disabled = False
if log_level == "debug":
logger.setLevel(logging.DEBUG)
elif log_level == "info":
logger.setLevel(logging.INFO)
elif log_level == "error":
logger.setLevel(logging.ERROR)
# check required directory param only if not list albums
if not list_albums and not directory:
print('--directory or --list-albums are required')
sys.exit(2)
raise_error_on_2sa = (
smtp_username is not None
or notification_email is not None
or notification_script is not None
)
try:
icloud = authenticate(
username,
password,
cookie_directory,
raise_error_on_2sa,
client_id=os.environ.get("CLIENT_ID"),
)
except TwoStepAuthRequiredError:
if notification_script is not None:
subprocess.call([notification_script])
if smtp_username is not None or notification_email is not None:
send_2sa_notification(
smtp_username,
smtp_password,
smtp_host,
smtp_port,
smtp_no_tls,
notification_email,
)
sys.exit(1)
# Default album is "All Photos", so this is the same as
# calling `icloud.photos.all`.
# After 6 or 7 runs within 1h Apple blocks the API for some time. In that
# case exit.
try:
photos = icloud.photos.albums[album]
except PyiCloudAPIResponseError as err:
# For later: come up with a nicer message to the user. For now take the
# exception text
print(err)
sys.exit(1)
if list_albums:
albums_dict = icloud.photos.albums
albums = albums_dict.values() # pragma: no cover
album_titles = [str(a) for a in albums]
print(*album_titles, sep="\n")
sys.exit(0)
directory = os.path.normpath(directory)
logger.debug(
"Looking up all photos%s from album %s...",
"" if skip_videos else " and videos",
album)
def photos_exception_handler(ex, retries):
"""Handles session errors in the PhotoAlbum photos iterator"""
if "Invalid global session" in str(ex):
if retries > constants.MAX_RETRIES:
logger.tqdm_write(
"iCloud re-authentication failed! Please try again later."
)
raise ex
logger.tqdm_write(
"Session error, re-authenticating...",
logging.ERROR)
if retries > 1:
# If the first reauthentication attempt failed,
# start waiting a few seconds before retrying in case
# there are some issues with the Apple servers
time.sleep(constants.WAIT_SECONDS * retries)
icloud.authenticate()
photos.exception_handler = photos_exception_handler
photos_count = len(photos)
# Optional: Only download the x most recent photos.
if recent is not None:
photos_count = recent
photos = itertools.islice(photos, recent)
tqdm_kwargs = {"total": photos_count}
if until_found is not None:
del tqdm_kwargs["total"]
photos_count = "???"
# ensure photos iterator doesn't have a known length
photos = (p for p in photos)
plural_suffix = "" if photos_count == 1 else "s"
video_suffix = ""
photos_count_str = "the first" if photos_count == 1 else photos_count
if not skip_videos:
video_suffix = " or video" if photos_count == 1 else " and videos"
logger.info(
"Downloading %s %s photo%s%s to %s ...",
photos_count_str,
size,
plural_suffix,
video_suffix,
directory,
)
# Use only ASCII characters in progress bar
tqdm_kwargs["ascii"] = True
# Skip the one-line progress bar if we're only printing the filenames,
# or if the progress bar is explicity disabled,
# or if this is not a terminal (e.g. cron or piping output to file)
if not os.environ.get("FORCE_TQDM") and (
only_print_filenames or no_progress_bar or not sys.stdout.isatty()
):
photos_enumerator = photos
logger.set_tqdm(None)
else:
photos_enumerator = tqdm(photos, **tqdm_kwargs)
logger.set_tqdm(photos_enumerator)
def download_photo(counter, photo):
"""internal function for actually downloading the photos"""
if skip_videos and photo.item_type != "image":
logger.set_tqdm_description(
"Skipping %s, only downloading photos." % photo.filename
)
return
if photo.item_type != "image" and photo.item_type != "movie":
logger.set_tqdm_description(
"Skipping %s, only downloading photos and videos. "
"(Item type was: %s)" % (photo.filename, photo.item_type)
)
return
try:
created_date = photo.created.astimezone(get_localzone())
except (ValueError, OSError):
logger.set_tqdm_description(
"Could not convert photo created date to local timezone (%s)" %
photo.created, logging.ERROR)
created_date = photo.created
current_date = datetime.datetime.now(datetime.timezone.utc)
try:
if folder_structure.lower() == "none":
date_path = ""
else:
date_path = folder_structure.format(created_date)
except ValueError: # pragma: no cover
# This error only seems to happen in Python 2
logger.set_tqdm_description(
"Photo created date was not valid (%s)" %
photo.created, logging.ERROR)
# e.g. ValueError: year=5 is before 1900
# (https://github.com/icloud-photos-downloader/icloud_photos_downloader/issues/122)
# Just use the Unix epoch
created_date = datetime.datetime.fromtimestamp(0)
date_path = folder_structure.format(created_date)
download_dir = os.path.normpath(os.path.join(directory, date_path))
download_size = size
try:
versions = photo.versions
except KeyError as ex:
print(
"KeyError: %s attribute was not found in the photo fields!" %
ex)
with open('icloudpd-photo-error.json', 'w') as outfile:
# pylint: disable=protected-access
json.dump({
"master_record": photo._master_record,
"asset_record": photo._asset_record
}, outfile)
# pylint: enable=protected-access
print("icloudpd has saved the photo record to: "
"./icloudpd-photo-error.json")
print("Please create a Gist with the contents of this file: "
"https://gist.github.com")
print(
"Then create an issue on GitHub: "
"https://github.com/icloud-photos-downloader/icloud_photos_downloader/issues")
print(
"Include a link to the Gist in your issue, so that we can "
"see what went wrong.\n")
return
if size not in versions and size != "original":
if force_size:
filename = photo.filename.encode(
"utf-8").decode("ascii", "ignore")
logger.set_tqdm_description(
"%s size does not exist for %s. Skipping..." %
(size, filename), logging.ERROR, )
return
download_size = "original"
download_path = local_download_path(
photo, download_size, download_dir, download_suffix)
file_exists = os.path.isfile(download_path)
if not file_exists and download_size == "original":
# Deprecation - We used to download files like IMG_1234-original.jpg,
# so we need to check for these.
# Now we match the behavior of iCloud for Windows: IMG_1234.jpg
original_download_path = ("-%s." % size).join(
download_path.rsplit(".", 1)
)
file_exists = os.path.isfile(original_download_path)
if file_exists:
# for later: this crashes if download-size medium is specified
file_size = os.stat(download_path).st_size
version = photo.versions[download_size]
photo_size = version["size"]
if file_size != photo_size:
download_path = ("-%s." % photo_size).join(
download_path.rsplit(".", 1)
)
logger.set_tqdm_description(
"%s deduplicated." % truncate_middle(download_path, 96)
)
file_exists = os.path.isfile(download_path)
if file_exists:
counter.increment()
logger.set_tqdm_description(
"%s already exists." % truncate_middle(download_path, 96)
)
if delete_if_downloaded and (current_date - created_date).days > download_delete_age:
move_picture_to_recently_deleted(icloud, photo)
if not file_exists:
counter.reset()
if only_print_filenames:
print(download_path)
else:
truncated_path = truncate_middle(download_path, 96)
logger.set_tqdm_description(
"Downloading %s" %
truncated_path)
download_result = download.download_media(
icloud, photo, download_path, download_size
)
if download_result:
if set_exif_datetime and photo.filename.lower().endswith(
(".jpg", ".jpeg")) and not exif_datetime.get_photo_exif(download_path):
# %Y:%m:%d looks wrong but it's the correct format
date_str = created_date.strftime(
"%Y-%m-%d %H:%M:%S%z")
logger.debug(
"Setting EXIF timestamp for %s: %s",
download_path,
date_str,
)
exif_datetime.set_photo_exif(
download_path,
created_date.strftime("%Y:%m:%d %H:%M:%S"),
)
download.set_utime(download_path, created_date)
if delete_if_downloaded and (current_date - created_date).days > download_delete_age:
move_picture_to_recently_deleted(icloud, photo)
# Also download the live photo if present
if not skip_live_photos:
lp_size = live_photo_size + "Video"
if lp_size in photo.versions:
version = photo.versions[lp_size]
filename = version["filename"]
if live_photo_size != "original":
# Add size to filename if not original
filename = filename.replace(
".MOV", "-%s.MOV" %
live_photo_size)
lp_download_path = os.path.join(download_dir, filename)
lp_file_exists = os.path.isfile(lp_download_path)
if only_print_filenames and not lp_file_exists:
print(lp_download_path)
else:
if lp_file_exists:
lp_file_size = os.stat(lp_download_path).st_size
lp_photo_size = version["size"]
if lp_file_size != lp_photo_size:
lp_download_path = ("-%s." % lp_photo_size).join(
lp_download_path.rsplit(".", 1)
)
logger.set_tqdm_description(
"%s deduplicated." %
truncate_middle(
lp_download_path, 96))
lp_file_exists = os.path.isfile(lp_download_path)
if lp_file_exists:
logger.set_tqdm_description(
"%s already exists."
% truncate_middle(lp_download_path, 96)
)
if not lp_file_exists:
truncated_path = truncate_middle(lp_download_path, 96)
logger.set_tqdm_description(
"Downloading %s" % truncated_path)
download.download_media(
icloud, photo, lp_download_path, lp_size
)
consecutive_files_found = Counter(0)
def should_break(counter):
"""Exit if until_found condition is reached"""
return until_found is not None and counter.value() >= until_found
photos_iterator = iter(photos_enumerator)
while True:
try:
if should_break(consecutive_files_found):
logger.tqdm_write(
"Found %d consecutive previously downloaded photos. Exiting" %
until_found)
break
item = next(photos_iterator)
download_photo(consecutive_files_found, item)
except StopIteration:
break
if only_print_filenames:
sys.exit(0)
logger.info("All photos have been downloaded!")
if auto_delete:
autodelete_photos(icloud, folder_structure, directory)
def move_picture_to_recently_deleted(icloud, photo):
url = '{}/records/modify?{}'.format(icloud.photos._service_endpoint, urlencode(icloud.photos.params))
headers = {'Content-type': 'text/plain'}
mr = {'fields': {'isDeleted': {'value': 1}}}
mr['recordChangeTag'] = photo._asset_record['recordChangeTag']
mr['recordName'] = photo._asset_record['recordName']
mr['recordType'] = 'CPLAsset'
op = dict(
operationType='update',
record=mr,
)
operations = []
operations.append(op)
post_data = json.dumps(dict(
atomic=True,
desiredKeys=['isDeleted'],
operations=operations,
zoneID={'zoneName': 'PrimarySync'},
))
icloud.photos.session.post(url, data=post_data, headers=headers).json()
|
[] |
[] |
[
"FORCE_TQDM",
"CLIENT_ID"
] |
[]
|
["FORCE_TQDM", "CLIENT_ID"]
|
python
| 2 | 0 | |
sessionctx/binloginfo/binloginfo_test.go
|
// Copyright 2016 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package binloginfo_test
import (
"context"
"net"
"os"
"strconv"
"sync"
"testing"
"time"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
pumpcli "github.com/pingcap/tidb-tools/tidb-binlog/pump_client"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/testkit"
binlog "github.com/pingcap/tipb/go-binlog"
"google.golang.org/grpc"
)
func TestT(t *testing.T) {
CustomVerboseFlag = true
logLevel := os.Getenv("log_level")
logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
TestingT(t)
}
type mockBinlogPump struct {
mu struct {
sync.Mutex
payloads [][]byte
mockFail bool
}
}
func (p *mockBinlogPump) WriteBinlog(ctx context.Context, req *binlog.WriteBinlogReq) (*binlog.WriteBinlogResp, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.mu.mockFail {
return &binlog.WriteBinlogResp{}, errors.New("mock fail")
}
p.mu.payloads = append(p.mu.payloads, req.Payload)
return &binlog.WriteBinlogResp{}, nil
}
// PullBinlogs implements PumpServer interface.
func (p *mockBinlogPump) PullBinlogs(req *binlog.PullBinlogReq, srv binlog.Pump_PullBinlogsServer) error {
return nil
}
var _ = Suite(&testBinlogSuite{})
type testBinlogSuite struct {
store kv.Storage
domain *domain.Domain
unixFile string
serv *grpc.Server
pump *mockBinlogPump
client *pumpcli.PumpsClient
ddl ddl.DDL
}
const maxRecvMsgSize = 64 * 1024
func (s *testBinlogSuite) SetUpSuite(c *C) {
store, err := mockstore.NewMockTikvStore()
c.Assert(err, IsNil)
s.store = store
session.SetSchemaLease(0)
s.unixFile = "/tmp/mock-binlog-pump" + strconv.FormatInt(time.Now().UnixNano(), 10)
l, err := net.Listen("unix", s.unixFile)
c.Assert(err, IsNil)
s.serv = grpc.NewServer(grpc.MaxRecvMsgSize(maxRecvMsgSize))
s.pump = new(mockBinlogPump)
binlog.RegisterPumpServer(s.serv, s.pump)
go s.serv.Serve(l)
opt := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("unix", addr, timeout)
})
clientCon, err := grpc.Dial(s.unixFile, opt, grpc.WithInsecure())
c.Assert(err, IsNil)
c.Assert(clientCon, NotNil)
tk := testkit.NewTestKit(c, s.store)
s.domain, err = session.BootstrapSession(store)
c.Assert(err, IsNil)
tk.MustExec("use test")
sessionDomain := domain.GetDomain(tk.Se.(sessionctx.Context))
s.ddl = sessionDomain.DDL()
s.client = binloginfo.MockPumpsClient(binlog.NewPumpClient(clientCon))
s.ddl.SetBinlogClient(s.client)
}
func (s *testBinlogSuite) TearDownSuite(c *C) {
s.ddl.Stop()
s.serv.Stop()
os.Remove(s.unixFile)
s.domain.Close()
s.store.Close()
}
func (s *testBinlogSuite) TestBinlog(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.Se.GetSessionVars().BinlogClient = s.client
pump := s.pump
tk.MustExec("drop table if exists local_binlog")
ddlQuery := "create table local_binlog (id int unique key, name varchar(10)) shard_row_id_bits=1"
binlogDDLQuery := "create table local_binlog (id int unique key, name varchar(10)) /*!90000 shard_row_id_bits=1 */"
tk.MustExec(ddlQuery)
var matched bool // got matched pre DDL and commit DDL
for i := 0; i < 10; i++ {
preDDL, commitDDL, _ := getLatestDDLBinlog(c, pump, binlogDDLQuery)
if preDDL != nil && commitDDL != nil {
if preDDL.DdlJobId == commitDDL.DdlJobId {
c.Assert(commitDDL.StartTs, Equals, preDDL.StartTs)
c.Assert(commitDDL.CommitTs, Greater, commitDDL.StartTs)
matched = true
break
}
}
time.Sleep(time.Millisecond * 10)
}
c.Assert(matched, IsTrue)
tk.MustExec("insert local_binlog values (1, 'abc'), (2, 'cde')")
prewriteVal := getLatestBinlogPrewriteValue(c, pump)
c.Assert(prewriteVal.SchemaVersion, Greater, int64(0))
c.Assert(prewriteVal.Mutations[0].TableId, Greater, int64(0))
expected := [][]types.Datum{
{types.NewIntDatum(1), types.NewCollationStringDatum("abc", mysql.DefaultCollationName, collate.DefaultLen)},
{types.NewIntDatum(2), types.NewCollationStringDatum("cde", mysql.DefaultCollationName, collate.DefaultLen)},
}
gotRows := mutationRowsToRows(c, prewriteVal.Mutations[0].InsertedRows, 2, 4)
c.Assert(gotRows, DeepEquals, expected)
tk.MustExec("update local_binlog set name = 'xyz' where id = 2")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
oldRow := [][]types.Datum{
{types.NewIntDatum(2), types.NewCollationStringDatum("cde", mysql.DefaultCollationName, collate.DefaultLen)},
}
newRow := [][]types.Datum{
{types.NewIntDatum(2), types.NewCollationStringDatum("xyz", mysql.DefaultCollationName, collate.DefaultLen)},
}
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 1, 3)
c.Assert(gotRows, DeepEquals, oldRow)
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 7, 9)
c.Assert(gotRows, DeepEquals, newRow)
tk.MustExec("delete from local_binlog where id = 1")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3)
expected = [][]types.Datum{
{types.NewIntDatum(1), types.NewCollationStringDatum("abc", mysql.DefaultCollationName, collate.DefaultLen)},
}
c.Assert(gotRows, DeepEquals, expected)
// Test table primary key is not integer.
tk.MustExec("create table local_binlog2 (name varchar(64) primary key, age int)")
tk.MustExec("insert local_binlog2 values ('abc', 16), ('def', 18)")
tk.MustExec("delete from local_binlog2 where name = 'def'")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
c.Assert(prewriteVal.Mutations[0].Sequence[0], Equals, binlog.MutationType_DeleteRow)
expected = [][]types.Datum{
{types.NewStringDatum("def"), types.NewIntDatum(18), types.NewIntDatum(-1), types.NewIntDatum(2)},
}
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5)
c.Assert(gotRows, DeepEquals, expected)
// Test Table don't have primary key.
tk.MustExec("create table local_binlog3 (c1 int, c2 int)")
tk.MustExec("insert local_binlog3 values (1, 2), (1, 3), (2, 3)")
tk.MustExec("update local_binlog3 set c1 = 3 where c1 = 2")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
// The encoded update row is [oldColID1, oldColVal1, oldColID2, oldColVal2, -1, handle,
// newColID1, newColVal2, newColID2, newColVal2, -1, handle]
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 7, 9)
expected = [][]types.Datum{
{types.NewIntDatum(3), types.NewIntDatum(3)},
}
c.Assert(gotRows, DeepEquals, expected)
expected = [][]types.Datum{
{types.NewIntDatum(-1), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)},
}
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].UpdatedRows, 4, 5, 10, 11)
c.Assert(gotRows, DeepEquals, expected)
tk.MustExec("delete from local_binlog3 where c1 = 3 and c2 = 3")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
c.Assert(prewriteVal.Mutations[0].Sequence[0], Equals, binlog.MutationType_DeleteRow)
gotRows = mutationRowsToRows(c, prewriteVal.Mutations[0].DeletedRows, 1, 3, 4, 5)
expected = [][]types.Datum{
{types.NewIntDatum(3), types.NewIntDatum(3), types.NewIntDatum(-1), types.NewIntDatum(3)},
}
c.Assert(gotRows, DeepEquals, expected)
// Test Mutation Sequence.
tk.MustExec("create table local_binlog4 (c1 int primary key, c2 int)")
tk.MustExec("insert local_binlog4 values (1, 1), (2, 2), (3, 2)")
tk.MustExec("begin")
tk.MustExec("delete from local_binlog4 where c1 = 1")
tk.MustExec("insert local_binlog4 values (1, 1)")
tk.MustExec("update local_binlog4 set c2 = 3 where c1 = 3")
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
c.Assert(prewriteVal.Mutations[0].Sequence, DeepEquals, []binlog.MutationType{
binlog.MutationType_DeleteRow,
binlog.MutationType_Insert,
binlog.MutationType_Update,
})
// Test statement rollback.
tk.MustExec("create table local_binlog5 (c1 int primary key)")
tk.MustExec("begin")
tk.MustExec("insert into local_binlog5 value (1)")
// This statement execute fail and should not write binlog.
_, err := tk.Exec("insert into local_binlog5 value (4),(3),(1),(2)")
c.Assert(err, NotNil)
tk.MustExec("commit")
prewriteVal = getLatestBinlogPrewriteValue(c, pump)
c.Assert(prewriteVal.Mutations[0].Sequence, DeepEquals, []binlog.MutationType{
binlog.MutationType_Insert,
})
checkBinlogCount(c, pump)
pump.mu.Lock()
originBinlogLen := len(pump.mu.payloads)
pump.mu.Unlock()
tk.MustExec("set @@global.autocommit = 0")
tk.MustExec("set @@global.autocommit = 1")
pump.mu.Lock()
newBinlogLen := len(pump.mu.payloads)
pump.mu.Unlock()
c.Assert(newBinlogLen, Equals, originBinlogLen)
}
func (s *testBinlogSuite) TestMaxRecvSize(c *C) {
info := &binloginfo.BinlogInfo{
Data: &binlog.Binlog{
Tp: binlog.BinlogType_Prewrite,
PrewriteValue: make([]byte, maxRecvMsgSize+1),
},
Client: s.client,
}
binlogWR := info.WriteBinlog(1)
err := binlogWR.GetError()
c.Assert(err, NotNil)
c.Assert(terror.ErrCritical.Equal(err), IsFalse, Commentf("%v", err))
}
func getLatestBinlogPrewriteValue(c *C, pump *mockBinlogPump) *binlog.PrewriteValue {
var bin *binlog.Binlog
pump.mu.Lock()
for i := len(pump.mu.payloads) - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin = new(binlog.Binlog)
bin.Unmarshal(payload)
if bin.Tp == binlog.BinlogType_Prewrite {
break
}
}
pump.mu.Unlock()
c.Assert(bin, NotNil)
preVal := new(binlog.PrewriteValue)
preVal.Unmarshal(bin.PrewriteValue)
return preVal
}
func getLatestDDLBinlog(c *C, pump *mockBinlogPump, ddlQuery string) (preDDL, commitDDL *binlog.Binlog, offset int) {
pump.mu.Lock()
for i := len(pump.mu.payloads) - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin := new(binlog.Binlog)
bin.Unmarshal(payload)
if bin.Tp == binlog.BinlogType_Commit && bin.DdlJobId > 0 {
commitDDL = bin
}
if bin.Tp == binlog.BinlogType_Prewrite && bin.DdlJobId != 0 {
preDDL = bin
}
if preDDL != nil && commitDDL != nil {
offset = i
break
}
}
pump.mu.Unlock()
c.Assert(preDDL.DdlJobId, Greater, int64(0))
c.Assert(preDDL.StartTs, Greater, int64(0))
c.Assert(preDDL.CommitTs, Equals, int64(0))
c.Assert(string(preDDL.DdlQuery), Equals, ddlQuery)
return
}
func checkBinlogCount(c *C, pump *mockBinlogPump) {
var bin *binlog.Binlog
prewriteCount := 0
ddlCount := 0
pump.mu.Lock()
length := len(pump.mu.payloads)
for i := length - 1; i >= 0; i-- {
payload := pump.mu.payloads[i]
bin = new(binlog.Binlog)
bin.Unmarshal(payload)
if bin.Tp == binlog.BinlogType_Prewrite {
if bin.DdlJobId != 0 {
ddlCount++
} else {
prewriteCount++
}
}
}
pump.mu.Unlock()
c.Assert(ddlCount, Greater, 0)
match := false
for i := 0; i < 10; i++ {
pump.mu.Lock()
length = len(pump.mu.payloads)
pump.mu.Unlock()
if (prewriteCount+ddlCount)*2 == length {
match = true
break
}
time.Sleep(time.Millisecond * 10)
}
c.Assert(match, IsTrue)
}
func mutationRowsToRows(c *C, mutationRows [][]byte, columnValueOffsets ...int) [][]types.Datum {
var rows = make([][]types.Datum, 0)
for _, mutationRow := range mutationRows {
datums, err := codec.Decode(mutationRow, 5)
c.Assert(err, IsNil)
for i := range datums {
if datums[i].Kind() == types.KindBytes {
datums[i].SetBytesAsString(datums[i].GetBytes(), mysql.DefaultCollationName, collate.DefaultLen)
}
}
row := make([]types.Datum, 0, len(columnValueOffsets))
for _, colOff := range columnValueOffsets {
row = append(row, datums[colOff])
}
rows = append(rows, row)
}
return rows
}
func (s *testBinlogSuite) TestBinlogForSequence(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
s.pump.mu.Lock()
s.pump.mu.payloads = s.pump.mu.payloads[:0]
s.pump.mu.Unlock()
tk.Se.GetSessionVars().BinlogClient = s.client
tk.MustExec("drop sequence if exists seq")
// the default start = 1, increment = 1.
tk.MustExec("create sequence seq cache 3")
// trigger the sequence cache allocation.
err := tk.QueryToErr("select nextval(seq)")
c.Assert(err, IsNil)
sequenceTable := testGetTableByName(c, tk.Se, "test", "seq")
tc, ok := sequenceTable.(*tables.TableCommon)
c.Assert(ok, Equals, true)
_, end, round := tc.GetSequenceCommon().GetSequenceBaseEndRound()
c.Assert(end, Equals, int64(3))
c.Assert(round, Equals, int64(0))
// Check the sequence binlog.
// Got matched pre DDL and commit DDL.
ok = mustGetDDLBinlog(s, "select setval(`test`.`seq`, 3)", c)
c.Assert(ok, IsTrue)
// Invalidate the current sequence cache.
tk.MustExec("select setval(seq, 5)")
// trigger the next sequence cache allocation.
err = tk.QueryToErr("select nextval(seq)")
c.Assert(err, IsNil)
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
c.Assert(end, Equals, int64(8))
c.Assert(round, Equals, int64(0))
ok = mustGetDDLBinlog(s, "select setval(`test`.`seq`, 8)", c)
c.Assert(ok, IsTrue)
tk.MustExec("create database test2")
tk.MustExec("use test2")
tk.MustExec("drop sequence if exists seq2")
tk.MustExec("create sequence seq2 start 1 increment -2 cache 3 minvalue -10 maxvalue 10 cycle")
// trigger the sequence cache allocation.
err = tk.QueryToErr("select nextval(seq2)")
c.Assert(err, IsNil)
sequenceTable = testGetTableByName(c, tk.Se, "test2", "seq2")
tc, ok = sequenceTable.(*tables.TableCommon)
c.Assert(ok, Equals, true)
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
c.Assert(end, Equals, int64(-3))
c.Assert(round, Equals, int64(0))
ok = mustGetDDLBinlog(s, "select setval(`test2`.`seq2`, -3)", c)
c.Assert(ok, IsTrue)
tk.MustExec("select setval(seq2, -100)")
// trigger the sequence cache allocation.
err = tk.QueryToErr("select nextval(seq2)")
c.Assert(err, IsNil)
_, end, round = tc.GetSequenceCommon().GetSequenceBaseEndRound()
c.Assert(end, Equals, int64(6))
c.Assert(round, Equals, int64(1))
ok = mustGetDDLBinlog(s, "select setval(`test2`.`seq2`, 6)", c)
c.Assert(ok, IsTrue)
// Test dml txn is independent from sequence txn.
tk.MustExec("drop sequence if exists seq")
tk.MustExec("create sequence seq cache 3")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (a int default next value for seq)")
// sequence txn commit first then the dml txn.
tk.MustExec("insert into t values(-1),(default),(-1),(default)")
// binlog list like [... ddl prewrite(offset), ddl commit, dml prewrite]
_, _, offset := getLatestDDLBinlog(c, s.pump, "select setval(`test2`.`seq`, 3)")
s.pump.mu.Lock()
c.Assert(offset+2, Equals, len(s.pump.mu.payloads)-1)
s.pump.mu.Unlock()
}
// Sometimes this test doesn't clean up fail, let the function name begin with 'Z'
// so it runs last and would not disrupt other tests.
func (s *testBinlogSuite) TestZIgnoreError(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.Se.GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int)")
binloginfo.SetIgnoreError(true)
s.pump.mu.Lock()
s.pump.mu.mockFail = true
s.pump.mu.Unlock()
tk.MustExec("insert into t values (1)")
tk.MustExec("insert into t values (1)")
// Clean up.
s.pump.mu.Lock()
s.pump.mu.mockFail = false
s.pump.mu.Unlock()
binloginfo.DisableSkipBinlogFlag()
binloginfo.SetIgnoreError(false)
}
func (s *testBinlogSuite) TestPartitionedTable(c *C) {
// This test checks partitioned table write binlog with table ID, rather than partition ID.
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.Se.GetSessionVars().BinlogClient = s.client
tk.MustExec("drop table if exists t")
tk.MustExec(`create table t (id int) partition by range (id) (
partition p0 values less than (1),
partition p1 values less than (4),
partition p2 values less than (7),
partition p3 values less than (10))`)
tids := make([]int64, 0, 10)
for i := 0; i < 10; i++ {
tk.MustExec("insert into t values (?)", i)
prewriteVal := getLatestBinlogPrewriteValue(c, s.pump)
tids = append(tids, prewriteVal.Mutations[0].TableId)
}
c.Assert(len(tids), Equals, 10)
for i := 1; i < 10; i++ {
c.Assert(tids[i], Equals, tids[0])
}
}
func (s *testBinlogSuite) TestDeleteSchema(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("CREATE TABLE `b1` (`id` int(11) NOT NULL AUTO_INCREMENT, `job_id` varchar(50) NOT NULL, `split_job_id` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`), KEY `b1` (`job_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
tk.MustExec("CREATE TABLE `b2` (`id` int(11) NOT NULL AUTO_INCREMENT, `job_id` varchar(50) NOT NULL, `batch_class` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `bu` (`job_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")
tk.MustExec("insert into b2 (job_id, batch_class) values (2, 'TEST');")
tk.MustExec("insert into b1 (job_id) values (2);")
// This test cover a bug that the final schema and the binlog row inconsistent.
// The final schema of this SQL should be the schema of table b1, rather than the schema of join result.
tk.MustExec("delete from b1 where job_id in (select job_id from b2 where batch_class = 'TEST') or split_job_id in (select job_id from b2 where batch_class = 'TEST');")
tk.MustExec("delete b1 from b2 right join b1 on b1.job_id = b2.job_id and batch_class = 'TEST';")
}
func (s *testBinlogSuite) TestAddSpecialComment(c *C) {
testCase := []struct {
input string
result string
}{
{
"create table t1 (id int ) shard_row_id_bits=2;",
"create table t1 (id int ) /*!90000 shard_row_id_bits=2 */ ;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 pre_split_regions=2;",
"create table t1 (id int ) /*!90000 shard_row_id_bits=2 pre_split_regions=2 */ ;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 pre_split_regions=2;",
"create table t1 (id int ) /*!90000 shard_row_id_bits=2 pre_split_regions=2 */ ;",
},
{
"create table t1 (id int ) shard_row_id_bits=2 engine=innodb pre_split_regions=2;",
"create table t1 (id int ) /*!90000 shard_row_id_bits=2 pre_split_regions=2 */ engine=innodb ;",
},
{
"create table t1 (id int ) pre_split_regions=2 shard_row_id_bits=2;",
"create table t1 (id int ) /*!90000 shard_row_id_bits=2 pre_split_regions=2 */ ;",
},
{
"create table t6 (id int ) shard_row_id_bits=2 shard_row_id_bits=3 pre_split_regions=2;",
"create table t6 (id int ) /*!90000 shard_row_id_bits=2 shard_row_id_bits=3 pre_split_regions=2 */ ;",
},
{
"create table t1 (id int primary key auto_random(2));",
"create table t1 (id int primary key /*T!30100 auto_random(2) */ );",
},
{
"create table t1 (id int auto_random ( 4 ) primary key);",
"create table t1 (id int /*T!30100 auto_random ( 4 ) */ primary key);",
},
{
"create table t1 (id int auto_random ( 4 ) primary key);",
"create table t1 (id int /*T!30100 auto_random ( 4 ) */ primary key);",
},
}
for _, ca := range testCase {
re := binloginfo.AddSpecialComment(ca.input)
c.Assert(re, Equals, ca.result)
}
}
func mustGetDDLBinlog(s *testBinlogSuite, ddlQuery string, c *C) (matched bool) {
for i := 0; i < 100; i++ {
preDDL, commitDDL, _ := getLatestDDLBinlog(c, s.pump, ddlQuery)
if preDDL != nil && commitDDL != nil {
if preDDL.DdlJobId == commitDDL.DdlJobId {
c.Assert(commitDDL.StartTs, Equals, preDDL.StartTs)
c.Assert(commitDDL.CommitTs, Greater, commitDDL.StartTs)
matched = true
break
}
}
time.Sleep(time.Millisecond * 30)
}
return
}
func testGetTableByName(c *C, ctx sessionctx.Context, db, table string) table.Table {
dom := domain.GetDomain(ctx)
// Make sure the table schema is the new schema.
err := dom.Reload()
c.Assert(err, IsNil)
tbl, err := dom.InfoSchema().TableByName(model.NewCIStr(db), model.NewCIStr(table))
c.Assert(err, IsNil)
return tbl
}
|
[
"\"log_level\""
] |
[] |
[
"log_level"
] |
[]
|
["log_level"]
|
go
| 1 | 0 | |
keecenter/settings.py
|
"""
Django settings for keecenter project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import dj_database_url
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'x43)ex0#op5!d1iug^j*o(w5@xs#0_=)v@koa2&z3m&s1(v)e*')
ALLOWED_HOSTS = ['127.0.0.1', 'keecenter.herokuapp.com', 'localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'django_summernote',
'rest_framework',
'rest_framework.authtoken',
'djoser',
'public',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'keecenter.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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 = 'keecenter.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keecenter_db',
'USER': 'physic',
'PASSWORD': '123RqweFasdVzxc$',
'HOST': 'localhost',
'PORT': '5432',
}
}
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'uk'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE = 1
# Media connection settings
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
'rest_framework.permissions.AllowAny',
),
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS':
'rest_framework_json_api.pagination.PageNumberPagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_json_api.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
}
try:
from .local_settings import *
except ImportError:
from .prod_settings import *
|
[] |
[] |
[
"SECRET_KEY"
] |
[]
|
["SECRET_KEY"]
|
python
| 1 | 0 | |
samcli/commands/local/lib/local_lambda.py
|
"""
Implementation of Local Lambda runner
"""
import os
import logging
import boto3
from samcli.local.lambdafn.env_vars import EnvironmentVariables
from samcli.local.lambdafn.config import FunctionConfig
from samcli.local.lambdafn.exceptions import FunctionNotFound
LOG = logging.getLogger(__name__)
class LocalLambdaRunner(object):
"""
Runs Lambda functions locally. This class is a wrapper around the `samcli.local` library which takes care
of actually running the function on a Docker container.
"""
PRESENT_DIR = "."
MAX_DEBUG_TIMEOUT = 36000 # 10 hours in seconds
def __init__(self,
local_runtime,
function_provider,
cwd,
env_vars_values=None,
aws_profile=None,
debug_context=None,
aws_region=None):
"""
Initializes the class
:param samcli.local.lambdafn.runtime.LambdaRuntime local_runtime: Lambda runtime capable of running a function
:param samcli.commands.local.lib.provider.FunctionProvider function_provider: Provider that can return a
Lambda function
:param string cwd: Current working directory. We will resolve all function CodeURIs relative to this directory.
:param dict env_vars_values: Optional. Dictionary containing values of environment variables
:param integer debug_port: Optional. Port to bind the debugger to
:param string debug_args: Optional. Additional arguments passed to the debugger
:param string aws_profile: Optional. AWS Credentials profile to use
:param string aws_region: Optional. AWS region to use
"""
self.local_runtime = local_runtime
self.provider = function_provider
self.cwd = cwd
self.env_vars_values = env_vars_values or {}
self.aws_profile = aws_profile
self.aws_region = aws_region
self.debug_context = debug_context
def invoke(self, function_name, event, stdout=None, stderr=None):
"""
Find the Lambda function with given name and invoke it. Pass the given event to the function and return
response through the given streams.
This function will block until either the function completes or times out.
:param string function_name: Name of the Lambda function to invoke
:param string event: Event data passed to the function. Must be a valid JSON String.
:param io.BaseIO stdout: Stream to write the output of the Lambda function to.
:param io.BaseIO stderr: Stream to write the Lambda runtime logs to.
:raises FunctionNotfound: When we cannot find a function with the given name
"""
# Generate the correct configuration based on given inputs
function = self.provider.get(function_name)
if not function:
raise FunctionNotFound("Unable to find a Function with name '%s'", function_name)
LOG.debug("Found one Lambda function with name '%s'", function_name)
LOG.info("Invoking %s (%s)", function.handler, function.runtime)
config = self._get_invoke_config(function)
# Invoke the function
self.local_runtime.invoke(config, event, debug_context=self.debug_context, stdout=stdout, stderr=stderr)
def is_debugging(self):
"""
Are we debugging the invoke?
Returns
-------
bool
True, if we are debugging the invoke ie. the Docker container will break into the debugger and wait for
attach
"""
return bool(self.debug_context)
def _get_invoke_config(self, function):
"""
Returns invoke configuration to pass to Lambda Runtime to invoke the given function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime
"""
env_vars = self._make_env_vars(function)
code_abs_path = self._get_code_path(function.codeuri)
LOG.debug("Resolved absolute path to code is %s", code_abs_path)
function_timeout = function.timeout
# The Runtime container handles timeout inside the container. When debugging with short timeouts, this can
# cause the container execution to stop. When in debug mode, we set the timeout in the container to a max 10
# hours. This will ensure the container doesn't unexpectedly stop while debugging function code
if self.is_debugging():
function_timeout = self.MAX_DEBUG_TIMEOUT
return FunctionConfig(name=function.name,
runtime=function.runtime,
handler=function.handler,
code_abs_path=code_abs_path,
memory=function.memory,
timeout=function_timeout,
env_vars=env_vars)
def _make_env_vars(self, function):
"""
Returns the environment variables configuration for this function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.env_vars.EnvironmentVariables: Environment variable configuration for this
function
"""
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
else:
LOG.debug("No environment variables found for function '%s'", name)
# This could either be in standard format, or a CloudFormation parameter file format.
#
# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}
# CloudFormation parameter file is {"Parameters": {key:value}}
if "Parameters" in self.env_vars_values:
LOG.debug("Environment variables overrides data is in CloudFormation parameter file format")
# CloudFormation parameter file format
overrides = self.env_vars_values["Parameters"]
else:
# Standard format
LOG.debug("Environment variables overrides data is standard format")
overrides = self.env_vars_values.get(name, None)
shell_env = os.environ
aws_creds = self.get_aws_creds()
return EnvironmentVariables(function.memory,
function.timeout,
function.handler,
variables=variables,
shell_env_values=shell_env,
override_values=overrides,
aws_creds=aws_creds)
def _get_code_path(self, codeuri):
"""
Returns path to the function code resolved based on current working directory.
:param string codeuri: CodeURI of the function. This should contain the path to the function code
:return string: Absolute path to the function code
"""
LOG.debug("Resolving code path. Cwd=%s, CodeUri=%s", self.cwd, codeuri)
# First, let us figure out the current working directory.
# If current working directory is not provided, then default to the directory where the CLI is running from
if not self.cwd or self.cwd == self.PRESENT_DIR:
self.cwd = os.getcwd()
# Make sure cwd is an absolute path
self.cwd = os.path.abspath(self.cwd)
# Next, let us get absolute path of function code.
# Codepath is always relative to current working directory
# If the path is relative, then construct the absolute version
if not os.path.isabs(codeuri):
codeuri = os.path.normpath(os.path.join(self.cwd, codeuri))
return codeuri
def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None
"""
result = {}
LOG.debug("Loading AWS credentials from session with profile '%s'", self.aws_profile)
# TODO: Consider changing it to use boto3 default session. We already have an annotation
# to pass command line arguments for region & profile to setup boto3 default session
session = boto3.session.Session(profile_name=self.aws_profile, region_name=self.aws_region)
if not session:
return result
# Load the credentials from profile/environment
creds = session.get_credentials()
if not creds:
# If we were unable to load credentials, then just return empty. We will use the default
return result
# After loading credentials, region name might be available here.
if hasattr(session, 'region_name') and session.region_name:
result["region"] = session.region_name
# Only add the key, if its value is present
if hasattr(creds, 'access_key') and creds.access_key:
result["key"] = creds.access_key
if hasattr(creds, 'secret_key') and creds.secret_key:
result["secret"] = creds.secret_key
if hasattr(creds, 'token') and creds.token:
result["sessiontoken"] = creds.token
return result
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
pkg/awsclicompat/session.go
|
package awsclicompat
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"os"
)
// NewSession creates a new AWS session for the given AWS region and AWS PROFILE.
//
// The following credential sources are supported:
//
// 1. static credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
// 2. static credentials loaded from profiles (AWS_PROFILE, when AWS_SDK_LOAD_CONFIG=true)
// 3. dynamic credentials obtained by assuming the role using static credentials loaded from the profile (AWS_PROFILE, when AWS_SDK_LOAD_CONFIG=true)
// 4. dynamic credentials obtained by assuming the role using static credentials loaded from the env (FORCE_AWS_PROFILE=true w/ credential_source=Environment)
//
// The fourth option of using FORCE_AWS_PROFILE=true and AWS_PROFILE=yourprofile is equivalent to `aws --profile ${AWS_PROFILE}`.
// See https://github.com/variantdev/vals/issues/19#issuecomment-600437486 for more details and why and when this is needed.
func NewSession(region string, profile string) *session.Session {
var cfg *aws.Config
if region != "" {
cfg = aws.NewConfig().WithRegion(region)
} else {
cfg = aws.NewConfig()
}
opts := session.Options{
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
SharedConfigState: session.SharedConfigEnable,
Config: *cfg,
}
if profile != "" {
opts.Profile = profile
} else if os.Getenv("FORCE_AWS_PROFILE") == "true" {
opts.Profile = os.Getenv("AWS_PROFILE")
}
sess := session.Must(session.NewSessionWithOptions(opts))
return sess
}
|
[
"\"FORCE_AWS_PROFILE\"",
"\"AWS_PROFILE\""
] |
[] |
[
"AWS_PROFILE",
"FORCE_AWS_PROFILE"
] |
[]
|
["AWS_PROFILE", "FORCE_AWS_PROFILE"]
|
go
| 2 | 0 | |
tests/test_tinypages.py
|
"""Tests for tinypages build using sphinx extensions."""
import filecmp
import os
from pathlib import Path
from subprocess import Popen, PIPE
import sys
import pytest
pytest.importorskip('sphinx')
@pytest.mark.skipif(os.name == 'nt', reason='path issues on Azure Windows CI')
def test_tinypages(tmpdir):
tmp_path = Path(tmpdir)
html_dir = tmp_path / 'html'
doctree_dir = tmp_path / 'doctrees'
# Build the pages with warnings turned into errors
cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',
'-d', str(doctree_dir),
str(Path(__file__).parent / 'tinypages'), str(html_dir)]
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True,
env={**os.environ, "MPLBACKEND": ""})
out, err = proc.communicate()
assert proc.returncode == 0, \
f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n"
if err:
if err.strip() != 'vtkDebugLeaks has found no leaks.':
pytest.fail(f"sphinx build emitted the following warnings:\n{err}")
assert html_dir.is_dir()
def plot_file(plt, num, subnum):
return html_dir / f'some_plots-{plt}_{num:02d}_{subnum:02d}.png'
# verify directives generating a figure generated figures
assert plot_file(1, 0, 0).exists()
assert plot_file(2, 0, 0).exists()
assert plot_file(4, 0, 0).exists()
assert plot_file(8, 0, 0).exists()
assert plot_file(9, 0, 0).exists()
assert plot_file(9, 1, 0).exists()
# test skip directive
assert not plot_file(10, 0, 0).exists()
# verify external file generated figure
cone_file = html_dir / f'plot_cone_00_00.png'
assert cone_file.exists()
html_contents = (html_dir / 'some_plots.html').read_bytes()
assert b'# Only a comment' in html_contents
# check if figure caption made it into html file
assert b'This is the caption for plot 8.' in html_contents
# check if figure caption using :caption: made it into html file
assert b'Plot 10 uses the caption option.' in html_contents
# check that the multi-image caption is applied twice
assert html_contents.count(b'This caption applies to both plots.') == 2
assert b'you should not be reading this right now' not in html_contents
assert b'should be printed: include-source with no args' in html_contents
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
dev1/src/conf/conf.go
|
package conf
import (
"errors"
"os"
"util"
)
var (
// Conf : holds the global app config.
Conf config
)
type config struct {
ReleaseMode bool
LogLevel string
App app
Weixin weixin
Env string
}
type app struct {
Host string
Port string
}
type weixin struct {
AppID string
AppSecret string
}
func init() {
}
// InitConfig initializes the app configuration by first setting defaults,
// then overriding settings from the app config file, then overriding
// It returns an error if any.
func InitConfig() error {
res := util.TestOSENV([]string{"APP_HOST", "APP_PORT", "ENV", "APPID", "APP_SECRET"})
if !res {
return errors.New("Lack environment variables")
}
Conf.App = app{
Host: os.Getenv("APP_HOST"),
Port: os.Getenv("APP_PORT"),
}
Conf.Weixin = weixin{
AppID: os.Getenv("APPID"),
AppSecret: os.Getenv("APP_SECRET"),
}
Conf.Env = os.Getenv("ENV")
if Conf.Env == "prod" {
Conf.LogLevel = "info"
} else {
Conf.LogLevel = "debug"
}
return nil
}
|
[
"\"APP_HOST\"",
"\"APP_PORT\"",
"\"APPID\"",
"\"APP_SECRET\"",
"\"ENV\""
] |
[] |
[
"APP_HOST",
"ENV",
"APP_PORT",
"APP_SECRET",
"APPID"
] |
[]
|
["APP_HOST", "ENV", "APP_PORT", "APP_SECRET", "APPID"]
|
go
| 5 | 0 | |
.vscode/extensions/ms-python.python-2020.3.69010/pythonFiles/lib/python/old_ptvsd/ptvsd/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch.py
|
# Defines which version of the trace_dispatch we'll use.
# Should give warning only here if cython is not available but supported.
import os
from _pydevd_bundle.pydevd_constants import CYTHON_SUPPORTED
from _pydev_bundle import pydev_log
use_cython = os.getenv('PYDEVD_USE_CYTHON', None)
dirname = os.path.dirname(os.path.dirname(__file__))
# Do not show incorrect warning for .egg files for Remote debugger
if not CYTHON_SUPPORTED or dirname.endswith('.egg'):
# Do not try to import cython extensions if cython isn't supported
use_cython = 'NO'
def delete_old_compiled_extensions():
import _pydevd_bundle
cython_extensions_dir = os.path.dirname(os.path.dirname(_pydevd_bundle.__file__))
_pydevd_bundle_ext_dir = os.path.dirname(_pydevd_bundle.__file__)
_pydevd_frame_eval_ext_dir = os.path.join(cython_extensions_dir, '_pydevd_frame_eval_ext')
try:
import shutil
for file in os.listdir(_pydevd_bundle_ext_dir):
if file.startswith("pydevd") and file.endswith(".so"):
os.remove(os.path.join(_pydevd_bundle_ext_dir, file))
for file in os.listdir(_pydevd_frame_eval_ext_dir):
if file.startswith("pydevd") and file.endswith(".so"):
os.remove(os.path.join(_pydevd_frame_eval_ext_dir, file))
build_dir = os.path.join(cython_extensions_dir, "build")
if os.path.exists(build_dir):
shutil.rmtree(os.path.join(cython_extensions_dir, "build"))
except OSError:
pydev_log.error_once("warning: failed to delete old cython speedups. Please delete all *.so files from the directories "
"\"%s\" and \"%s\"" % (_pydevd_bundle_ext_dir, _pydevd_frame_eval_ext_dir))
if use_cython == 'YES':
# We must import the cython version if forcing cython
from _pydevd_bundle.pydevd_cython_wrapper import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func
elif use_cython == 'NO':
# Use the regular version if not forcing cython
from _pydevd_bundle.pydevd_trace_dispatch_regular import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func # @UnusedImport
elif use_cython is None:
# Regular: use fallback if not found and give message to user
try:
from _pydevd_bundle.pydevd_cython_wrapper import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func
# This version number is always available
from _pydevd_bundle.pydevd_additional_thread_info_regular import version as regular_version
# This version number from the already compiled cython extension
from _pydevd_bundle.pydevd_cython_wrapper import version as cython_version
if cython_version != regular_version:
# delete_old_compiled_extensions() -- would be ok in dev mode but we don't want to erase
# files from other python versions on release, so, just raise import error here.
raise ImportError('Cython version of speedups does not match.')
except ImportError:
from _pydevd_bundle.pydevd_trace_dispatch_regular import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func # @UnusedImport
pydev_log.show_compile_cython_command_line()
else:
raise RuntimeError('Unexpected value for PYDEVD_USE_CYTHON: %s (accepted: YES, NO)' % (use_cython,))
|
[] |
[] |
[
"PYDEVD_USE_CYTHON"
] |
[]
|
["PYDEVD_USE_CYTHON"]
|
python
| 1 | 0 | |
docs/scripts/docs.go
|
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"os"
"time"
"github.com/renehernandez/appfile/cmd"
"github.com/spf13/cobra"
)
func generateCommandsReference(buffer *bytes.Buffer) {
cmd := cmd.NewRootCmd()
buffer.WriteString("# CLI Reference\n\n")
buffer.WriteString("This is a reference for the `appfile` CLI,")
buffer.WriteString(" which enables you to manage deployments to DigitalOcean App Platform.\n\n")
buffer.WriteString("## Command List\n\n")
buffer.WriteString("The following is a complete list of the commands provided by `appfile`.\n\n")
buffer.WriteString("Command | Description \n")
buffer.WriteString("---- | ---- \n")
for _, c := range cmd.Commands() {
buffer.WriteString(fmt.Sprintf("[%s](#appfile-%s) | %s\n", c.Name(), c.Name(), c.Short))
}
buffer.WriteString("\n")
}
func generateCommandsHelp(buffer *bytes.Buffer) {
cmd := cmd.NewRootCmd()
cmd.DisableAutoGenTag = true
GenMarkdown(cmd, buffer)
for _, c := range cmd.Commands() {
c.DisableAutoGenTag = true
GenMarkdown(c, buffer)
}
}
// GenMarkdown creates markdown output.
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
}
// GenMarkdownCustom creates custom markdown output.
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
cmd.InitDefaultHelpCmd()
cmd.InitDefaultHelpFlag()
buf := new(bytes.Buffer)
name := cmd.CommandPath()
buf.WriteString("## " + name + "\n\n")
buf.WriteString(cmd.Short + "\n\n")
if len(cmd.Long) > 0 {
buf.WriteString("### Synopsis\n\n")
buf.WriteString(cmd.Long + "\n\n")
}
if cmd.Runnable() {
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
}
if len(cmd.Example) > 0 {
buf.WriteString("### Examples\n\n")
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
}
if err := printOptions(buf, cmd, name); err != nil {
return err
}
if !cmd.DisableAutoGenTag {
buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
}
_, err := buf.WriteTo(w)
return err
}
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(buf)
if flags.HasAvailableFlags() {
buf.WriteString("### Options\n\n```\n")
flags.PrintDefaults()
buf.WriteString("```\n\n")
}
parentFlags := cmd.InheritedFlags()
parentFlags.SetOutput(buf)
if parentFlags.HasAvailableFlags() {
buf.WriteString("### Options inherited from parent commands\n\n```\n")
parentFlags.PrintDefaults()
buf.WriteString("```\n\n")
}
return nil
}
func generateCliReference() {
buffer := &bytes.Buffer{}
generateCommandsReference(buffer)
generateCommandsHelp(buffer)
f, err := os.Create("./docs/cli_reference.md")
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err = buffer.WriteTo(f)
if err != nil {
log.Fatal(err)
}
}
func generateRedirect() {
version := os.Getenv("APPFILE_VERSION")
content, err := ioutil.ReadFile("./docs/scripts/index.html.gotmpl")
if err != nil {
log.Fatal(err)
}
if err := os.Mkdir("./docs/redirect", os.ModePerm); err != nil {
log.Fatal(err)
}
f, err := os.Create("./docs/redirect/index.html")
if err != nil {
log.Fatal(err)
}
tmpl := template.Must(template.New("redirect").Parse(string(content)))
tmpl.Execute(f, version)
}
func main() {
generateCliReference()
generateRedirect()
}
|
[
"\"APPFILE_VERSION\""
] |
[] |
[
"APPFILE_VERSION"
] |
[]
|
["APPFILE_VERSION"]
|
go
| 1 | 0 | |
tests/functional/services/catalog/utils/api/conf.py
|
import os
from tests.functional.services.utils import http_utils
CATALOG_API_CONF = http_utils.DEFAULT_API_CONF.copy()
CATALOG_API_CONF["ANCHORE_BASE_URL"] = os.environ.get(
"ANCHORE_CATALOG_URL", "http://engine-catalog:8228/v1"
)
def catalog_api_conf():
return CATALOG_API_CONF
|
[] |
[] |
[
"ANCHORE_CATALOG_URL"
] |
[]
|
["ANCHORE_CATALOG_URL"]
|
python
| 1 | 0 | |
vendor/github.com/ONSdigital/go-ns/log/log.go
|
package log
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/mgutz/ansi"
)
// Namespace is the service namespace used for logging
var Namespace = "service-namespace"
// HumanReadable, if true, outputs log events in a human readable format
var HumanReadable bool
var hrMutex sync.Mutex
func init() {
configureHumanReadable()
}
func configureHumanReadable() {
HumanReadable, _ = strconv.ParseBool(os.Getenv("HUMAN_LOG"))
}
// Data contains structured log data
type Data map[string]interface{}
// Context returns a context ID from a request (using X-Request-Id)
func Context(req *http.Request) string {
return req.Header.Get("X-Request-Id")
}
// Handler wraps a http.Handler and logs the status code and total response time
func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rc := &responseCapture{w, 0}
s := time.Now()
h.ServeHTTP(rc, req)
e := time.Now()
d := e.Sub(s)
Event("request", Context(req), Data{
"start": s,
"end": e,
"duration": d,
"status": rc.statusCode,
"method": req.Method,
"path": req.URL.Path,
})
})
}
type responseCapture struct {
http.ResponseWriter
statusCode int
}
func (r *responseCapture) WriteHeader(status int) {
r.statusCode = status
r.ResponseWriter.WriteHeader(status)
}
func (r *responseCapture) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// Event records an event
var Event = event
func event(name string, context string, data Data) {
m := map[string]interface{}{
"created": time.Now(),
"event": name,
"namespace": Namespace,
}
if len(context) > 0 {
m["context"] = context
}
if data != nil {
m["data"] = data
}
if HumanReadable {
printHumanReadable(name, context, data, m)
return
}
b, err := json.Marshal(&m)
if err != nil {
// This should never happen
// We'll log the error (which for our purposes, can't fail), which
// gives us an indication we have something to investigate
b, _ = json.Marshal(map[string]interface{}{
"created": time.Now(),
"event": "log_error",
"namespace": Namespace,
"context": context,
"data": map[string]interface{}{"error": err.Error()},
})
}
fmt.Fprintf(os.Stdout, "%s\n", b)
}
func printHumanReadable(name, context string, data Data, m map[string]interface{}) {
hrMutex.Lock()
defer hrMutex.Unlock()
ctx := ""
if len(context) > 0 {
ctx = "[" + context + "] "
}
msg := ""
if message, ok := data["message"]; ok {
msg = ": " + fmt.Sprintf("%s", message)
delete(data, "message")
}
if name == "error" && len(msg) == 0 {
if err, ok := data["error"]; ok {
msg = ": " + fmt.Sprintf("%s", err)
delete(data, "error")
}
}
col := ansi.DefaultFG
switch name {
case "error":
col = ansi.LightRed
case "info":
col = ansi.LightCyan
case "trace":
col = ansi.Blue
case "debug":
col = ansi.Green
case "request":
col = ansi.Cyan
}
fmt.Fprintf(os.Stdout, "%s%s %s%s%s%s\n", col, m["created"], ctx, name, msg, ansi.DefaultFG)
if data != nil {
for k, v := range data {
fmt.Fprintf(os.Stdout, " -> %s: %+v\n", k, v)
}
}
}
// ErrorC is a structured error message with context
func ErrorC(context string, err error, data Data) {
if data == nil {
data = Data{}
}
if _, ok := data["error"]; !ok {
data["message"] = err.Error()
data["error"] = err
}
Event("error", context, data)
}
// ErrorR is a structured error message for a request
func ErrorR(req *http.Request, err error, data Data) {
ErrorC(Context(req), err, data)
}
// Error is a structured error message
func Error(err error, data Data) {
ErrorC("", err, data)
}
// DebugC is a structured debug message with context
func DebugC(context string, message string, data Data) {
if data == nil {
data = Data{}
}
if _, ok := data["message"]; !ok {
data["message"] = message
}
Event("debug", context, data)
}
// DebugR is a structured debug message for a request
func DebugR(req *http.Request, message string, data Data) {
DebugC(Context(req), message, data)
}
// Debug is a structured trace message
func Debug(message string, data Data) {
DebugC("", message, data)
}
// TraceC is a structured trace message with context
func TraceC(context string, message string, data Data) {
if data == nil {
data = Data{}
}
if _, ok := data["message"]; !ok {
data["message"] = message
}
Event("trace", context, data)
}
// TraceR is a structured trace message for a request
func TraceR(req *http.Request, message string, data Data) {
TraceC(Context(req), message, data)
}
// Trace is a structured trace message
func Trace(message string, data Data) {
TraceC("", message, data)
}
// InfoC is a structured info message with context
func InfoC(context string, message string, data Data) {
if data == nil {
data = Data{}
}
if _, ok := data["message"]; !ok {
data["message"] = message
}
Event("info", context, data)
}
// InfoR is a structured info message for a request
func InfoR(req *http.Request, message string, data Data) {
InfoC(Context(req), message, data)
}
// Info is a structured info message
func Info(message string, data Data) {
InfoC("", message, data)
}
|
[
"\"HUMAN_LOG\""
] |
[] |
[
"HUMAN_LOG"
] |
[]
|
["HUMAN_LOG"]
|
go
| 1 | 0 | |
app/server_inactivity.go
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"fmt"
"os"
"strconv"
"time"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
"github.com/mattermost/mattermost-server/v6/store"
)
const serverInactivityHours = 100
func (s *Server) doInactivityCheck() {
if !*s.Config().EmailSettings.EnableInactivityEmail {
mlog.Info("No activity check because EnableInactivityEmail is false")
return
}
if !s.Config().FeatureFlags.EnableInactivityCheckJob {
mlog.Info("No activity check because EnableInactivityCheckJob feature flag is disabled")
return
}
inactivityDurationHoursEnv := os.Getenv("MM_INACTIVITY_DURATION")
inactivityDurationHours, parseError := strconv.ParseFloat(inactivityDurationHoursEnv, 64)
if parseError != nil {
// default to 100 hours
inactivityDurationHours = serverInactivityHours
}
systemValue, sysValErr := s.Store.System().GetByName("INACTIVITY")
if sysValErr != nil {
// any other error apart from ErrNotFound we stop execution
if _, ok := sysValErr.(*store.ErrNotFound); !ok {
mlog.Warn("An error occurred while getting INACTIVITY from system store", mlog.Err(sysValErr))
return
}
}
// If we have a system value, it means this job already ran atleast once.
// we then check the last time the job ran plus the last time a post was made to determine if we
// can remind the user to use workspace again. If no post was made, we check the last time they logged in (session)
// and determine whether to send them a reminder.
if systemValue != nil {
sysT, _ := strconv.ParseInt(systemValue.Value, 10, 64)
tt := time.Unix(sysT/1000, 0)
timeLastSentInactivityEmail := time.Since(tt).Hours()
lastPostAt, _ := s.Store.Post().GetLastPostRowCreateAt()
if lastPostAt != 0 {
posT := time.Unix(lastPostAt/1000, 0)
timeForLastPost := time.Since(posT).Hours()
if timeLastSentInactivityEmail > inactivityDurationHours && timeForLastPost > inactivityDurationHours {
s.takeInactivityAction()
}
return
}
lastSessionAt, _ := s.Store.Session().GetLastSessionRowCreateAt()
if lastSessionAt != 0 {
sesT := time.Unix(lastSessionAt/1000, 0)
timeForLastSession := time.Since(sesT).Hours()
if timeLastSentInactivityEmail > inactivityDurationHours && timeForLastSession > inactivityDurationHours {
s.takeInactivityAction()
}
return
}
}
// The first time this job runs. We check if the user has not made any posts
// and remind them to use the workspace. If no posts have been made. We check the last time
// they logged in (session) and send a reminder.
lastPostAt, _ := s.Store.Post().GetLastPostRowCreateAt()
if lastPostAt != 0 {
posT := time.Unix(lastPostAt/1000, 0)
timeForLastPost := time.Since(posT).Hours()
if timeForLastPost > inactivityDurationHours {
s.takeInactivityAction()
}
return
}
lastSessionAt, _ := s.Store.Session().GetLastSessionRowCreateAt()
if lastSessionAt != 0 {
sesT := time.Unix(lastSessionAt/1000, 0)
timeForLastSession := time.Since(sesT).Hours()
if timeForLastSession > inactivityDurationHours {
s.takeInactivityAction()
}
return
}
}
func (s *Server) takeInactivityAction() {
siteURL := *s.Config().ServiceSettings.SiteURL
if siteURL == "" {
mlog.Warn("No SiteURL configured")
}
properties := map[string]interface{}{
"SiteURL": siteURL,
}
s.GetTelemetryService().SendTelemetry("inactive_server", properties)
users, err := s.Store.User().GetSystemAdminProfiles()
if err != nil {
mlog.Error("Failed to get system admins for inactivity check from Mattermost.")
return
}
for _, user := range users {
// See https://go.dev/doc/faq#closures_and_goroutines for why we make this assignment
user := user
if user.Email == "" {
mlog.Error("Invalid system admin email.", mlog.String("user_email", user.Email))
continue
}
name := user.FirstName
if name == "" {
name = user.Username
}
mlog.Debug("Sending inactivity reminder email.", mlog.String("user_email", user.Email))
s.Go(func() {
if err := s.EmailService.SendLicenseInactivityEmail(user.Email, name, user.Locale, siteURL); err != nil {
mlog.Error("Error while sending inactivity reminder email.", mlog.String("user_email", user.Email), mlog.Err(err))
}
})
}
// Mark time that we sent emails. The next time we calculate
sysVar := &model.System{Name: "INACTIVITY", Value: fmt.Sprint(model.GetMillis())}
if err := s.Store.System().SaveOrUpdate(sysVar); err != nil {
mlog.Error("Unable to save INACTIVITY", mlog.Err(err))
}
// do some telemetry about sending the email
s.GetTelemetryService().SendTelemetry("inactive_server_emails_sent", properties)
}
|
[
"\"MM_INACTIVITY_DURATION\""
] |
[] |
[
"MM_INACTIVITY_DURATION"
] |
[]
|
["MM_INACTIVITY_DURATION"]
|
go
| 1 | 0 | |
services/network/mgmt/2020-04-01/network/watchers.go
|
package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// WatchersClient is the network Client
type WatchersClient struct {
BaseClient
}
// NewWatchersClient creates an instance of the WatchersClient client.
func NewWatchersClient(subscriptionID string) WatchersClient {
return NewWatchersClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWatchersClientWithBaseURI creates an instance of the WatchersClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWatchersClientWithBaseURI(baseURI string, subscriptionID string) WatchersClient {
return WatchersClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CheckConnectivity verifies the possibility of establishing a direct TCP connection from a virtual machine to a given
// endpoint including another VM or an arbitrary remote server.
// Parameters:
// resourceGroupName - the name of the network watcher resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that determine how the connectivity check will be performed.
func (client WatchersClient) CheckConnectivity(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (result WatchersCheckConnectivityFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CheckConnectivity")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Source", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}}},
{Target: "parameters.Destination", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "CheckConnectivity", err.Error())
}
req, err := client.CheckConnectivityPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", nil, "Failure preparing request")
return
}
result, err = client.CheckConnectivitySender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", nil, "Failure sending request")
return
}
return
}
// CheckConnectivityPreparer prepares the CheckConnectivity request.
func (client WatchersClient) CheckConnectivityPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectivityCheck", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CheckConnectivitySender sends the CheckConnectivity request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) CheckConnectivitySender(req *http.Request) (future WatchersCheckConnectivityFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (ci ConnectivityInformation, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersCheckConnectivityFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if ci.Response.Response, err = future.GetResult(sender); err == nil && ci.Response.Response.StatusCode != http.StatusNoContent {
ci, err = client.CheckConnectivityResponder(ci.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", ci.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// CheckConnectivityResponder handles the response to the CheckConnectivity request. The method always
// closes the http.Response Body.
func (client WatchersClient) CheckConnectivityResponder(resp *http.Response) (result ConnectivityInformation, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// CreateOrUpdate creates or updates a network watcher in the specified resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters that define the network watcher resource.
func (client WatchersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher) (result Watcher, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure responding to request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client WatchersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
parameters.Etag = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client WatchersClient) CreateOrUpdateResponder(resp *http.Response) (result Watcher, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified network watcher resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
func (client WatchersClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string) (result WatchersDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Delete")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", nil, "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client WatchersClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) DeleteSender(req *http.Request) (future WatchersDeleteFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (ar autorest.Response, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersDeleteFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersDeleteFuture")
return
}
ar.Response = future.Response()
return
}
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client WatchersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the specified network watcher by resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
func (client WatchersClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string) (result Watcher, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client WatchersClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetResponder(resp *http.Response) (result Watcher, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAzureReachabilityReport nOTE: This feature is currently in preview and still being tested for stability. Gets the
// relative latency score for internet service providers from a specified location to Azure regions.
// Parameters:
// resourceGroupName - the name of the network watcher resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that determine Azure reachability report configuration.
func (client WatchersClient) GetAzureReachabilityReport(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (result WatchersGetAzureReachabilityReportFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetAzureReachabilityReport")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.ProviderLocation", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.ProviderLocation.Country", Name: validation.Null, Rule: true, Chain: nil}}},
{Target: "parameters.StartTime", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.EndTime", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetAzureReachabilityReport", err.Error())
}
req, err := client.GetAzureReachabilityReportPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", nil, "Failure preparing request")
return
}
result, err = client.GetAzureReachabilityReportSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", nil, "Failure sending request")
return
}
return
}
// GetAzureReachabilityReportPreparer prepares the GetAzureReachabilityReport request.
func (client WatchersClient) GetAzureReachabilityReportPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/azureReachabilityReport", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAzureReachabilityReportSender sends the GetAzureReachabilityReport request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetAzureReachabilityReportSender(req *http.Request) (future WatchersGetAzureReachabilityReportFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (arr AzureReachabilityReport, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetAzureReachabilityReportFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if arr.Response.Response, err = future.GetResult(sender); err == nil && arr.Response.Response.StatusCode != http.StatusNoContent {
arr, err = client.GetAzureReachabilityReportResponder(arr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", arr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetAzureReachabilityReportResponder handles the response to the GetAzureReachabilityReport request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetAzureReachabilityReportResponder(resp *http.Response) (result AzureReachabilityReport, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetFlowLogStatus queries status of flow log and traffic analytics (optional) on a specified resource.
// Parameters:
// resourceGroupName - the name of the network watcher resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that define a resource to query flow log and traffic analytics (optional) status.
func (client WatchersClient) GetFlowLogStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (result WatchersGetFlowLogStatusFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetFlowLogStatus")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetFlowLogStatus", err.Error())
}
req, err := client.GetFlowLogStatusPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", nil, "Failure preparing request")
return
}
result, err = client.GetFlowLogStatusSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", nil, "Failure sending request")
return
}
return
}
// GetFlowLogStatusPreparer prepares the GetFlowLogStatus request.
func (client WatchersClient) GetFlowLogStatusPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetFlowLogStatusSender sends the GetFlowLogStatus request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetFlowLogStatusSender(req *http.Request) (future WatchersGetFlowLogStatusFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (fli FlowLogInformation, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetFlowLogStatusFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent {
fli, err = client.GetFlowLogStatusResponder(fli.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", fli.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetFlowLogStatusResponder handles the response to the GetFlowLogStatus request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetFlowLogStatusResponder(resp *http.Response) (result FlowLogInformation, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetNetworkConfigurationDiagnostic gets Network Configuration Diagnostic data to help customers understand and debug
// network behavior. It provides detailed information on what security rules were applied to a specified traffic flow
// and the result of evaluating these rules. Customers must provide details of a flow like source, destination,
// protocol, etc. The API returns whether traffic was allowed or denied, the rules evaluated for the specified flow and
// the evaluation results.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters to get network configuration diagnostic.
func (client WatchersClient) GetNetworkConfigurationDiagnostic(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (result WatchersGetNetworkConfigurationDiagnosticFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNetworkConfigurationDiagnostic")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.Profiles", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetNetworkConfigurationDiagnostic", err.Error())
}
req, err := client.GetNetworkConfigurationDiagnosticPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", nil, "Failure preparing request")
return
}
result, err = client.GetNetworkConfigurationDiagnosticSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", nil, "Failure sending request")
return
}
return
}
// GetNetworkConfigurationDiagnosticPreparer prepares the GetNetworkConfigurationDiagnostic request.
func (client WatchersClient) GetNetworkConfigurationDiagnosticPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/networkConfigurationDiagnostic", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetNetworkConfigurationDiagnosticSender sends the GetNetworkConfigurationDiagnostic request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetNetworkConfigurationDiagnosticSender(req *http.Request) (future WatchersGetNetworkConfigurationDiagnosticFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (cdr ConfigurationDiagnosticResponse, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetNetworkConfigurationDiagnosticFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent {
cdr, err = client.GetNetworkConfigurationDiagnosticResponder(cdr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", cdr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetNetworkConfigurationDiagnosticResponder handles the response to the GetNetworkConfigurationDiagnostic request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetNetworkConfigurationDiagnosticResponder(resp *http.Response) (result ConfigurationDiagnosticResponse, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetNextHop gets the next hop from the specified VM.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters that define the source and destination endpoint.
func (client WatchersClient) GetNextHop(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (result WatchersGetNextHopFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNextHop")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.SourceIPAddress", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.DestinationIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetNextHop", err.Error())
}
req, err := client.GetNextHopPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", nil, "Failure preparing request")
return
}
result, err = client.GetNextHopSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", nil, "Failure sending request")
return
}
return
}
// GetNextHopPreparer prepares the GetNextHop request.
func (client WatchersClient) GetNextHopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetNextHopSender sends the GetNextHop request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetNextHopSender(req *http.Request) (future WatchersGetNextHopFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (nhr NextHopResult, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetNextHopFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if nhr.Response.Response, err = future.GetResult(sender); err == nil && nhr.Response.Response.StatusCode != http.StatusNoContent {
nhr, err = client.GetNextHopResponder(nhr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", nhr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetNextHopResponder handles the response to the GetNextHop request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetNextHopResponder(resp *http.Response) (result NextHopResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetTopology gets the current network topology by resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters that define the representation of topology.
func (client WatchersClient) GetTopology(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (result Topology, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTopology")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetTopologyPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", nil, "Failure preparing request")
return
}
resp, err := client.GetTopologySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure sending request")
return
}
result, err = client.GetTopologyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure responding to request")
return
}
return
}
// GetTopologyPreparer prepares the GetTopology request.
func (client WatchersClient) GetTopologyPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetTopologySender sends the GetTopology request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetTopologySender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetTopologyResponder handles the response to the GetTopology request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetTopologyResponder(resp *http.Response) (result Topology, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetTroubleshooting initiate troubleshooting on a specified resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that define the resource to troubleshoot.
func (client WatchersClient) GetTroubleshooting(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (result WatchersGetTroubleshootingFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshooting")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.TroubleshootingProperties", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.TroubleshootingProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.TroubleshootingProperties.StoragePath", Name: validation.Null, Rule: true, Chain: nil},
}}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetTroubleshooting", err.Error())
}
req, err := client.GetTroubleshootingPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", nil, "Failure preparing request")
return
}
result, err = client.GetTroubleshootingSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", nil, "Failure sending request")
return
}
return
}
// GetTroubleshootingPreparer prepares the GetTroubleshooting request.
func (client WatchersClient) GetTroubleshootingPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetTroubleshootingSender sends the GetTroubleshooting request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetTroubleshootingSender(req *http.Request) (future WatchersGetTroubleshootingFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (tr TroubleshootingResult, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent {
tr, err = client.GetTroubleshootingResponder(tr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", tr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetTroubleshootingResponder handles the response to the GetTroubleshooting request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetTroubleshootingResponder(resp *http.Response) (result TroubleshootingResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetTroubleshootingResult get the last completed troubleshooting result on a specified resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that define the resource to query the troubleshooting result.
func (client WatchersClient) GetTroubleshootingResult(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (result WatchersGetTroubleshootingResultFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshootingResult")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetTroubleshootingResult", err.Error())
}
req, err := client.GetTroubleshootingResultPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", nil, "Failure preparing request")
return
}
result, err = client.GetTroubleshootingResultSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", nil, "Failure sending request")
return
}
return
}
// GetTroubleshootingResultPreparer prepares the GetTroubleshootingResult request.
func (client WatchersClient) GetTroubleshootingResultPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetTroubleshootingResultSender sends the GetTroubleshootingResult request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetTroubleshootingResultSender(req *http.Request) (future WatchersGetTroubleshootingResultFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (tr TroubleshootingResult, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingResultFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent {
tr, err = client.GetTroubleshootingResultResponder(tr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", tr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetTroubleshootingResultResponder handles the response to the GetTroubleshootingResult request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetTroubleshootingResultResponder(resp *http.Response) (result TroubleshootingResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetVMSecurityRules gets the configured and effective security group rules on the specified VM.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters that define the VM to check security groups for.
func (client WatchersClient) GetVMSecurityRules(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (result WatchersGetVMSecurityRulesFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetVMSecurityRules")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "GetVMSecurityRules", err.Error())
}
req, err := client.GetVMSecurityRulesPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", nil, "Failure preparing request")
return
}
result, err = client.GetVMSecurityRulesSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", nil, "Failure sending request")
return
}
return
}
// GetVMSecurityRulesPreparer prepares the GetVMSecurityRules request.
func (client WatchersClient) GetVMSecurityRulesPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetVMSecurityRulesSender sends the GetVMSecurityRules request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) GetVMSecurityRulesSender(req *http.Request) (future WatchersGetVMSecurityRulesFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (sgvr SecurityGroupViewResult, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersGetVMSecurityRulesFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if sgvr.Response.Response, err = future.GetResult(sender); err == nil && sgvr.Response.Response.StatusCode != http.StatusNoContent {
sgvr, err = client.GetVMSecurityRulesResponder(sgvr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", sgvr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// GetVMSecurityRulesResponder handles the response to the GetVMSecurityRules request. The method always
// closes the http.Response Body.
func (client WatchersClient) GetVMSecurityRulesResponder(resp *http.Response) (result SecurityGroupViewResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all network watchers by resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
func (client WatchersClient) List(ctx context.Context, resourceGroupName string) (result WatcherListResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.List")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.ListPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure responding to request")
return
}
return
}
// ListPreparer prepares the List request.
func (client WatchersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client WatchersClient) ListResponder(resp *http.Response) (result WatcherListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListAll gets all network watchers by subscription.
func (client WatchersClient) ListAll(ctx context.Context) (result WatcherListResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAll")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.ListAllPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", nil, "Failure preparing request")
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure sending request")
return
}
result, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure responding to request")
return
}
return
}
// ListAllPreparer prepares the ListAll request.
func (client WatchersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkWatchers", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListAllSender sends the ListAll request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) ListAllSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListAllResponder handles the response to the ListAll request. The method always
// closes the http.Response Body.
func (client WatchersClient) ListAllResponder(resp *http.Response) (result WatcherListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListAvailableProviders nOTE: This feature is currently in preview and still being tested for stability. Lists all
// available internet service providers for a specified Azure region.
// Parameters:
// resourceGroupName - the name of the network watcher resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that scope the list of available providers.
func (client WatchersClient) ListAvailableProviders(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (result WatchersListAvailableProvidersFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAvailableProviders")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.ListAvailableProvidersPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", nil, "Failure preparing request")
return
}
result, err = client.ListAvailableProvidersSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", nil, "Failure sending request")
return
}
return
}
// ListAvailableProvidersPreparer prepares the ListAvailableProviders request.
func (client WatchersClient) ListAvailableProvidersPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/availableProvidersList", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListAvailableProvidersSender sends the ListAvailableProviders request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) ListAvailableProvidersSender(req *http.Request) (future WatchersListAvailableProvidersFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (apl AvailableProvidersList, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersListAvailableProvidersFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if apl.Response.Response, err = future.GetResult(sender); err == nil && apl.Response.Response.StatusCode != http.StatusNoContent {
apl, err = client.ListAvailableProvidersResponder(apl.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", apl.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// ListAvailableProvidersResponder handles the response to the ListAvailableProviders request. The method always
// closes the http.Response Body.
func (client WatchersClient) ListAvailableProvidersResponder(resp *http.Response) (result AvailableProvidersList, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// SetFlowLogConfiguration configures flow log and traffic analytics (optional) on a specified resource.
// Parameters:
// resourceGroupName - the name of the network watcher resource group.
// networkWatcherName - the name of the network watcher resource.
// parameters - parameters that define the configuration of flow log.
func (client WatchersClient) SetFlowLogConfiguration(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (result WatchersSetFlowLogConfigurationFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.SetFlowLogConfiguration")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.FlowLogProperties", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "parameters.FlowLogProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.FlowLogProperties.Enabled", Name: validation.Null, Rule: true, Chain: nil},
}}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "SetFlowLogConfiguration", err.Error())
}
req, err := client.SetFlowLogConfigurationPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", nil, "Failure preparing request")
return
}
result, err = client.SetFlowLogConfigurationSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", nil, "Failure sending request")
return
}
return
}
// SetFlowLogConfigurationPreparer prepares the SetFlowLogConfiguration request.
func (client WatchersClient) SetFlowLogConfigurationPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// SetFlowLogConfigurationSender sends the SetFlowLogConfiguration request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) SetFlowLogConfigurationSender(req *http.Request) (future WatchersSetFlowLogConfigurationFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (fli FlowLogInformation, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersSetFlowLogConfigurationFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent {
fli, err = client.SetFlowLogConfigurationResponder(fli.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", fli.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// SetFlowLogConfigurationResponder handles the response to the SetFlowLogConfiguration request. The method always
// closes the http.Response Body.
func (client WatchersClient) SetFlowLogConfigurationResponder(resp *http.Response) (result FlowLogInformation, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// UpdateTags updates a network watcher tags.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters supplied to update network watcher tags.
func (client WatchersClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (result Watcher, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.UpdateTags")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", nil, "Failure preparing request")
return
}
resp, err := client.UpdateTagsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure sending request")
return
}
result, err = client.UpdateTagsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure responding to request")
return
}
return
}
// UpdateTagsPreparer prepares the UpdateTags request.
func (client WatchersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateTagsSender sends the UpdateTags request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// UpdateTagsResponder handles the response to the UpdateTags request. The method always
// closes the http.Response Body.
func (client WatchersClient) UpdateTagsResponder(resp *http.Response) (result Watcher, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// VerifyIPFlow verify IP flow from the specified VM to a location given the currently configured NSG rules.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkWatcherName - the name of the network watcher.
// parameters - parameters that define the IP flow to be verified.
func (client WatchersClient) VerifyIPFlow(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (result WatchersVerifyIPFlowFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.VerifyIPFlow")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.LocalPort", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.RemotePort", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.LocalIPAddress", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.RemoteIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("network.WatchersClient", "VerifyIPFlow", err.Error())
}
req, err := client.VerifyIPFlowPreparer(ctx, resourceGroupName, networkWatcherName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", nil, "Failure preparing request")
return
}
result, err = client.VerifyIPFlowSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", nil, "Failure sending request")
return
}
return
}
// VerifyIPFlowPreparer prepares the VerifyIPFlow request.
func (client WatchersClient) VerifyIPFlowPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkWatcherName": autorest.Encode("path", networkWatcherName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// VerifyIPFlowSender sends the VerifyIPFlow request. The method will close the
// http.Response Body if it receives an error.
func (client WatchersClient) VerifyIPFlowSender(req *http.Request) (future WatchersVerifyIPFlowFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client WatchersClient) (vifr VerificationIPFlowResult, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("network.WatchersVerifyIPFlowFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if vifr.Response.Response, err = future.GetResult(sender); err == nil && vifr.Response.Response.StatusCode != http.StatusNoContent {
vifr, err = client.VerifyIPFlowResponder(vifr.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", vifr.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// VerifyIPFlowResponder handles the response to the VerifyIPFlow request. The method always
// closes the http.Response Body.
func (client WatchersClient) VerifyIPFlowResponder(resp *http.Response) (result VerificationIPFlowResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
praw_practice.py
|
import praw
import os
from dotenv import load_dotenv
load_dotenv()
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")
reddit = praw.Reddit(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent='testscript',
username=USERNAME,
password=PASSWORD)
subreddit = reddit.subreddit('python')
hot_python = subreddit.hot(limit=5)
for post in hot_python:
if not post.stickied:
print('Title: {}, Upvotes: {}, Downvotes: {}\n'.format(
post.title,
post.ups,
post.downs))
|
[] |
[] |
[
"USERNAME",
"CLIENT_SECRET",
"PASSWORD",
"CLIENT_ID"
] |
[]
|
["USERNAME", "CLIENT_SECRET", "PASSWORD", "CLIENT_ID"]
|
python
| 4 | 0 | |
config.py
|
import os
EXCHANGE_URL = "http://localhost:8080/"
MARKET_NAME = "TESTNET3RINKEBY"
MONEY_NAME = "TESTNET3"
STOCK_NAME = "RINKEBY"
BTC_ETH_PRICE_URL = "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC"
BTC_ETH_PRICE_ERROR_PRC = float(os.getenv('BTC_ETH_PRICE_ERROR_PRC', 0))
BOT_USER_ID = int(os.getenv('BOT_USER_ID', -666))
BOT_TRADE_BALANCE_PRC = float(os.getenv('BOT_TRADE_BALANCE_PRC', 1))
BOT_SPREAD_PRC = float(os.getenv('BOT_SPREAD_PRC', 0.1))
BOT_BUY_PROB = float(os.getenv('BOT_BUY_PROB', 0.5))
|
[] |
[] |
[
"BOT_SPREAD_PRC",
"BOT_TRADE_BALANCE_PRC",
"BOT_BUY_PROB",
"BOT_USER_ID",
"BTC_ETH_PRICE_ERROR_PRC"
] |
[]
|
["BOT_SPREAD_PRC", "BOT_TRADE_BALANCE_PRC", "BOT_BUY_PROB", "BOT_USER_ID", "BTC_ETH_PRICE_ERROR_PRC"]
|
python
| 5 | 0 | |
src/robust_deid/sequence_tagging/evaluation/note_evaluation/note_token_evaluation.py
|
from collections import Counter
from typing import Sequence, List, Tuple, Union, Type, Optional
from seqeval.reporters import DictReporter
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix
class NoteTokenEvaluation(object):
"""
This class is used to evaluate token level precision, recall and F1 scores.
Script to evaluate at a token level. Calculate precision, recall, and f1 metrics
at the token level rather than the span level.
"""
@staticmethod
def unpack_nested_list(nested_list: Sequence[Sequence[str]]) -> List[str]:
"""
Use this function to unpack a nested list and also for token level evaluation we dont
need to consider the B, I prefixes (depending on the NER notation, so remove that as well.
Args:
nested_list (Sequence[Sequence[str]]): A nested list of predictions/labels
Returns:
(List[str]): Unpacked nested list of predictions/labels
"""
return [inner if inner == 'O' else inner[2:] for nested in nested_list for inner in nested]
@staticmethod
def get_counts(sequence: Sequence[str], ner_types: Sequence[str]) -> List[int]:
"""
Use this function to get the counts for each NER type
Args:
ner_list (Sequence[str]): A list of the NER labels/predicitons
Returns:
(List[int]): Position 0 contains the counts for the NER type that corresponds to position 0
"""
counts = Counter()
counts.update(sequence)
return [counts[ner_type] for ner_type in ner_types]
@staticmethod
def precision_recall_fscore(
labels: Sequence[str],
predictions: Sequence[str],
ner_types: Sequence[str],
average: Optional[str] = None
) -> Tuple[Union[float, List[float]], Union[float, List[float]], Union[float, List[float]], Union[int, List[int]]]:
"""
Use this function to get the token level precision, recall and fscore. Internally we use the
sklearn precision_score, recall_score and f1 score functions. Also return the count of each
NER type.
Args:
labels (Sequence[str]): A list of the gold standard NER labels
predictions (Sequence[str]): A list of the predicted NER labels
average (Optional[str]): None for per NER types scores, or pass an appropriate average value
Returns:
eval_precision (Union[float, List[float]]): precision score (averaged or per ner type)
eval_precision (Union[float, List[float]]): recall score (averaged or per ner type)
eval_precision (Union[float, List[float]]): F1 score (averaged or per ner type)
counts (Union[int, List[int]]): Counts (total or per ner type)
"""
eval_precision = precision_score(y_true=labels, y_pred=predictions, labels=ner_types, average=average)
eval_recall = recall_score(y_true=labels, y_pred=predictions, labels=ner_types, average=average)
eval_f1 = f1_score(y_true=labels, y_pred=predictions, labels=ner_types, average=average)
counts = NoteTokenEvaluation.get_counts(sequence=labels, ner_types=ner_types)
if (average == None):
eval_precision = list(eval_precision)
eval_recall = list(eval_recall)
eval_f1 = list(eval_f1)
else:
counts = sum(counts)
return eval_precision, eval_recall, eval_f1, counts
@staticmethod
def get_confusion_matrix(labels: Sequence[str], predictions: Sequence[str], ner_types: Sequence[str]):
"""
Use this function to get the token level precision, recall and fscore per NER type
and also the micro, macro and weighted averaged precision, recall and f scores.
Essentially we return a classification report
Args:
labels (Sequence[str]): A list of the gold standard NER labels
predictions (Sequence[str]): A list of the predicted NER labels
Returns:
(Type[DictReporter]): Classification report
"""
labels = NoteTokenEvaluation.unpack_nested_list(labels)
predictions = NoteTokenEvaluation.unpack_nested_list(predictions)
return confusion_matrix(y_true=labels, y_pred=predictions, labels=ner_types + ['O', ])
@staticmethod
def classification_report(
labels: Sequence[Sequence[str]],
predictions: Sequence[Sequence[str]],
ner_types: Sequence[str]
) -> Type[DictReporter]:
"""
Use this function to get the token level precision, recall and fscore per NER type
and also the micro, macro and weighted averaged precision, recall and f scores.
Essentially we return a classification report which contains all this information
Args:
labels (Sequence[Sequence[str]]): A list of the gold standard NER labels for each note
predictions (Sequence[Sequence[str]]): A list of the predicted NER labels for each note
Returns:
(Type[DictReporter]): Classification report that contains the token level metric scores
"""
# Unpack the nested lists (labels and predictions) before running the evaluation metrics
labels = NoteTokenEvaluation.unpack_nested_list(nested_list=labels)
predictions = NoteTokenEvaluation.unpack_nested_list(nested_list=predictions)
# Store results in this and return this object
reporter = DictReporter()
# Calculate precision, recall and f1 for each NER type
eval_precision, eval_recall, eval_f1, counts = NoteTokenEvaluation.precision_recall_fscore(
labels=labels,
predictions=predictions,
ner_types=ner_types,
average=None
)
# Store the results
for row in zip(ner_types, eval_precision, eval_recall, eval_f1, counts):
reporter.write(*row)
reporter.write_blank()
# Calculate the overall precision, recall and f1 - based on the defined averages
average_options = ('micro', 'macro', 'weighted')
for average in average_options:
eval_precision, eval_recall, eval_f1, counts = NoteTokenEvaluation.precision_recall_fscore(
labels=labels,
predictions=predictions,
ner_types=ner_types,
average=average
)
# Store the results
reporter.write('{} avg'.format(average), eval_precision, eval_recall, eval_f1, counts)
reporter.write_blank()
# Return the token level results
return reporter.report()
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
migrations/test/upperhash_test.go
|
// +build integration
package upperhash_test
import (
"database/sql"
"fmt"
"os"
"testing"
"time"
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var conn *sql.DB
func TestMain(m *testing.M) {
dbURI := os.Getenv("TEST_DB_URI")
if dbURI == "" {
fmt.Println("environment variable TEST_DB_URI unset")
os.Exit(1)
}
// connect to DB
var err error
conn, err = sql.Open("postgres", dbURI)
if err != nil {
fmt.Printf("error connect to DB at %q: %s\n", dbURI, err)
os.Exit(1)
}
// check DB connection
for i := 0; i < 10; i++ {
err = conn.Ping()
if err == nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if err != nil {
fmt.Printf("error ping DB at %q: %s\n", dbURI, err)
os.Exit(1)
}
// run tests
os.Exit(m.Run())
}
func UpperHash(t *testing.T) {
row := conn.QueryRow("SELECT upper_md5($1::text)", "hello, world")
var hash string
if err := row.Scan(&hash); err != nil {
require.NoError(t, err)
}
assert.Equal(t, "E4D7F1B4ED2E42D15898F4B27B019DA4", hash)
}
|
[
"\"TEST_DB_URI\""
] |
[] |
[
"TEST_DB_URI"
] |
[]
|
["TEST_DB_URI"]
|
go
| 1 | 0 | |
modules/infra/flamepaw/main.go
|
package main
import (
"flamepaw/cli"
"flamepaw/common"
"fmt"
"io"
"os"
"os/exec"
"strings"
log "github.com/sirupsen/logrus"
)
func main() {
lvl, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
lvl = "debug"
}
ll, err := log.ParseLevel(lvl)
if err != nil {
ll = log.DebugLevel
}
log.SetLevel(ll)
if common.CliCmd == "server" {
cli.Server()
} else if common.CliCmd == "test" {
cli.Test()
} else {
cmdFunc := strings.ReplaceAll(common.CliCmd, ".", "_")
pyCmd := "from modules.core._manage import " + cmdFunc + "; " + cmdFunc + "()"
log.Info("Running " + common.PythonPath + " -c '" + pyCmd + "'")
os.Setenv("MAIN_TOKEN", common.MainBotToken)
os.Setenv("CLIENT_SECRET", common.ClientSecret)
os.Setenv("PYTHONPYCACHEPREFIX", common.RootPath+"/data/pycache")
if os.Getenv("PYLOG_LEVEL") != "debug" {
os.Setenv("LOGURU_LEVEL", "INFO")
}
devserver := exec.Command(common.PythonPath, "-c", pyCmd)
if common.CliCmd == "db.setup" {
log.Info("Applying stdin patch")
userInput := make(chan string)
go readInput(userInput)
stdin, err := devserver.StdinPipe()
if err != nil {
log.Fatal(err)
}
go func() {
defer stdin.Close()
io.WriteString(stdin, <-userInput)
}()
}
devserver.Dir = common.RootPath
devserver.Env = os.Environ()
devserver.Stdout = os.Stdout
devserver.Stderr = os.Stderr
devserver.Run()
}
os.Exit(0)
}
// STDIN patch
func readInput(input chan<- string) {
for {
var u string
_, err := fmt.Scanf("%s\n", &u)
if err != nil {
panic(err)
}
input <- u
}
}
|
[
"\"PYLOG_LEVEL\""
] |
[] |
[
"PYLOG_LEVEL"
] |
[]
|
["PYLOG_LEVEL"]
|
go
| 1 | 0 | |
python-webrtc/python/tgcalls_test.py
|
# tgcalls - a Python binding for C++ library by Telegram
# pytgcalls - a library connecting the Python binding with MTProto
# Copyright (C) 2020-2021 Il`ya (Marshal) <https://github.com/MarshalX>
#
# This file is part of tgcalls and pytgcalls.
#
# tgcalls and pytgcalls is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# tgcalls and pytgcalls is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with tgcalls. If not, see <http://www.gnu.org/licenses/>.
import os
import json
import time
import asyncio
import threading
import webrtc
# pip install pytgcalls[pyrogram]==3.0.0.dev21
import pyrogram
from pytgcalls.mtproto.pyrogram_bridge import PyrogramBridge
remote_sdp = None
def parse_sdp(sdp):
lines = sdp.split('\r\n')
def lookup(prefix):
for line in lines:
if line.startswith(prefix):
return line[len(prefix) :]
info = {
'fingerprint': lookup('a=fingerprint:').split(' ')[1],
'hash': lookup('a=fingerprint:').split(' ')[0],
'setup': lookup('a=setup:'),
'pwd': lookup('a=ice-pwd:'),
'ufrag': lookup('a=ice-ufrag:'),
}
ssrc = lookup('a=ssrc:')
if ssrc:
info['source'] = int(ssrc.split(' ')[0])
return info
def get_params_from_parsed_sdp(info):
return {
'fingerprints': [{'fingerprint': info['fingerprint'], 'hash': info['hash'], 'setup': 'active'}],
'pwd': info['pwd'],
'ssrc': info['source'],
'ssrc-groups': [],
'ufrag': info['ufrag'],
}
def build_answer(sdp):
def add_candidates():
candidates_sdp = []
for cand in sdp['transport']['candidates']:
candidates_sdp.append(
f"a=candidate:{cand['foundation']} {cand['component']} {cand['protocol']} "
f"{cand['priority']} {cand['ip']} {cand['port']} typ {cand['type']} "
f"generation {cand['generation']}"
)
return '\n'.join(candidates_sdp)
return f"""v=0
o=- {time.time()} 2 IN IP4 0.0.0.0
s=-
t=0 0
a=group:BUNDLE 0
a=ice-lite
m=audio 1 RTP/SAVPF 111 126
c=IN IP4 0.0.0.0
a=mid:0
a=ice-ufrag:{sdp['transport']['ufrag']}
a=ice-pwd:{sdp['transport']['pwd']}
a=fingerprint:sha-256 {sdp['transport']['fingerprints'][0]['fingerprint']}
a=setup:passive
{add_candidates()}
a=rtpmap:111 opus/48000/2
a=rtpmap:126 telephone-event/8000
a=fmtp:111 minptime=10; useinbandfec=1; usedtx=1
a=rtcp:1 IN IP4 0.0.0.0
a=rtcp-mux
a=rtcp-fb:111 transport-cc
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=recvonly
"""
# a=sendrecv
async def group_call_participants_update_callback(_):
pass
async def group_call_update_callback(update):
global remote_sdp
data = update.call.params.data
remote_sdp = build_answer(json.loads(data))
def send_audio_data(audio_source):
def get_ms_time():
return round(time.time() * 1000)
last_read_ms = 0
length = int(480 * 16 / 8 * 2) # 2 channels with 16 bits per sample in 48khz
f = open('test.raw', 'rb')
while True:
start_time = get_ms_time()
if last_read_ms == 0 or start_time - last_read_ms >= 10:
data = f.read(length)
if not data: # eof
f.close()
break
event_data = webrtc.RTCOnDataEvent(data, length // 4) # 2 channels
event_data.channel_count = 2
audio_source.on_data(event_data)
last_read_ms = start_time
delta_time = get_ms_time() - start_time
if delta_time < 10:
time.sleep((10 - delta_time) / 1000)
async def main(client, input_peer):
pc = webrtc.RTCPeerConnection()
# stream = webrtc.get_user_media()
# for track in stream.get_tracks():
# track.enabled = True
# pc.add_track(track, stream)
audio_source = webrtc.RTCAudioSource()
track = audio_source.create_track()
pc.add_track(track)
local_sdp = await pc.create_offer()
await pc.set_local_description(local_sdp)
app = PyrogramBridge(client)
app.register_group_call_native_callback(group_call_participants_update_callback, group_call_update_callback)
await app.get_and_set_group_call(input_peer)
await app.resolve_and_set_join_as(None)
def pre_update_processing():
pass
parsed_sdp = parse_sdp(local_sdp.sdp)
payload = get_params_from_parsed_sdp(parsed_sdp)
await app.join_group_call(None, json.dumps(payload), False, False, pre_update_processing)
while not remote_sdp:
await asyncio.sleep(0.1)
# await asyncio.wait_for(REMOTE_ANSWER_EVENT.wait(), 30)
# TODO allow to pass RTCSessionDescriptionInit
await pc.set_remote_description(
webrtc.RTCSessionDescription(webrtc.RTCSessionDescriptionInit(webrtc.RTCSdpType.answer, remote_sdp))
)
thread = threading.Thread(target=send_audio_data, args=(audio_source,))
thread.daemon = True
thread.start()
# await asyncio.sleep(10)
await pyrogram.idle()
if __name__ == '__main__':
pyro_client = pyrogram.Client(
os.environ.get('SESSION_NAME'), api_hash=os.environ.get('API_HASH'), api_id=os.environ.get('API_ID')
)
pyro_client.start()
peer = os.environ.get('PEER')
asyncio.get_event_loop().run_until_complete(main(pyro_client, peer))
|
[] |
[] |
[
"API_ID",
"PEER",
"API_HASH",
"SESSION_NAME"
] |
[]
|
["API_ID", "PEER", "API_HASH", "SESSION_NAME"]
|
python
| 4 | 0 | |
go/buildskia/buildskia.go
|
// Utility functions for downloading, building, and compiling programs against Skia.
package buildskia
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"go.skia.org/infra/go/common"
"go.skia.org/infra/go/depot_tools/deps_parser"
"go.skia.org/infra/go/exec"
"go.skia.org/infra/go/git"
"go.skia.org/infra/go/git/gitinfo"
"go.skia.org/infra/go/gitiles"
"go.skia.org/infra/go/skerr"
"go.skia.org/infra/go/sklog"
"go.skia.org/infra/go/util"
"go.skia.org/infra/go/util/limitwriter"
"go.skia.org/infra/go/vcsinfo"
)
type ReleaseType string
// ReleaseType constants.
const (
RELEASE_BUILD ReleaseType = "Release"
DEBUG_BUILD ReleaseType = "Debug"
RELEASE_DEVELOPER_BUILD ReleaseType = "Release_Developer"
)
const (
CMAKE_OUTDIR = "cmakeout"
CMAKE_COMPILE_ARGS_FILE = "skia_compile_arguments.txt"
CMAKE_LINK_ARGS_FILE = "skia_link_arguments.txt"
)
// GetSkiaHead returns the most recent commit hash on Skia's main branch.
//
// If client is nil then a default timeout client is used.
func GetSkiaHead(client *http.Client) (string, error) {
head, err := gitiles.NewRepo(common.REPO_SKIA, client).Details(context.TODO(), git.MasterBranch)
if err != nil {
return "", skerr.Wrapf(err, "Could not get Skia's HEAD")
}
return head.Hash, nil
}
// GetSkiaHash returns Skia's LKGR commit hash as recorded in chromium's DEPS file.
//
// If client is nil then a default timeout client is used.
func GetSkiaHash(client *http.Client) (string, error) {
depsContents, err := gitiles.NewRepo(common.REPO_CHROMIUM, client).ReadFile(context.TODO(), deps_parser.DepsFileName)
if err != nil {
return "", skerr.Wrapf(err, "Failed to read Chromium DEPS")
}
dep, err := deps_parser.GetDep(string(depsContents), common.REPO_SKIA)
if err != nil {
return "", skerr.Wrapf(err, "Failed to get Skia's LKGR")
}
return dep.Version, nil
}
// DownloadSkia uses git to clone Skia from googlesource.com and check it out
// to the specified gitHash for the specified branch. Upon success, any
// dependencies needed to compile Skia have been installed (e.g. the latest
// version of gyp).
//
// branch - The empty string signifies the main branch.
// gitHash - The git hash to check out Skia at.
// path - The path to check Skia out into.
// depotToolsPath - The depot_tools directory.
// clean - If true clean out the directory before cloning Skia.
// installDeps - If true then run tools/install_dependencies.sh before
// sync. The calling user should be sudo capable.
//
// It returns an error on failure.
func DownloadSkia(ctx context.Context, branch, gitHash, path, depotToolsPath string, clean bool, installDeps bool) (*vcsinfo.LongCommit, error) {
sklog.Infof("Cloning Skia gitHash %s to %s, clean: %t", gitHash, path, clean)
if clean {
util.RemoveAll(filepath.Join(path))
}
repo, err := gitinfo.CloneOrUpdate(ctx, "https://skia.googlesource.com/skia", path, true)
if err != nil {
return nil, fmt.Errorf("Failed cloning Skia: %s", err)
}
if branch != "" {
if err := repo.Checkout(ctx, branch); err != nil {
return nil, fmt.Errorf("Failed to change to branch %s: %s", branch, err)
}
}
if err = repo.Reset(ctx, gitHash); err != nil {
return nil, fmt.Errorf("Problem setting Skia to gitHash %s: %s", gitHash, err)
}
env := []string{"PATH=" + depotToolsPath + ":" + os.Getenv("PATH")}
if installDeps {
depsCmd := &exec.Command{
Name: "sudo",
Args: []string{"tools/install_dependencies.sh"},
Dir: path,
InheritPath: false,
Env: env,
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, depsCmd); err != nil {
return nil, fmt.Errorf("Failed installing dependencies: %s", err)
}
}
syncCmd := &exec.Command{
Name: "bin/sync",
Dir: path,
InheritPath: false,
Env: env,
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, syncCmd); err != nil {
return nil, fmt.Errorf("Failed syncing and setting up gyp: %s", err)
}
if lc, err := repo.Details(ctx, gitHash, false); err != nil {
return nil, fmt.Errorf("Could not get git details for skia gitHash %s: %s", gitHash, err)
} else {
return lc, nil
}
}
// GNDownloadSkia uses depot_tools fetch to clone Skia from googlesource.com
// and check it out to the specified gitHash for the specified branch. Upon
// success, any dependencies needed to compile Skia have been installed.
//
// branch - The empty string signifies the main branch.
// gitHash - The git hash to check out Skia at.
// path - The path to check Skia out into.
// depotToolsPath - The depot_tools directory.
// clean - If true clean out the directory before cloning Skia.
// installDeps - If true then run tools/install_dependencies.sh before
// syncing. The calling user should be sudo capable.
//
// It returns an error on failure.
func GNDownloadSkia(ctx context.Context, branch, gitHash, path, depotToolsPath string, clean bool, installDeps bool) (*vcsinfo.LongCommit, error) {
sklog.Infof("Cloning Skia gitHash %s to %s, clean: %t", gitHash, path, clean)
if clean {
util.RemoveAll(filepath.Join(path))
}
if err := os.MkdirAll(path, 0755); err != nil {
return nil, fmt.Errorf("Failed to create dir for checkout: %s", err)
}
env := []string{"PATH=" + depotToolsPath + ":" + os.Getenv("PATH")}
fetchCmd := &exec.Command{
Name: filepath.Join(depotToolsPath, "fetch"),
Args: []string{"skia"},
Dir: path,
InheritPath: false,
Env: env,
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, fetchCmd); err != nil {
// Failing to fetch might be because we already have Skia checked out here.
sklog.Warningf("Failed to fetch skia: %s", err)
}
repoPath := filepath.Join(path, "skia")
repo, err := gitinfo.NewGitInfo(ctx, repoPath, false, true)
if err != nil {
return nil, fmt.Errorf("Failed working with Skia repo: %s", err)
}
if err = repo.Reset(ctx, gitHash); err != nil {
return nil, fmt.Errorf("Problem setting Skia to gitHash %s: %s", gitHash, err)
}
if installDeps {
depsCmd := &exec.Command{
Name: "sudo",
Args: []string{"tools/install_dependencies.sh"},
Dir: repoPath,
InheritPath: false,
Env: env,
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, depsCmd); err != nil {
return nil, fmt.Errorf("Failed installing dependencies: %s", err)
}
}
syncCmd := &exec.Command{
Name: filepath.Join(depotToolsPath, "gclient"),
Args: []string{"sync"},
Dir: path,
InheritPath: false,
Env: env,
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, syncCmd); err != nil {
return nil, fmt.Errorf("Failed syncing: %s", err)
}
fetchGn := &exec.Command{
Name: filepath.Join(repoPath, "bin", "fetch-gn"),
Args: []string{},
Dir: repoPath,
InheritPath: false,
Env: []string{"PATH=" + depotToolsPath + ":" + os.Getenv("PATH")},
LogStderr: true,
LogStdout: true,
}
if err := exec.Run(ctx, fetchGn); err != nil {
return nil, fmt.Errorf("Failed installing dependencies: %s", err)
}
if lc, err := repo.Details(ctx, gitHash, false); err != nil {
return nil, fmt.Errorf("Could not get git details for skia gitHash %s: %s", gitHash, err)
} else {
return lc, nil
}
}
// GNGen runs GN on Skia.
//
// path - The absolute path to the Skia checkout, should be the same
// path passed to DownloadSkiaGN.
// depotTools - The path to depot_tools.
// outSubDir - The name of the sub-directory under 'out' to build in.
// args - A slice of strings to pass to gn --args. See the skia
// BUILD.gn and https://skia.org/user/quick/gn.
//
// The results of the build are stored in path/skia/out/<outSubDir>.
func GNGen(ctx context.Context, path, depotTools, outSubDir string, args []string) error {
genCmd := &exec.Command{
Name: filepath.Join(depotTools, "gn"),
Args: []string{"gen", filepath.Join("out", outSubDir), fmt.Sprintf(`--args=%s`, strings.Join(args, " "))},
Dir: filepath.Join(path, "skia"),
InheritPath: false,
Env: []string{
"PATH=" + depotTools + ":" + os.Getenv("PATH"),
},
LogStderr: true,
LogStdout: true,
}
sklog.Infof("About to run: %#v", *genCmd)
if err := exec.Run(ctx, genCmd); err != nil {
return fmt.Errorf("Failed gn gen: %s", err)
}
return nil
}
// GNNinjaBuild builds the given target using ninja.
//
// path - The absolute path to the Skia checkout as passed into DownloadSkiaGN.
// depotToolsPath - The depot_tools directory.
// outSubDir - The name of the sub-directory under 'out' to build in.
// target - The specific target to build. Pass in the empty string to build all targets.
// verbose - If the build's std out should be logged (usally quite long)
//
// Returns the build logs and any errors on failure.
func GNNinjaBuild(ctx context.Context, path, depotToolsPath, outSubDir, target string, verbose bool) (string, error) {
args := []string{"-C", filepath.Join("out", outSubDir)}
if target != "" {
args = append(args, target)
}
buf := bytes.Buffer{}
output := limitwriter.New(&buf, 64*1024)
buildCmd := &exec.Command{
Name: filepath.Join(depotToolsPath, "ninja"),
Args: args,
Dir: filepath.Join(path, "skia"),
InheritPath: false,
Env: []string{"PATH=" + depotToolsPath + ":" + os.Getenv("PATH")},
CombinedOutput: output,
LogStderr: true,
LogStdout: verbose,
}
sklog.Infof("About to run: %#v", *buildCmd)
if err := exec.Run(ctx, buildCmd); err != nil {
return buf.String(), fmt.Errorf("Failed compile: %s", err)
}
return buf.String(), nil
}
// NinjaBuild builds the given target using ninja.
//
// skiaPath - The absolute path to the Skia checkout.
// depotToolsPath - The depot_tools directory.
// extraEnv - Any additional environment variables that need to be set. Can be nil.
// build - The type of build to perform.
// target - The build target, e.g. "SampleApp" or "most".
// verbose - If the build's std out should be logged (usally quite long)
//
// Returns an error on failure.
func NinjaBuild(ctx context.Context, skiaPath, depotToolsPath string, extraEnv []string, build ReleaseType, target string, numCores int, verbose bool) error {
buildCmd := &exec.Command{
Name: filepath.Join(depotToolsPath, "ninja"),
Args: []string{"-C", "out/" + string(build), "-j", fmt.Sprintf("%d", numCores), target},
Dir: skiaPath,
InheritPath: false,
Env: append(extraEnv,
"PATH="+depotToolsPath+":"+os.Getenv("PATH"),
),
LogStderr: true,
LogStdout: verbose,
}
sklog.Infof("About to run: %#v", *buildCmd)
if err := exec.Run(ctx, buildCmd); err != nil {
return fmt.Errorf("Failed ninja build: %s", err)
}
return nil
}
// CMakeBuild runs /skia/cmake/cmake_build to build Skia.
//
// path - The absolute path to the Skia checkout.
// depotTools - The path to depot_tools.
// build - Is the type of build to perform.
//
// The results of the build are stored in path/CMAKE_OUTDIR.
func CMakeBuild(ctx context.Context, path, depotTools string, build ReleaseType) error {
if build == "" {
build = "Release"
}
buildCmd := &exec.Command{
Name: filepath.Join(path, "cmake", "cmake_build"),
Dir: filepath.Join(path, "cmake"),
InheritPath: false,
Env: []string{
"SKIA_OUT=" + filepath.Join(path, CMAKE_OUTDIR), // Note that cmake_build will put the results in a sub-directory
// that is the build type.
"BUILDTYPE=" + string(build),
"PATH=" + filepath.Join(path, "cmake") + ":" + depotTools + ":" + os.Getenv("PATH"),
},
LogStderr: true,
LogStdout: true,
}
sklog.Infof("About to run: %#v", *buildCmd)
if err := exec.Run(ctx, buildCmd); err != nil {
return fmt.Errorf("Failed cmake build: %s", err)
}
return nil
}
// CMakeCompileAndLink will compile the given files into an executable.
//
// path - the absolute path to the Skia checkout.
// out - A filename, either absolute, or relative to path, to write the exe.
// filenames - Absolute paths to the files to compile.
// extraIncludeDirs - Entra directories to search for includes.
// extraLinkFlags - Entra linker flags.
//
// Returns the stdout+stderr of the compiler and a non-nil error if the compile failed.
//
// Should run something like:
//
// $ c++ @skia_compile_arguments.txt fiddle_main.cpp \
// draw.cpp @skia_link_arguments.txt -lOSMesa \
// -o myexample
//
func CMakeCompileAndLink(ctx context.Context, path, out string, filenames []string, extraIncludeDirs []string, extraLinkFlags []string, build ReleaseType) (string, error) {
if !filepath.IsAbs(out) {
out = filepath.Join(path, out)
}
args := []string{
fmt.Sprintf("@%s", filepath.Join(path, CMAKE_OUTDIR, string(build), CMAKE_COMPILE_ARGS_FILE)),
}
if len(extraIncludeDirs) > 0 {
args = append(args, "-I"+strings.Join(extraIncludeDirs, ","))
}
for _, fn := range filenames {
args = append(args, fn)
}
moreArgs := []string{
fmt.Sprintf("@%s", filepath.Join(path, CMAKE_OUTDIR, string(build), CMAKE_LINK_ARGS_FILE)),
"-o",
out,
}
for _, s := range moreArgs {
args = append(args, s)
}
if len(extraLinkFlags) > 0 {
for _, fl := range extraLinkFlags {
args = append(args, fl)
}
}
buf := bytes.Buffer{}
output := limitwriter.New(&buf, 64*1024)
compileCmd := &exec.Command{
Name: "c++",
Args: args,
Dir: path,
InheritPath: true,
CombinedOutput: output,
Timeout: 10 * time.Second,
LogStderr: true,
LogStdout: true,
}
sklog.Infof("About to run: %#v", *compileCmd)
if err := exec.Run(ctx, compileCmd); err != nil {
return buf.String(), fmt.Errorf("Failed compile: %s", err)
}
return buf.String(), nil
}
// CMakeCompile will compile the given files into an executable.
//
// path - the absolute path to the Skia checkout.
// out - A filename, either absolute, or relative to path, to write the .o file.
// filenames - Absolute paths to the files to compile.
//
// Should run something like:
//
// $ c++ @skia_compile_arguments.txt fiddle_main.cpp \
// -o fiddle_main.o
//
func CMakeCompile(ctx context.Context, path, out string, filenames []string, extraIncludeDirs []string, build ReleaseType) error {
if !filepath.IsAbs(out) {
out = filepath.Join(path, out)
}
args := []string{
"-c",
fmt.Sprintf("@%s", filepath.Join(path, CMAKE_OUTDIR, string(build), CMAKE_COMPILE_ARGS_FILE)),
}
if len(extraIncludeDirs) > 0 {
args = append(args, "-I"+strings.Join(extraIncludeDirs, ","))
}
for _, fn := range filenames {
args = append(args, fn)
}
moreArgs := []string{
"-o",
out,
}
for _, s := range moreArgs {
args = append(args, s)
}
compileCmd := &exec.Command{
Name: "c++",
Args: args,
Dir: path,
InheritPath: true,
LogStderr: true,
LogStdout: true,
}
sklog.Infof("About to run: %#v", *compileCmd)
if err := exec.Run(ctx, compileCmd); err != nil {
return fmt.Errorf("Failed compile: %s", err)
}
return nil
}
|
[
"\"PATH\"",
"\"PATH\"",
"\"PATH\"",
"\"PATH\"",
"\"PATH\"",
"\"PATH\"",
"\"PATH\""
] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
go
| 1 | 0 | |
setup_sympycore.py
|
#!/usr/bin/env python
CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science/Research
License :: OSI Approved
Programming Language :: Python
Topic :: Scientific/Engineering
Topic :: Software Development
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Operating System :: Unix
Operating System :: MacOS
"""
import os
if os.path.exists('MANIFEST'): os.remove('MANIFEST')
from distutils.core import Extension, Command
from distutils.command.build_py import build_py as _build_py
expr_ext = Extension('sympycore.expr_ext',
sources = [os.path.join('src','expr_ext.c')],
)
combinatorics_ext = Extension('sympycore.arithmetic.combinatorics',
sources = [os.path.join('sympycore','arithmetic','combinatorics.c')],
)
extensions = [expr_ext,
#combinatorics_ext
]
packages = ['sympycore',
'sympycore.algebras',
'sympycore.arithmetic',
'sympycore.arithmetic.mpmath',
'sympycore.arithmetic.mpmath.calculus',
'sympycore.arithmetic.mpmath.functions',
'sympycore.arithmetic.mpmath.libmp',
'sympycore.arithmetic.mpmath.matrices',
'sympycore.basealgebra',
'sympycore.calculus',
'sympycore.calculus.functions',
'sympycore.functions',
'sympycore.heads',
'sympycore.logic',
'sympycore.matrices',
'sympycore.polynomials',
'sympycore.physics',
'sympycore.physics.sysbio',
'sympycore.ring',
'sympycore.sets',
]
packages += [p+'.tests' for p in packages \
if os.path.exists(os.path.join(p.replace('.', os.sep), 'tests'))]
class tester(Command):
description = "run sympycore tests"
user_options = [('nose-args=', 'n', 'arguments to nose command'),
('with-coverage', 'c', 'use nose --with-coverage flag'),
('cover-package=', None, 'use nose --cover-package flag'),
('detailed-errors', 'd', 'use nose --detailed-errors flag'),
('nocapture', 's', 'use nose --nocapture flag'),
('nose-verbose', 'v', 'use nose --verbose flag'),
('match=', 'm', 'use nose --match flag'),
('profile', 'p', 'use nose --profile flag'),
('with-doctest', None, 'use nose --with-doctest flag'),
('stop', 'x', 'use nose --stop flag')
]
def initialize_options(self):
self.nose_args = None
self.with_coverage = None
self.cover_package = None
self.detailed_errors = None
self.nocapture = None
self.nose_verbose = None
self.match = None
self.profile = None
self.with_doctest = None
self.stop = None
return
def finalize_options (self):
if self.nose_args is None:
self.nose_args = ''
if self.with_coverage:
self.nose_args += ' --with-coverage'
if self.cover_package:
if not self.with_coverage:
self.nose_args += ' --with-coverage'
self.nose_args += ' --cover-package=%s' % self.cover_package
elif self.with_coverage:
self.nose_args += ' --cover-package=sympycore'
if self.detailed_errors:
self.nose_args += ' --detailed-errors'
if self.nocapture:
self.nose_args += ' --nocapture'
if self.nose_verbose:
self.nose_args += ' --verbose'
if self.match:
self.nose_args += ' --match=%r' % (self.match)
if self.profile:
self.nose_args += ' --with-profile'
if self.with_doctest:
self.nose_args += ' --with-doctest'
if self.stop:
self.nose_args += ' --stop'
return
def run(self):
import sympycore
sympycore.test(nose_args=self.nose_args)
class build_py(_build_py):
def find_data_files (self, package, src_dir):
files = _build_py.find_data_files(self, package, src_dir)
if package=='sympycore':
revision = self._get_svn_revision(src_dir)
if revision is not None:
target = os.path.join(src_dir, '__svn_version__.py')
print 'Creating ', target
f = open(target,'w')
f.write('version = %r\n' % (str(revision)))
f.close()
import atexit
def rm_file(f=target):
try: os.remove(f); print 'Removed ',f
except OSError: pass
try: os.remove(f+'c'); print 'Removed ',f+'c'
except OSError: pass
atexit.register(rm_file)
files.append(target)
if package=='sympycore.arithmetic.mpmath':
f = os.path.join(src_dir, 'REVISION')
if os.path.isfile(f):
files.append(f)
return files
def _get_svn_revision(self, path):
"""Return path's SVN revision number.
"""
import os, sys, re
revision = None
m = None
try:
sin, sout = os.popen4('svnversion')
m = re.match(r'(?P<revision>\d+)', sout.read())
except:
pass
if m:
revision = int(m.group('revision'))
return revision
if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK',None):
entries = os.path.join(path,'_svn','entries')
else:
entries = os.path.join(path,'.svn','entries')
if os.path.isfile(entries):
f = open(entries)
fstr = f.read()
f.close()
if fstr[:5] == '<?xml': # pre 1.4
m = re.search(r'revision="(?P<revision>\d+)"',fstr)
if m:
revision = int(m.group('revision'))
else: # non-xml entries file --- check to be sure that
m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr)
if m:
revision = int(m.group('revision'))
return revision
from distutils.core import setup
setup(name='sympycore',
version='0.2-svn',
author = 'Pearu Peterson, Fredrik Johansson',
author_email = '[email protected]',
license = 'http://sympycore.googlecode.com/svn/trunk/LICENSE',
url = 'http://sympycore.googlecode.com',
download_url = 'http://code.google.com/p/sympycore/downloads/',
classifiers=filter(None, CLASSIFIERS.split('\n')),
description = 'SympyCore: an efficient pure Python Computer Algebra System',
long_description = '''\
SympyCore project provides a pure Python package sympycore for
representing symbolic expressions using efficient data structures as
well as methods to manipulate them. Sympycore uses a clear algebra
oriented design that can be easily extended.
''',
platforms = ["All"],
packages = packages,
ext_modules = extensions,
package_dir = {'sympycore': 'sympycore'},
cmdclass=dict(test=tester, build_py=build_py)
)
|
[] |
[] |
[
"SVN_ASP_DOT_NET_HACK"
] |
[]
|
["SVN_ASP_DOT_NET_HACK"]
|
python
| 1 | 0 | |
object_detection/pytorch/tools/train_mlperf.py
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""
Basic training script for PyTorch
"""
# Set up custom environment before nearly anything else is imported
# NOTE: this should be the first import (no not reorder)
from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip
import argparse
import os
import functools
import logging
import random
import datetime
import time
import torch
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.data import make_data_loader
from maskrcnn_benchmark.solver import make_lr_scheduler
from maskrcnn_benchmark.solver import make_optimizer
from maskrcnn_benchmark.engine.inference import inference
from maskrcnn_benchmark.engine.trainer import do_train
from maskrcnn_benchmark.engine.tester import test
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.utils.collect_env import collect_env_info
from maskrcnn_benchmark.utils.comm import synchronize, get_rank, is_main_process
from maskrcnn_benchmark.utils.imports import import_file
from maskrcnn_benchmark.utils.logger import setup_logger
from maskrcnn_benchmark.utils.miscellaneous import mkdir
from maskrcnn_benchmark.utils.mlperf_logger import print_mlperf, generate_seeds, broadcast_seeds
from mlperf_compliance import mlperf_log
def test_and_exchange_map(tester, model, distributed):
results = tester(model=model, distributed=distributed)
# main process only
if is_main_process():
# Note: one indirection due to possibility of multiple test datasets, we only care about the first
# tester returns (parsed results, raw results). In our case, don't care about the latter
map_results, raw_results = results[0]
bbox_map = map_results.results["bbox"]['AP']
segm_map = map_results.results["segm"]['AP']
else:
bbox_map = 0.
segm_map = 0.
if distributed:
map_tensor = torch.tensor([bbox_map, segm_map], dtype=torch.float32, device=torch.device("cuda"))
torch.distributed.broadcast(map_tensor, 0)
bbox_map = map_tensor[0].item()
segm_map = map_tensor[1].item()
return bbox_map, segm_map
def mlperf_test_early_exit(iteration, iters_per_epoch, tester, model, distributed, min_bbox_map, min_segm_map):
# Note: let iters / epoch == 10k, at iter 9999 we've finished epoch 0 and need to test
if iteration > 0 and (iteration + 1)% iters_per_epoch == 0:
epoch = iteration // iters_per_epoch
print_mlperf(key=mlperf_log.EVAL_START, value=epoch)
bbox_map, segm_map = test_and_exchange_map(tester, model, distributed)
# necessary for correctness
model.train()
print_mlperf(key=mlperf_log.EVAL_TARGET, value={"BBOX": min_bbox_map,
"SEGM": min_segm_map})
logger = logging.getLogger('maskrcnn_benchmark.trainer')
logger.info('bbox mAP: {}, segm mAP: {}'.format(bbox_map, segm_map))
print_mlperf(key=mlperf_log.EVAL_ACCURACY, value={"epoch" : epoch, "value":{"BBOX" : bbox_map, "SEGM" : segm_map}})
print_mlperf(key=mlperf_log.EVAL_STOP)
# terminating condition
if bbox_map >= min_bbox_map and segm_map >= min_segm_map:
logger.info("Target mAP reached, exiting...")
print_mlperf(key=mlperf_log.RUN_STOP, value={"success":True})
return True
# At this point will start the next epoch, so note this in the log
# print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=epoch+1)
return False
def mlperf_log_epoch_start(iteration, iters_per_epoch):
# First iteration:
# Note we've started training & tag first epoch start
if iteration == 0:
print_mlperf(key=mlperf_log.TRAIN_LOOP)
print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=0)
return
if iteration % iters_per_epoch == 0:
epoch = iteration // iters_per_epoch
print_mlperf(key=mlperf_log.TRAIN_EPOCH, value=epoch)
from maskrcnn_benchmark.layers.batch_norm import FrozenBatchNorm2d
def cast_frozen_bn_to_half(module):
if isinstance(module, FrozenBatchNorm2d):
module.half()
for child in module.children():
cast_frozen_bn_to_half(child)
return module
def train(cfg, local_rank, distributed):
# Model logging
print_mlperf(key=mlperf_log.INPUT_BATCH_SIZE, value=cfg.SOLVER.IMS_PER_BATCH)
print_mlperf(key=mlperf_log.BATCH_SIZE_TEST, value=cfg.TEST.IMS_PER_BATCH)
print_mlperf(key=mlperf_log.INPUT_MEAN_SUBTRACTION, value = cfg.INPUT.PIXEL_MEAN)
print_mlperf(key=mlperf_log.INPUT_NORMALIZATION_STD, value=cfg.INPUT.PIXEL_STD)
print_mlperf(key=mlperf_log.INPUT_RESIZE)
print_mlperf(key=mlperf_log.INPUT_RESIZE_ASPECT_PRESERVING)
print_mlperf(key=mlperf_log.MIN_IMAGE_SIZE, value=cfg.INPUT.MIN_SIZE_TRAIN)
print_mlperf(key=mlperf_log.MAX_IMAGE_SIZE, value=cfg.INPUT.MAX_SIZE_TRAIN)
print_mlperf(key=mlperf_log.INPUT_RANDOM_FLIP)
print_mlperf(key=mlperf_log.RANDOM_FLIP_PROBABILITY, value=0.5)
print_mlperf(key=mlperf_log.FG_IOU_THRESHOLD, value=cfg.MODEL.RPN.FG_IOU_THRESHOLD)
print_mlperf(key=mlperf_log.BG_IOU_THRESHOLD, value=cfg.MODEL.RPN.BG_IOU_THRESHOLD)
print_mlperf(key=mlperf_log.RPN_PRE_NMS_TOP_N_TRAIN, value=cfg.MODEL.RPN.PRE_NMS_TOP_N_TRAIN)
print_mlperf(key=mlperf_log.RPN_PRE_NMS_TOP_N_TEST, value=cfg.MODEL.RPN.PRE_NMS_TOP_N_TEST)
print_mlperf(key=mlperf_log.RPN_POST_NMS_TOP_N_TRAIN, value=cfg.MODEL.RPN.FPN_POST_NMS_TOP_N_TRAIN)
print_mlperf(key=mlperf_log.RPN_POST_NMS_TOP_N_TEST, value=cfg.MODEL.RPN.FPN_POST_NMS_TOP_N_TEST)
print_mlperf(key=mlperf_log.ASPECT_RATIOS, value=cfg.MODEL.RPN.ASPECT_RATIOS)
print_mlperf(key=mlperf_log.BACKBONE, value=cfg.MODEL.BACKBONE.CONV_BODY)
print_mlperf(key=mlperf_log.NMS_THRESHOLD, value=cfg.MODEL.RPN.NMS_THRESH)
model = build_detection_model(cfg)
device = torch.device(cfg.MODEL.DEVICE)
model.to(device)
optimizer = make_optimizer(cfg, model)
# Optimizer logging
print_mlperf(key=mlperf_log.OPT_NAME, value=mlperf_log.SGD_WITH_MOMENTUM)
print_mlperf(key=mlperf_log.OPT_LR, value=cfg.SOLVER.BASE_LR)
print_mlperf(key=mlperf_log.OPT_MOMENTUM, value=cfg.SOLVER.MOMENTUM)
print_mlperf(key=mlperf_log.OPT_WEIGHT_DECAY, value=cfg.SOLVER.WEIGHT_DECAY)
scheduler = make_lr_scheduler(cfg, optimizer)
if distributed:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank], output_device=local_rank,
# this should be removed if we update BatchNorm stats
broadcast_buffers=False,
)
arguments = {}
arguments["iteration"] = 0
output_dir = cfg.OUTPUT_DIR
save_to_disk = get_rank() == 0
checkpointer = DetectronCheckpointer(
cfg, model, optimizer, scheduler, output_dir, save_to_disk
)
arguments["save_checkpoints"] = cfg.SAVE_CHECKPOINTS
extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)
arguments.update(extra_checkpoint_data)
data_loader, iters_per_epoch = make_data_loader(
cfg,
is_train=True,
is_distributed=distributed,
start_iter=arguments["iteration"],
)
checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD
# set the callback function to evaluate and potentially
# early exit each epoch
if cfg.PER_EPOCH_EVAL:
per_iter_callback_fn = functools.partial(
mlperf_test_early_exit,
iters_per_epoch=iters_per_epoch,
tester=functools.partial(test, cfg=cfg),
model=model,
distributed=distributed,
min_bbox_map=cfg.MLPERF.MIN_BBOX_MAP,
min_segm_map=cfg.MLPERF.MIN_SEGM_MAP)
else:
per_iter_callback_fn = None
start_train_time = time.time()
do_train(
model,
data_loader,
optimizer,
scheduler,
checkpointer,
device,
checkpoint_period,
arguments,
per_iter_start_callback_fn=functools.partial(mlperf_log_epoch_start, iters_per_epoch=iters_per_epoch),
per_iter_end_callback_fn=per_iter_callback_fn,
)
end_train_time = time.time()
total_training_time = end_train_time - start_train_time
print(
"&&&& MLPERF METRIC THROUGHPUT per GPU={:.4f} iterations / s".format((arguments["iteration"] * 1.0) / total_training_time)
)
return model
def main():
mlperf_log.ROOT_DIR_MASKRCNN = os.path.dirname(os.path.abspath(__file__))
parser = argparse.ArgumentParser(description="PyTorch Object Detection Training")
parser.add_argument(
"--config-file",
default="",
metavar="FILE",
help="path to config file",
type=str,
)
parser.add_argument("--local_rank", type=int, default=0)
parser.add_argument(
"opts",
help="Modify config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
args = parser.parse_args()
num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
args.distributed = num_gpus > 1
if is_main_process:
# Setting logging file parameters for compliance logging
os.environ["COMPLIANCE_FILE"] = '/MASKRCNN_complVv0.5.0_' + str(datetime.datetime.now())
mlperf_log.LOG_FILE = os.getenv("COMPLIANCE_FILE")
mlperf_log._FILE_HANDLER = logging.FileHandler(mlperf_log.LOG_FILE)
mlperf_log._FILE_HANDLER.setLevel(logging.DEBUG)
mlperf_log.LOGGER.addHandler(mlperf_log._FILE_HANDLER)
if args.distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://"
)
synchronize()
print_mlperf(key=mlperf_log.RUN_START)
# setting seeds - needs to be timed, so after RUN_START
if is_main_process():
master_seed = random.SystemRandom().randint(0, 2 ** 32 - 1)
seed_tensor = torch.tensor(master_seed, dtype=torch.float32, device=torch.device("cuda"))
else:
seed_tensor = torch.tensor(0, dtype=torch.float32, device=torch.device("cuda"))
torch.distributed.broadcast(seed_tensor, 0)
master_seed = int(seed_tensor.item())
else:
print_mlperf(key=mlperf_log.RUN_START)
# random master seed, random.SystemRandom() uses /dev/urandom on Unix
master_seed = random.SystemRandom().randint(0, 2 ** 32 - 1)
# actually use the random seed
args.seed = master_seed
# random number generator with seed set to master_seed
random_number_generator = random.Random(master_seed)
print_mlperf(key=mlperf_log.RUN_SET_RANDOM_SEED, value=master_seed)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
output_dir = cfg.OUTPUT_DIR
if output_dir:
mkdir(output_dir)
logger = setup_logger("maskrcnn_benchmark", output_dir, get_rank())
logger.info("Using {} GPUs".format(num_gpus))
logger.info(args)
# generate worker seeds, one seed for every distributed worker
worker_seeds = generate_seeds(random_number_generator, torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1)
# todo sharath what if CPU
# broadcast seeds from rank=0 to other workers
worker_seeds = broadcast_seeds(worker_seeds, device='cuda')
# Setting worker seeds
logger.info("Worker {}: Setting seed {}".format(args.local_rank, worker_seeds[args.local_rank]))
torch.manual_seed(worker_seeds[args.local_rank])
logger.info("Collecting env info (might take some time)")
logger.info("\n" + collect_env_info())
logger.info("Loaded configuration file {}".format(args.config_file))
with open(args.config_file, "r") as cf:
config_str = "\n" + cf.read()
logger.info(config_str)
logger.info("Running with config:\n{}".format(cfg))
model = train(cfg, args.local_rank, args.distributed)
print_mlperf(key=mlperf_log.RUN_FINAL)
if __name__ == "__main__":
start = time.time()
main()
print("&&&& MLPERF METRIC TIME=", time.time() - start)
|
[] |
[] |
[
"COMPLIANCE_FILE",
"WORLD_SIZE"
] |
[]
|
["COMPLIANCE_FILE", "WORLD_SIZE"]
|
python
| 2 | 0 | |
Train/run_Train_SiamFC.py
|
import __init_paths
import os
import numpy as np
from tqdm import tqdm
import torch
from torch.autograd import Variable
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from lib.VIDDataset import VIDDataset
from lib.DataAugmentation import RandomStretch, CenterCrop, RandomCrop, ToTensor
from lib.Utils import create_label
from lib.eval_utils import centerThrErr
from experiments.siamese_fc.Config import Config
from experiments.siamese_fc.network import SiamNet
# fix random seed
np.random.seed(1357)
torch.manual_seed(1234)
def train(data_dir, train_imdb, val_imdb,
model_save_path="./model/",
config=None):
assert config is not None
use_gpu = config.use_gpu
# set gpu ID
if use_gpu:
os.environ['CUDA_VISIBLE_DEVICES'] = str(config.gpu_id)
# do data augmentation in PyTorch;
# you can also do complex data augmentation as in the original paper
center_crop_size = config.instance_size - config.stride
random_crop_size = config.instance_size - 2 * config.stride
train_z_transforms = transforms.Compose([
RandomStretch(),
CenterCrop((config.examplar_size, config.examplar_size)),
ToTensor()
])
train_x_transforms = transforms.Compose([
RandomStretch(),
CenterCrop((center_crop_size, center_crop_size)),
RandomCrop((random_crop_size, random_crop_size)),
ToTensor()
])
valid_z_transforms = transforms.Compose([
CenterCrop((config.examplar_size, config.examplar_size)),
ToTensor(),
])
valid_x_transforms = transforms.Compose([
ToTensor()
])
# load data (see details in VIDDataset.py)
train_dataset = VIDDataset(train_imdb, data_dir, config,
train_z_transforms, train_x_transforms)
val_dataset = VIDDataset(val_imdb, data_dir, config, valid_z_transforms,
valid_x_transforms, "Validation")
# create dataloader
train_loader = DataLoader(train_dataset, batch_size=config.batch_size,
shuffle=True,
num_workers=config.train_num_workers,
drop_last=True)
val_loader = DataLoader(val_dataset, batch_size=config.batch_size,
shuffle=True,
num_workers=config.val_num_workers,
drop_last=True)
# create SiamFC network architecture (see details in SiamNet.py)
net = SiamNet()
# move network to GPU if using GPU
if use_gpu:
net.cuda()
# define training strategy;
# ========================================
# customize parameters attributes
# 1. adjust layer weight learnable
# 2. bias in feat_extraction exempt from weight_decay
params = []
# feature extract
for key, value in dict(net.feat_extraction.named_parameters()).items():
if 'conv' in key:
if 'bias' in key:
params += [{'params': [value],
'weight_decay': 0}]
else: # weight
params += [{'params': [value],
'weight_decay': config.weight_decay}]
if 'bn' in key:
params += [{'params': [value],
'weight_decay': 0}]
# adjust layer
params += [
{'params': [net.adjust.bias]},
# {'params': [net.adjust.weight], 'lr': not config.fix_adjust_layer},
]
if config.fix_adjust_layer:
params += [
{'params': [net.adjust.weight], 'lr': 0},
]
else:
params += [
{'params': [net.adjust.weight]},
]
# ========================================
optimizer = torch.optim.SGD(params,
config.lr,
config.momentum,
config.weight_decay)
# adjusting learning in each epoch
if not config.resume:
train_lrs = np.logspace(-2, -5, config.num_epoch)
scheduler = LambdaLR(optimizer, lambda epoch: train_lrs[epoch])
else:
train_lrs = np.logspace(-2, -5, config.num_epoch)
train_lrs = train_lrs[config.start_epoch:]
net.load_state_dict(torch.load(os.path.join(model_save_path,
'SiamFC_' +
str(config.start_epoch) +
'_model.pth')))
optimizer.load_state_dict(torch.load(os.path.join(model_save_path,
'optimizer.pth')))
scheduler = LambdaLR(optimizer, lambda epoch: train_lrs[epoch])
print('resume training from epoch {} checkpoint'.format(config.start_epoch))
# used to control generating label for training;
# once generated, they are fixed since the labels for each
# pair of images (examplar z and search region x) are the same
train_response_flag = False
valid_response_flag = False
# -------------------- training & validation process --------------------
for i in range(config.start_epoch, config.num_epoch):
# adjusting learning rate
scheduler.step()
# -------------------------- training --------------------------
# indicating training (very important for batch normalization)
net.train()
# used to collect loss
train_loss = []
# used as eval metric
err_disp = 0
sample_num = 0
for j, data in enumerate(train_loader):
# fetch data,
# i.e., B x C x W x H (batchsize x channel x wdith x heigh)
exemplar_imgs, instance_imgs = data
# forward pass
if use_gpu:
exemplar_imgs = exemplar_imgs.cuda()
instance_imgs = instance_imgs.cuda()
output = net.forward(Variable(exemplar_imgs),
Variable(instance_imgs))
# create label for training (only do it one time)
if not train_response_flag:
# change control flag
train_response_flag = True
# get shape of output (i.e., response map)
response_size = output.shape[2:4]
# generate label and weight
train_eltwise_label, train_instance_weight = \
create_label(response_size, config, use_gpu)
# clear the gradient
optimizer.zero_grad()
# loss
if config.loss == "logistic":
loss = net.weight_loss(output,
Variable(train_eltwise_label),
Variable(train_instance_weight))
elif config.loss == 'customize':
loss = net.customize_loss(output,
Variable(train_eltwise_label),
Variable(train_instance_weight))
# backward
loss.backward()
# update parameter
optimizer.step()
# collect training loss
train_loss.append(loss.data)
# collect additional data for metric
err_disp = centerThrErr(output.data.cpu().numpy(),
train_eltwise_label.cpu().numpy(),
err_disp, sample_num)
sample_num += config.batch_size
# stdout
if (j + 1) % config.log_freq == 0:
print ("Epoch %d, Iter %06d, loss: %f, error disp: %f"
% (i+1, (j+1), np.mean(train_loss), err_disp))
# ------------------------- saving model ---------------------------
if not os.path.exists(model_save_path):
os.makedirs(model_save_path)
torch.save(net.state_dict(),
os.path.join(model_save_path,
"SiamFC_" + str(i + 1) + "_model.pth"))
torch.save(optimizer.state_dict(),
os.path.join(model_save_path,
'optimizer.pth'))
# --------------------------- validation ---------------------------
# indicate validation
net.eval()
# used to collect validation loss
val_loss = []
for j, data in enumerate(tqdm(val_loader)):
exemplar_imgs, instance_imgs = data
# forward pass
if use_gpu:
exemplar_imgs = exemplar_imgs.cuda()
instance_imgs = instance_imgs.cuda()
output = net.forward(Variable(exemplar_imgs),
Variable(instance_imgs))
# create label for validation (only do it one time)
if not valid_response_flag:
valid_response_flag = True
response_size = output.shape[2:4]
valid_eltwise_label, valid_instance_weight = \
create_label(response_size, config, use_gpu)
# loss
if config.loss == "logistic":
loss = net.weight_loss(output,
Variable(valid_eltwise_label),
Variable(valid_instance_weight))
elif config.loss == 'customize':
loss = net.customize_loss(output,
Variable(valid_eltwise_label),
Variable(valid_instance_weight))
# collect validation loss
val_loss.append(loss.data)
print ("Epoch %d training loss: %f, validation loss: %f"
% (i+1, np.mean(train_loss), np.mean(val_loss)))
if __name__ == "__main__":
# initialize training configuration
config = Config()
data_dir = config.data_dir
train_imdb = config.train_imdb
val_imdb = config.val_imdb
model_save_path = os.path.join(config.save_base_path, config.save_sub_path)
# training SiamFC network, using GPU by default
train(data_dir, train_imdb, val_imdb,
model_save_path=model_save_path,
config=config)
|
[] |
[] |
[
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_VISIBLE_DEVICES"]
|
python
| 1 | 0 | |
go/exercise/ssh/ssh-client.go
|
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
type SSHCommand struct {
Path string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
type SSHClient struct {
Config *ssh.ClientConfig
Host string
Port int
}
func (client *SSHClient) RunCommand(cmd *SSHCommand) error {
var (
session *ssh.Session
err error
)
if session, err = client.newSession(); err != nil {
return err
}
defer session.Close()
if err = client.prepareCommand(session, cmd); err != nil {
return err
}
err = session.Run(cmd.Path)
return err
}
func (client *SSHClient) prepareCommand(session *ssh.Session, cmd *SSHCommand) error {
for _, env := range cmd.Env {
variable := strings.Split(env, "=")
if len(variable) != 2 {
continue
}
if err := session.Setenv(variable[0], variable[1]); err != nil {
fmt.Println(variable[0], variable[1])
return err
}
}
if cmd.Stdin != nil {
stdin, err := session.StdinPipe()
if err != nil {
return fmt.Errorf("Unable to setup stdin for session: %v", err)
}
go io.Copy(stdin, cmd.Stdin)
}
if cmd.Stdout != nil {
stdout, err := session.StdoutPipe()
if err != nil {
return fmt.Errorf("Unable to setup stdout for session: %v", err)
}
go io.Copy(cmd.Stdout, stdout)
}
if cmd.Stderr != nil {
stderr, err := session.StderrPipe()
if err != nil {
return fmt.Errorf("Unable to setup stderr for session: %v", err)
}
go io.Copy(cmd.Stderr, stderr)
}
return nil
}
func (client *SSHClient) newSession() (*ssh.Session, error) {
connection, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", client.Host, client.Port), client.Config)
if err != nil {
return nil, fmt.Errorf("Failed to dial: %s", err)
}
session, err := connection.NewSession()
if err != nil {
return nil, fmt.Errorf("Failed to create session: %s", err)
}
modes := ssh.TerminalModes{
// ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
session.Close()
return nil, fmt.Errorf("request for pseudo terminal failed: %s", err)
}
return session, nil
}
func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil
}
return ssh.PublicKeys(key)
}
func SSHAgent() ssh.AuthMethod {
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
}
return nil
}
func main() {
// ssh.Password("your_password")
sshConfig := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
SSHAgent(),
},
}
client := &SSHClient{
Config: sshConfig,
Host: "192.168.15.211",
Port: 22,
}
cmd := &SSHCommand{
Path: "ls -l $LC_DIR",
Env: []string{"LC_DIR=/"},
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
fmt.Printf("Running command: %s\n", cmd.Path)
if err := client.RunCommand(cmd); err != nil {
fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
os.Exit(1)
}
}
|
[
"\"SSH_AUTH_SOCK\""
] |
[] |
[
"SSH_AUTH_SOCK"
] |
[]
|
["SSH_AUTH_SOCK"]
|
go
| 1 | 0 | |
website/settings.py
|
"""
Django settings for website project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
import os
import django_heroku
from dj_database_url import parse as dburl
from decouple import config, Csv
# 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!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'cloudinary_storage',
'django.contrib.staticfiles',
'cloudinary',
# My Apps
'core',
'portfolio',
]
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',
]
# Django DebugToolbar
if DEBUG:
INSTALLED_APPS.append('debug_toolbar')
MIDDLEWARE.insert(0, 'debug_toolbar.middleware.DebugToolbarMiddleware')
INTERNAL_IPS = ['127.0.0.1']
ROOT_URLCONF = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
DATABASES = {
'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'
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_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Media Files (Uploads)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
COLLECTFAST_ENABLED = False
# Configure Django App for Heroku.
django_heroku.settings(locals())
# Force ssl if run in Heroku
if 'DYNO' in os.environ: # pragma: no cover
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Cloudinary
CLOUDINARY_STORAGE = {
'CLOUD_NAME': config('CLOUDINARY_NAME'),
'API_KEY': config('CLOUDINARY_API_KEY'),
'API_SECRET': config('CLOUDINARY_API_SECRET'),
'STATICFILES_MANIFEST_ROOT': os.path.join(BASE_DIR, 'static-manifest-directory')
}
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.RawMediaCloudinaryStorage'
STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage'
# Sentry
sentry_sdk.init(dsn=config('SENTRY_DSN'), integrations=[DjangoIntegration()])
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
pkg/testing/integration/program.go
|
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/pulumi/pulumi/pkg/apitype"
"github.com/pulumi/pulumi/pkg/backend/filestate"
"github.com/pulumi/pulumi/pkg/engine"
"github.com/pulumi/pulumi/pkg/operations"
"github.com/pulumi/pulumi/pkg/resource"
"github.com/pulumi/pulumi/pkg/resource/config"
"github.com/pulumi/pulumi/pkg/resource/stack"
pulumi_testing "github.com/pulumi/pulumi/pkg/testing"
"github.com/pulumi/pulumi/pkg/tokens"
"github.com/pulumi/pulumi/pkg/util/ciutil"
"github.com/pulumi/pulumi/pkg/util/contract"
"github.com/pulumi/pulumi/pkg/util/fsutil"
"github.com/pulumi/pulumi/pkg/util/retry"
"github.com/pulumi/pulumi/pkg/workspace"
)
const PythonRuntime = "python"
const NodeJSRuntime = "nodejs"
const GoRuntime = "go"
const DotNetRuntime = "dotnet"
// RuntimeValidationStackInfo contains details related to the stack that runtime validation logic may want to use.
type RuntimeValidationStackInfo struct {
StackName tokens.QName
Deployment *apitype.DeploymentV3
RootResource apitype.ResourceV3
Outputs map[string]interface{}
Events []apitype.EngineEvent
}
// EditDir is an optional edit to apply to the example, as subsequent deployments.
type EditDir struct {
Dir string
ExtraRuntimeValidation func(t *testing.T, stack RuntimeValidationStackInfo)
// Additive is true if Dir should be copied *on top* of the test directory.
// Otherwise Dir *replaces* the test directory, except we keep .pulumi/ and Pulumi.yaml and Pulumi.<stack>.yaml.
Additive bool
// ExpectFailure is true if we expect this test to fail. This is very coarse grained, and will essentially
// tolerate *any* failure in the program (IDEA: in the future, offer a way to narrow this down more).
ExpectFailure bool
// ExpectNoChanges is true if the edit is expected to not propose any changes.
ExpectNoChanges bool
// Stdout is the writer to use for all stdout messages.
Stdout io.Writer
// Stderr is the writer to use for all stderr messages.
Stderr io.Writer
// Verbose may be set to true to print messages as they occur, rather than buffering and showing upon failure.
Verbose bool
// Run program directory in query mode.
QueryMode bool
}
// TestCommandStats is a collection of data related to running a single command during a test.
type TestCommandStats struct {
// StartTime is the time at which the command was started
StartTime string `json:"startTime"`
// EndTime is the time at which the command exited
EndTime string `json:"endTime"`
// ElapsedSeconds is the time at which the command exited
ElapsedSeconds float64 `json:"elapsedSeconds"`
// StackName is the name of the stack
StackName string `json:"stackName"`
// TestId is the unique ID of the test run
TestID string `json:"testId"`
// StepName is the command line which was invoked
StepName string `json:"stepName"`
// CommandLine is the command line which was invoked
CommandLine string `json:"commandLine"`
// TestName is the name of the directory in which the test was executed
TestName string `json:"testName"`
// IsError is true if the command failed
IsError bool `json:"isError"`
// The Cloud that the test was run against, or empty for local deployments
CloudURL string `json:"cloudURL"`
}
// TestStatsReporter reports results and metadata from a test run.
type TestStatsReporter interface {
ReportCommand(stats TestCommandStats)
}
// ProgramTestOptions provides options for ProgramTest
type ProgramTestOptions struct {
// Dir is the program directory to test.
Dir string
// Array of NPM packages which must be `yarn linked` (e.g. {"pulumi", "@pulumi/aws"})
Dependencies []string
// Map of package names to versions. The test will use the specified versions of these packages instead of what
// is declared in `package.json`.
Overrides map[string]string
// Map of config keys and values to set (e.g. {"aws:region": "us-east-2"})
Config map[string]string
// Map of secure config keys and values to set on the stack (e.g. {"aws:region": "us-east-2"})
Secrets map[string]string
// SecretsProvider is the optional custom secrets provider to use instead of the default.
SecretsProvider string
// EditDirs is an optional list of edits to apply to the example, as subsequent deployments.
EditDirs []EditDir
// ExtraRuntimeValidation is an optional callback for additional validation, called before applying edits.
ExtraRuntimeValidation func(t *testing.T, stack RuntimeValidationStackInfo)
// RelativeWorkDir is an optional path relative to `Dir` which should be used as working directory during tests.
RelativeWorkDir string
// AllowEmptyPreviewChanges is true if we expect that this test's no-op preview may propose changes (e.g.
// because the test is sensitive to the exact contents of its working directory and those contents change
// incidentally between the initial update and the empty update).
AllowEmptyPreviewChanges bool
// AllowEmptyUpdateChanges is true if we expect that this test's no-op update may perform changes (e.g.
// because the test is sensitive to the exact contents of its working directory and those contents change
// incidentally between the initial update and the empty update).
AllowEmptyUpdateChanges bool
// ExpectFailure is true if we expect this test to fail. This is very coarse grained, and will essentially
// tolerate *any* failure in the program (IDEA: in the future, offer a way to narrow this down more).
ExpectFailure bool
// ExpectRefreshChanges may be set to true if a test is expected to have changes yielded by an immediate refresh.
// This could occur, for example, is a resource's state is constantly changing outside of Pulumi (e.g., timestamps).
ExpectRefreshChanges bool
// SkipRefresh indicates that the refresh step should be skipped entirely.
SkipRefresh bool
// SkipStackRemoval indicates that the stack should not be removed. (And so the test's results could be inspected
// in the Pulumi Service after the test has completed.)
SkipStackRemoval bool
// Quick can be set to true to run a "quick" test that skips any non-essential steps (e.g., empty updates).
Quick bool
// PreviewCommandlineFlags specifies flags to add to the `pulumi preview` command line (e.g. "--color=raw")
PreviewCommandlineFlags []string
// UpdateCommandlineFlags specifies flags to add to the `pulumi up` command line (e.g. "--color=raw")
UpdateCommandlineFlags []string
// QueryCommandlineFlags specifies flags to add to the `pulumi query` command line (e.g. "--color=raw")
QueryCommandlineFlags []string
// RunBuild indicates that the build step should be run (e.g. run `yarn build` for `nodejs` programs)
RunBuild bool
// RunUpdateTest will ensure that updates to the package version can test for spurious diffs
RunUpdateTest bool
// CloudURL is an optional URL to override the default Pulumi Service API (https://api.pulumi-staging.io). The
// PULUMI_ACCESS_TOKEN environment variable must also be set to a valid access token for the target cloud.
CloudURL string
// StackName allows the stack name to be explicitly provided instead of computed from the
// environment during tests.
StackName string
// Tracing specifies the Zipkin endpoint if any to use for tracing Pulumi invocations.
Tracing string
// NoParallel will opt the test out of being ran in parallel.
NoParallel bool
// PrePulumiCommand specifies a callback that will be executed before each `pulumi` invocation. This callback may
// optionally return another callback to be invoked after the `pulumi` invocation completes.
PrePulumiCommand func(verb string) (func(err error) error, error)
// ReportStats optionally specifies how to report results from the test for external collection.
ReportStats TestStatsReporter
// Stdout is the writer to use for all stdout messages.
Stdout io.Writer
// Stderr is the writer to use for all stderr messages.
Stderr io.Writer
// Verbose may be set to true to print messages as they occur, rather than buffering and showing upon failure.
Verbose bool
// DebugLogging may be set to anything >0 to enable excessively verbose debug logging from `pulumi`. This is
// equivalent to `--logtostderr -v=N`, where N is the value of DebugLogLevel. This may also be enabled by setting
// the environment variable PULUMI_TEST_DEBUG_LOG_LEVEL.
DebugLogLevel int
// DebugUpdates may be set to true to enable debug logging from `pulumi preview`, `pulumi up`, and
// `pulumi destroy`. This may also be enabled by setting the environment variable PULUMI_TEST_DEBUG_UPDATES.
DebugUpdates bool
// Bin is a location of a `pulumi` executable to be run. Taken from the $PATH if missing.
Bin string
// YarnBin is a location of a `yarn` executable to be run. Taken from the $PATH if missing.
YarnBin string
// GoBin is a location of a `go` executable to be run. Taken from the $PATH if missing.
GoBin string
// PipenvBin is a location of a `pipenv` executable to run. Taken from the $PATH if missing.
PipenvBin string
// DotNetBin is a location of a `dotnet` executable to be run. Taken from the $PATH if missing.
DotNetBin string
// Additional environment variables to pass for each command we run.
Env []string
}
func (opts *ProgramTestOptions) GetDebugLogLevel() int {
if opts.DebugLogLevel > 0 {
return opts.DebugLogLevel
}
if du := os.Getenv("PULUMI_TEST_DEBUG_LOG_LEVEL"); du != "" {
if n, e := strconv.Atoi(du); e != nil {
panic(e)
} else if n > 0 {
return n
}
}
return 0
}
func (opts *ProgramTestOptions) GetDebugUpdates() bool {
return opts.DebugUpdates || os.Getenv("PULUMI_TEST_DEBUG_UPDATES") != ""
}
// GetStackName returns a stack name to use for this test.
func (opts *ProgramTestOptions) GetStackName() tokens.QName {
if opts.StackName == "" {
// Fetch the host and test dir names, cleaned so to contain just [a-zA-Z0-9-_] chars.
hostname, err := os.Hostname()
contract.AssertNoErrorf(err, "failure to fetch hostname for stack prefix")
var host string
for _, c := range hostname {
if len(host) >= 10 {
break
}
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' {
host += string(c)
}
}
var test string
for _, c := range filepath.Base(opts.Dir) {
if len(test) >= 10 {
break
}
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' {
test += string(c)
}
}
b := make([]byte, 4)
_, err = cryptorand.Read(b)
contract.AssertNoError(err)
opts.StackName = strings.ToLower("p-it-" + host + "-" + test + "-" + hex.EncodeToString(b))
}
return tokens.QName(opts.StackName)
}
// GetStackNameWithOwner gets the name of the stack prepended with an owner, if PULUMI_TEST_OWNER is set.
// We use this in CI to create test stacks in an organization that all developers have access to, for debugging.
func (opts *ProgramTestOptions) GetStackNameWithOwner() tokens.QName {
if owner := os.Getenv("PULUMI_TEST_OWNER"); owner != "" {
return tokens.QName(fmt.Sprintf("%s/%s", owner, opts.GetStackName()))
}
return opts.GetStackName()
}
// With combines a source set of options with a set of overrides.
func (opts ProgramTestOptions) With(overrides ProgramTestOptions) ProgramTestOptions {
if overrides.Dir != "" {
opts.Dir = overrides.Dir
}
if overrides.Dependencies != nil {
opts.Dependencies = overrides.Dependencies
}
if overrides.Overrides != nil {
opts.Overrides = overrides.Overrides
}
for k, v := range overrides.Config {
if opts.Config == nil {
opts.Config = make(map[string]string)
}
opts.Config[k] = v
}
for k, v := range overrides.Secrets {
if opts.Secrets == nil {
opts.Secrets = make(map[string]string)
}
opts.Secrets[k] = v
}
if overrides.SecretsProvider != "" {
opts.SecretsProvider = overrides.SecretsProvider
}
if overrides.EditDirs != nil {
opts.EditDirs = overrides.EditDirs
}
if overrides.ExtraRuntimeValidation != nil {
opts.ExtraRuntimeValidation = overrides.ExtraRuntimeValidation
}
if overrides.RelativeWorkDir != "" {
opts.RelativeWorkDir = overrides.RelativeWorkDir
}
if overrides.AllowEmptyPreviewChanges {
opts.AllowEmptyPreviewChanges = overrides.AllowEmptyPreviewChanges
}
if overrides.AllowEmptyUpdateChanges {
opts.AllowEmptyUpdateChanges = overrides.AllowEmptyUpdateChanges
}
if overrides.ExpectFailure {
opts.ExpectFailure = overrides.ExpectFailure
}
if overrides.ExpectRefreshChanges {
opts.ExpectRefreshChanges = overrides.ExpectRefreshChanges
}
if overrides.SkipRefresh {
opts.SkipRefresh = overrides.SkipRefresh
}
if overrides.SkipStackRemoval {
opts.SkipStackRemoval = overrides.SkipStackRemoval
}
if overrides.Quick {
opts.Quick = overrides.Quick
}
if overrides.PreviewCommandlineFlags != nil {
opts.PreviewCommandlineFlags = append(opts.PreviewCommandlineFlags, overrides.PreviewCommandlineFlags...)
}
if overrides.UpdateCommandlineFlags != nil {
opts.UpdateCommandlineFlags = append(opts.UpdateCommandlineFlags, overrides.UpdateCommandlineFlags...)
}
if overrides.QueryCommandlineFlags != nil {
opts.QueryCommandlineFlags = append(opts.QueryCommandlineFlags, overrides.QueryCommandlineFlags...)
}
if overrides.RunBuild {
opts.RunBuild = overrides.RunBuild
}
if overrides.RunUpdateTest {
opts.RunUpdateTest = overrides.RunUpdateTest
}
if overrides.CloudURL != "" {
opts.CloudURL = overrides.CloudURL
}
if overrides.StackName != "" {
opts.StackName = overrides.StackName
}
if overrides.Tracing != "" {
opts.Tracing = overrides.Tracing
}
if overrides.NoParallel {
opts.NoParallel = overrides.NoParallel
}
if overrides.PrePulumiCommand != nil {
opts.PrePulumiCommand = overrides.PrePulumiCommand
}
if overrides.ReportStats != nil {
opts.ReportStats = overrides.ReportStats
}
if overrides.Stdout != nil {
opts.Stdout = overrides.Stdout
}
if overrides.Stderr != nil {
opts.Stderr = overrides.Stderr
}
if overrides.Verbose {
opts.Verbose = overrides.Verbose
}
if overrides.DebugLogLevel != 0 {
opts.DebugLogLevel = overrides.DebugLogLevel
}
if overrides.DebugUpdates {
opts.DebugUpdates = overrides.DebugUpdates
}
if overrides.Bin != "" {
opts.Bin = overrides.Bin
}
if overrides.YarnBin != "" {
opts.YarnBin = overrides.YarnBin
}
if overrides.GoBin != "" {
opts.GoBin = overrides.GoBin
}
if overrides.PipenvBin != "" {
opts.PipenvBin = overrides.PipenvBin
}
if overrides.Env != nil {
opts.Env = append(opts.Env, overrides.Env...)
}
return opts
}
type regexFlag struct {
re *regexp.Regexp
}
func (rf *regexFlag) String() string {
if rf.re == nil {
return ""
}
return rf.re.String()
}
func (rf *regexFlag) Set(v string) error {
r, err := regexp.Compile(v)
if err != nil {
return err
}
rf.re = r
return nil
}
var directoryMatcher regexFlag
var listDirs bool
var pipenvMutex *fsutil.FileMutex
func init() {
flag.Var(&directoryMatcher, "dirs", "optional list of regexes to use to select integration tests to run")
flag.BoolVar(&listDirs, "list-dirs", false, "list available integration tests without running them")
mutexPath := filepath.Join(os.TempDir(), "pipenv-mutex.lock")
pipenvMutex = fsutil.NewFileMutex(mutexPath)
}
// GetLogs retrieves the logs for a given stack in a particular region making the query provided.
//
// [provider] should be one of "aws" or "azure"
func GetLogs(
t *testing.T,
provider, region string,
stackInfo RuntimeValidationStackInfo,
query operations.LogQuery) *[]operations.LogEntry {
snap, err := stack.DeserializeDeploymentV3(*stackInfo.Deployment, stack.DefaultSecretsProvider)
assert.NoError(t, err)
tree := operations.NewResourceTree(snap.Resources)
if !assert.NotNil(t, tree) {
return nil
}
cfg := map[config.Key]string{
config.MustMakeKey(provider, "region"): region,
}
ops := tree.OperationsProvider(cfg)
// Validate logs from example
logs, err := ops.GetLogs(query)
if !assert.NoError(t, err) {
return nil
}
return logs
}
// ProgramTest runs a lifecycle of Pulumi commands in a program working directory, using the `pulumi` and `yarn`
// binaries available on PATH. It essentially executes the following workflow:
//
// yarn install
// yarn link <each opts.Depencies>
// (+) yarn run build
// pulumi init
// (*) pulumi login
// pulumi stack init integrationtesting
// pulumi config set <each opts.Config>
// pulumi config set --secret <each opts.Secrets>
// pulumi preview
// pulumi up
// pulumi stack export --file stack.json
// pulumi stack import --file stack.json
// pulumi preview (expected to be empty)
// pulumi up (expected to be empty)
// pulumi destroy --yes
// pulumi stack rm --yes integrationtesting
//
// (*) Only if PULUMI_ACCESS_TOKEN is set.
// (+) Only if `opts.RunBuild` is true.
//
// All commands must return success return codes for the test to succeed, unless ExpectFailure is true.
func ProgramTest(t *testing.T, opts *ProgramTestOptions) {
// If we're just listing tests, simply print this test's directory.
if listDirs {
fmt.Printf("%s\n", opts.Dir)
return
}
// If we have a matcher, ensure that this test matches its pattern.
if directoryMatcher.re != nil && !directoryMatcher.re.Match([]byte(opts.Dir)) {
t.Skip(fmt.Sprintf("Skipping: '%v' does not match '%v'", opts.Dir, directoryMatcher.re))
}
// Disable stack backups for tests to avoid filling up ~/.pulumi/backups with unnecessary
// backups of test stacks.
if err := os.Setenv(filestate.DisableCheckpointBackupsEnvVar, "1"); err != nil {
t.Errorf("error setting env var '%s': %v", filestate.DisableCheckpointBackupsEnvVar, err)
}
// We want tests to default into being ran in parallel, hence the odd double negative.
if !opts.NoParallel {
t.Parallel()
}
if ciutil.IsCI() && os.Getenv("PULUMI_ACCESS_TOKEN") == "" {
t.Skip("Skipping: PULUMI_ACCESS_TOKEN is not set")
}
// If the test panics, recover and log instead of letting the panic escape the test. Even though *this* test will
// have run deferred functions and cleaned up, if the panic reaches toplevel it will kill the process and prevent
// other tests running in parallel from cleaning up.
defer func() {
if failure := recover(); failure != nil {
t.Errorf("panic testing %v: %v", opts.Dir, failure)
}
}()
// Set up some default values for sending test reports and tracing data. We use environment varaiables to
// control these globally and set reasonable values for our own use in CI.
if opts.ReportStats == nil {
if v := os.Getenv("PULUMI_TEST_REPORT_CONFIG"); v != "" {
splits := strings.Split(v, ":")
if len(splits) != 3 {
t.Errorf("report config should be set to a value of the form: <aws-region>:<bucket-name>:<keyPrefix>")
}
opts.ReportStats = NewS3Reporter(splits[0], splits[1], splits[2])
}
}
if opts.Tracing == "" {
opts.Tracing = os.Getenv("PULUMI_TEST_TRACE_ENDPOINT")
}
pt := newProgramTester(t, opts)
err := pt.testLifeCycleInitAndDestroy()
assert.NoError(t, err)
}
// fprintf works like fmt.FPrintf, except it explicitly drops the return values. This keeps the linters happy, since
// they don't like to see errors dropped on the floor. It is possible that our call to fmt.Fprintf will fail, even
// for "standard" streams like `stdout` and `stderr`, if they have been set to non-blocking by an external process.
// In that case, we just drop the error on the floor and continue. We see this behavior in Travis when we try to write
// a lot of messages quickly (as we do when logging test failures)
func fprintf(w io.Writer, format string, a ...interface{}) {
_, err := fmt.Fprintf(w, format, a...)
contract.IgnoreError(err)
}
// programTester contains state associated with running a single test pass.
type programTester struct {
t *testing.T // the Go tester for this run.
opts *ProgramTestOptions // options that control this test run.
bin string // the `pulumi` binary we are using.
yarnBin string // the `yarn` binary we are using.
goBin string // the `go` binary we are using.
pipenvBin string // The `pipenv` binary we are using.
dotNetBin string // the `dotnet` binary we are using.
eventLog string // The path to the event log for this test.
}
func newProgramTester(t *testing.T, opts *ProgramTestOptions) *programTester {
stackName := opts.GetStackName()
return &programTester{
t: t,
opts: opts,
eventLog: path.Join(os.TempDir(), string(stackName)+"-events.json"),
}
}
func (pt *programTester) getBin() (string, error) {
return getCmdBin(&pt.bin, "pulumi", pt.opts.Bin)
}
func (pt *programTester) getYarnBin() (string, error) {
return getCmdBin(&pt.yarnBin, "yarn", pt.opts.YarnBin)
}
func (pt *programTester) getGoBin() (string, error) {
return getCmdBin(&pt.goBin, "go", pt.opts.GoBin)
}
// getPipenvBin returns a path to the currently-installed Pipenv tool, or an error if the tool could not be found.
func (pt *programTester) getPipenvBin() (string, error) {
return getCmdBin(&pt.pipenvBin, "pipenv", pt.opts.PipenvBin)
}
func (pt *programTester) getDotNetBin() (string, error) {
return getCmdBin(&pt.dotNetBin, "dotnet", pt.opts.DotNetBin)
}
func (pt *programTester) pulumiCmd(args []string) ([]string, error) {
bin, err := pt.getBin()
if err != nil {
return nil, err
}
cmd := []string{bin}
if du := pt.opts.GetDebugLogLevel(); du > 0 {
cmd = append(cmd, "--logtostderr", "-v="+strconv.Itoa(du))
}
cmd = append(cmd, args...)
if tracing := pt.opts.Tracing; tracing != "" {
cmd = append(cmd, "--tracing", tracing)
}
return cmd, nil
}
func (pt *programTester) yarnCmd(args []string) ([]string, error) {
bin, err := pt.getYarnBin()
if err != nil {
return nil, err
}
result := []string{bin}
result = append(result, args...)
return withOptionalYarnFlags(result), nil
}
func (pt *programTester) pipenvCmd(args []string) ([]string, error) {
bin, err := pt.getPipenvBin()
if err != nil {
return nil, err
}
cmd := []string{bin}
return append(cmd, args...), nil
}
func (pt *programTester) runCommand(name string, args []string, wd string) error {
return RunCommand(pt.t, name, args, wd, pt.opts)
}
func (pt *programTester) runPulumiCommand(name string, args []string, wd string) error {
cmd, err := pt.pulumiCmd(args)
if err != nil {
return err
}
var postFn func(error) error
if pt.opts.PrePulumiCommand != nil {
postFn, err = pt.opts.PrePulumiCommand(args[0])
if err != nil {
return err
}
}
// If we're doing a preview or an update and this project is a Python project, we need to run
// the command in the context of the virtual environment that Pipenv created in order to pick up
// the correct version of Python. We also need to do this for destroy and refresh so that
// dynamic providers are run in the right virtual environment.
if args[0] == "preview" || args[0] == "up" || args[0] == "destroy" || args[0] == "refresh" {
projinfo, err := pt.getProjinfo(wd)
if err != nil {
return nil
}
if projinfo.Proj.Runtime.Name() == "python" {
pipenvBin, err := pt.getPipenvBin()
if err != nil {
return err
}
// "pipenv run" activates the current virtual environment and runs the remainder of the arguments as if it
// were a command.
cmd = append([]string{pipenvBin, "run"}, cmd...)
}
}
runErr := pt.runCommand(name, cmd, wd)
if postFn != nil {
if postErr := postFn(runErr); postErr != nil {
return multierror.Append(runErr, postErr)
}
}
return runErr
}
func (pt *programTester) runYarnCommand(name string, args []string, wd string) error {
cmd, err := pt.yarnCmd(args)
if err != nil {
return err
}
_, _, err = retry.Until(context.Background(), retry.Acceptor{
Accept: func(try int, nextRetryTime time.Duration) (bool, interface{}, error) {
runerr := pt.runCommand(name, cmd, wd)
if runerr == nil {
return true, nil, nil
} else if _, ok := runerr.(*exec.ExitError); ok {
// yarn failed, let's try again, assuming we haven't failed a few times.
if try > 3 {
return false, nil, errors.Errorf("%v did not complete after %v tries", cmd, try)
}
return false, nil, nil
}
// someother error, fail
return false, nil, runerr
},
})
return err
}
func (pt *programTester) runPipenvCommand(name string, args []string, wd string) error {
// Pipenv uses setuptools to install and uninstall packages. Setuptools has an installation mode called "develop"
// that we use to install the package being tested, since it is 1) lightweight and 2) not doing so has its own set
// of annoying problems.
//
// Setuptools develop does three things:
// 1. It invokes the "egg_info" command in the target package,
// 2. It creates a special `.egg-link` sentinel file in the current site-packages folder, pointing to the package
// being installed's path on disk
// 3. It updates easy-install.pth in site-packages so that pip understand that this package has been installed.
//
// Steps 2 and 3 operate entirely within the context of a virtualenv. The state that they mutate is fully contained
// within the current virtualenv. However, step 1 operates in the context of the package's source tree. Egg info
// is responsible for producing a minimal "egg" for a particular package, and its largest responsibility is creating
// a PKG-INFO file for a package. PKG-INFO contains, among other things, the version of the package being installed.
//
// If two packages are being installed in "develop" mode simultaneously (which happens often, when running tests),
// both installations will run "egg_info" on the source tree and both processes will be writing the same files
// simultaneously. If one process catches "PKG-INFO" in a half-written state, the one process that observed the
// torn write will fail to install the package (setuptools crashes).
//
// To avoid this problem, we use pipenvMutex to explicitly serialize installation operations. Doing so avoids the
// problem of multiple processes stomping on the same files in the source tree. Note that pipenvMutex is a file
// mutex, so this strategy works even if the go test runner chooses to split up text execution across multiple
// processes. (Furthermore, each test gets an instance of programTester and thus the mutex, so we'd need to be
// sharing the mutex globally in each test process if we weren't using the file system to lock.)
if name == "pipenv-install-package" {
if err := pipenvMutex.Lock(); err != nil {
panic(err)
}
if pt.opts.Verbose {
fprintf(pt.opts.Stdout, "acquired pipenv install lock\n")
defer fprintf(pt.opts.Stdout, "released pipenv install lock\n")
}
defer func() {
if err := pipenvMutex.Unlock(); err != nil {
panic(err)
}
}()
}
cmd, err := pt.pipenvCmd(args)
if err != nil {
return err
}
return pt.runCommand(name, cmd, wd)
}
func (pt *programTester) testLifeCycleInitAndDestroy() error {
tmpdir, projdir, err := pt.copyTestToTemporaryDirectory()
if err != nil {
return errors.Wrap(err, "copying test to temp dir")
}
testFinished := false
defer func() {
if tmpdir != "" {
if !testFinished || pt.t.Failed() {
// Test aborted or failed. Maybe copy to "failed tests" directory.
failedTestsDir := os.Getenv("PULUMI_FAILED_TESTS_DIR")
if failedTestsDir != "" {
dest := filepath.Join(failedTestsDir, pt.t.Name()+uniqueSuffix())
contract.IgnoreError(fsutil.CopyFile(dest, tmpdir, nil))
}
} else {
contract.IgnoreError(os.RemoveAll(tmpdir))
}
} else {
// When tmpdir is empty, we ran "in tree", which means we wrote output
// to the "command-output" folder in the projdir, and we should clean
// it up if the test passed
if testFinished && !pt.t.Failed() {
contract.IgnoreError(os.RemoveAll(filepath.Join(projdir, commandOutputFolderName)))
}
}
}()
err = pt.testLifeCycleInitialize(projdir)
if err != nil {
return errors.Wrap(err, "initializing test project")
}
// Ensure that before we exit, we attempt to destroy and remove the stack.
defer func() {
if projdir != "" {
destroyErr := pt.testLifeCycleDestroy(projdir)
assert.NoError(pt.t, destroyErr)
}
}()
if err = pt.testPreviewUpdateAndEdits(projdir); err != nil {
return errors.Wrap(err, "running test preview, update, and edits")
}
if pt.opts.RunUpdateTest {
err = upgradeProjectDeps(projdir, pt)
if err != nil {
return errors.Wrap(err, "upgrading project dependencies")
}
if err = pt.testPreviewUpdateAndEdits(projdir); err != nil {
return errors.Wrap(err, "running test preview, update, and edits")
}
}
testFinished = true
return nil
}
func upgradeProjectDeps(projectDir string, pt *programTester) error {
projInfo, err := pt.getProjinfo(projectDir)
if err != nil {
return errors.Wrap(err, "getting project info")
}
switch rt := projInfo.Proj.Runtime.Name(); rt {
case NodeJSRuntime:
if err = pt.yarnLinkPackageDeps(projectDir); err != nil {
return err
}
case PythonRuntime:
if err = pt.installPipPackageDeps(projectDir); err != nil {
return err
}
default:
return errors.Errorf("unrecognized project runtime: %s", rt)
}
return nil
}
func (pt *programTester) testLifeCycleInitialize(dir string) error {
stackName := pt.opts.GetStackName()
// If RelativeWorkDir is specified, apply that relative to the temp folder for use as working directory during tests.
if pt.opts.RelativeWorkDir != "" {
dir = path.Join(dir, pt.opts.RelativeWorkDir)
}
// Set the default target Pulumi API if not overridden in options.
if pt.opts.CloudURL == "" {
pulumiAPI := os.Getenv("PULUMI_API")
if pulumiAPI != "" {
pt.opts.CloudURL = pulumiAPI
}
}
// Ensure all links are present, the stack is created, and all configs are applied.
fprintf(pt.opts.Stdout, "Initializing project (dir %s; stack %s)\n", dir, stackName)
// Login as needed.
stackInitName := string(pt.opts.GetStackNameWithOwner())
if os.Getenv("PULUMI_ACCESS_TOKEN") == "" && pt.opts.CloudURL == "" {
fmt.Printf("Using existing logged in user for tests. Set PULUMI_ACCESS_TOKEN and/or PULUMI_API to override.\n")
} else {
// Set PulumiCredentialsPathEnvVar to our CWD, so we use credentials specific to just this
// test.
pt.opts.Env = append(pt.opts.Env, fmt.Sprintf("%s=%s", workspace.PulumiCredentialsPathEnvVar, dir))
loginArgs := []string{"login"}
loginArgs = addFlagIfNonNil(loginArgs, "--cloud-url", pt.opts.CloudURL)
// If this is a local OR cloud login, then don't attach the owner to the stack-name.
if pt.opts.CloudURL != "" {
stackInitName = string(pt.opts.GetStackName())
}
if err := pt.runPulumiCommand("pulumi-login", loginArgs, dir); err != nil {
return err
}
}
// Stack init
stackInitArgs := []string{"stack", "init", stackInitName}
if pt.opts.SecretsProvider != "" {
stackInitArgs = append(stackInitArgs, "--secrets-provider", pt.opts.SecretsProvider)
}
if err := pt.runPulumiCommand("pulumi-stack-init", stackInitArgs, dir); err != nil {
return err
}
for key, value := range pt.opts.Config {
if err := pt.runPulumiCommand("pulumi-config",
[]string{"config", "set", key, value}, dir); err != nil {
return err
}
}
for key, value := range pt.opts.Secrets {
if err := pt.runPulumiCommand("pulumi-config",
[]string{"config", "set", "--secret", key, value}, dir); err != nil {
return err
}
}
return nil
}
func (pt *programTester) testLifeCycleDestroy(dir string) error {
// Destroy and remove the stack.
fprintf(pt.opts.Stdout, "Destroying stack\n")
destroy := []string{"destroy", "--non-interactive", "--skip-preview"}
if pt.opts.GetDebugUpdates() {
destroy = append(destroy, "-d")
}
if err := pt.runPulumiCommand("pulumi-destroy", destroy, dir); err != nil {
return err
}
if pt.t.Failed() {
fprintf(pt.opts.Stdout, "Test failed, retaining stack '%s'\n", pt.opts.GetStackNameWithOwner())
return nil
}
if !pt.opts.SkipStackRemoval {
return pt.runPulumiCommand("pulumi-stack-rm", []string{"stack", "rm", "--yes"}, dir)
}
return nil
}
func (pt *programTester) testPreviewUpdateAndEdits(dir string) error {
// Now preview and update the real changes.
fprintf(pt.opts.Stdout, "Performing primary preview and update\n")
initErr := pt.previewAndUpdate(dir, "initial", pt.opts.ExpectFailure, false, false)
// If the initial preview/update failed, just exit without trying the rest (but make sure to destroy).
if initErr != nil {
return initErr
}
// Perform an empty preview and update; nothing is expected to happen here.
if !pt.opts.Quick {
fprintf(pt.opts.Stdout, "Roundtripping checkpoint via stack export and stack import\n")
if err := pt.exportImport(dir); err != nil {
return err
}
msg := ""
if !pt.opts.AllowEmptyUpdateChanges {
msg = "(no changes expected)"
}
fprintf(pt.opts.Stdout, "Performing empty preview and update%s\n", msg)
if err := pt.previewAndUpdate(
dir, "empty", false, !pt.opts.AllowEmptyPreviewChanges, !pt.opts.AllowEmptyUpdateChanges); err != nil {
return err
}
}
// Run additional validation provided by the test options, passing in the checkpoint info.
if err := pt.performExtraRuntimeValidation(pt.opts.ExtraRuntimeValidation, dir); err != nil {
return err
}
if !pt.opts.SkipRefresh {
// Perform a refresh and ensure it doesn't yield changes.
refresh := []string{"refresh", "--non-interactive", "--skip-preview"}
if pt.opts.GetDebugUpdates() {
refresh = append(refresh, "-d")
}
if !pt.opts.ExpectRefreshChanges {
refresh = append(refresh, "--expect-no-changes")
}
if err := pt.runPulumiCommand("pulumi-refresh", refresh, dir); err != nil {
return err
}
}
// If there are any edits, apply them and run a preview and update for each one.
return pt.testEdits(dir)
}
func (pt *programTester) exportImport(dir string) error {
exportCmd := []string{"stack", "export", "--file", "stack.json"}
importCmd := []string{"stack", "import", "--file", "stack.json"}
defer func() {
contract.IgnoreError(os.Remove(filepath.Join(dir, "stack.json")))
}()
if err := pt.runPulumiCommand("pulumi-stack-export", exportCmd, dir); err != nil {
return err
}
return pt.runPulumiCommand("pulumi-stack-import", importCmd, dir)
}
func (pt *programTester) previewAndUpdate(dir string, name string, shouldFail, expectNopPreview,
expectNopUpdate bool) error {
preview := []string{"preview", "--non-interactive"}
update := []string{"up", "--non-interactive", "--skip-preview", "--event-log", pt.eventLog}
if pt.opts.GetDebugUpdates() {
preview = append(preview, "-d")
update = append(update, "-d")
}
if expectNopPreview {
preview = append(preview, "--expect-no-changes")
}
if expectNopUpdate {
update = append(update, "--expect-no-changes")
}
if pt.opts.PreviewCommandlineFlags != nil {
preview = append(preview, pt.opts.PreviewCommandlineFlags...)
}
if pt.opts.UpdateCommandlineFlags != nil {
update = append(update, pt.opts.UpdateCommandlineFlags...)
}
// If not in quick mode, run an explicit preview.
if !pt.opts.Quick {
if err := pt.runPulumiCommand("pulumi-preview-"+name, preview, dir); err != nil {
if shouldFail {
fprintf(pt.opts.Stdout, "Permitting failure (ExpectFailure=true for this preview)\n")
return nil
}
return err
}
}
// Now run an update.
if err := pt.runPulumiCommand("pulumi-update-"+name, update, dir); err != nil {
if shouldFail {
fprintf(pt.opts.Stdout, "Permitting failure (ExpectFailure=true for this update)\n")
return nil
}
return err
}
// If we expected a failure, but none occurred, return an error.
if shouldFail {
return errors.New("expected this step to fail, but it succeeded")
}
return nil
}
func (pt *programTester) query(dir string, name string, shouldFail bool) error {
query := []string{"query", "--non-interactive"}
if pt.opts.GetDebugUpdates() {
query = append(query, "-d")
}
if pt.opts.QueryCommandlineFlags != nil {
query = append(query, pt.opts.QueryCommandlineFlags...)
}
// Now run a query.
if err := pt.runPulumiCommand("pulumi-query-"+name, query, dir); err != nil {
if shouldFail {
fprintf(pt.opts.Stdout, "Permitting failure (ExpectFailure=true for this update)\n")
return nil
}
return err
}
// If we expected a failure, but none occurred, return an error.
if shouldFail {
return errors.New("expected this step to fail, but it succeeded")
}
return nil
}
func (pt *programTester) testEdits(dir string) error {
for i, edit := range pt.opts.EditDirs {
var err error
if err = pt.testEdit(dir, i, edit); err != nil {
return err
}
}
return nil
}
func (pt *programTester) testEdit(dir string, i int, edit EditDir) error {
fprintf(pt.opts.Stdout, "Applying edit '%v' and rerunning preview and update\n", edit.Dir)
if edit.Additive {
// Just copy new files into dir
if err := fsutil.CopyFile(dir, edit.Dir, nil); err != nil {
return errors.Wrapf(err, "Couldn't copy %v into %v", edit.Dir, dir)
}
} else {
// Create a new temporary directory
newDir, err := ioutil.TempDir("", pt.opts.StackName+"-")
if err != nil {
return errors.Wrapf(err, "Couldn't create new temporary directory")
}
// Delete whichever copy of the test is unused when we return
dirToDelete := newDir
defer func() {
contract.IgnoreError(os.RemoveAll(dirToDelete))
}()
// Copy everything except Pulumi.yaml, Pulumi.<stack-name>.yaml, and .pulumi from source into new directory
exclusions := make(map[string]bool)
projectYaml := workspace.ProjectFile + ".yaml"
configYaml := workspace.ProjectFile + "." + pt.opts.StackName + ".yaml"
exclusions[workspace.BookkeepingDir] = true
exclusions[projectYaml] = true
exclusions[configYaml] = true
if err := fsutil.CopyFile(newDir, edit.Dir, exclusions); err != nil {
return errors.Wrapf(err, "Couldn't copy %v into %v", edit.Dir, newDir)
}
// Copy Pulumi.yaml, Pulumi.<stack-name>.yaml, and .pulumi from old directory to new directory
oldProjectYaml := filepath.Join(dir, projectYaml)
newProjectYaml := filepath.Join(newDir, projectYaml)
oldConfigYaml := filepath.Join(dir, configYaml)
newConfigYaml := filepath.Join(newDir, configYaml)
oldProjectDir := filepath.Join(dir, workspace.BookkeepingDir)
newProjectDir := filepath.Join(newDir, workspace.BookkeepingDir)
if err := fsutil.CopyFile(newProjectYaml, oldProjectYaml, nil); err != nil {
return errors.Wrap(err, "Couldn't copy Pulumi.yaml")
}
if err := fsutil.CopyFile(newConfigYaml, oldConfigYaml, nil); err != nil {
return errors.Wrapf(err, "Couldn't copy Pulumi.%s.yaml", pt.opts.StackName)
}
if err := fsutil.CopyFile(newProjectDir, oldProjectDir, nil); err != nil {
return errors.Wrap(err, "Couldn't copy .pulumi")
}
// Finally, replace our current temp directory with the new one.
dirOld := dir + ".old"
if err := os.Rename(dir, dirOld); err != nil {
return errors.Wrapf(err, "Couldn't rename %v to %v", dir, dirOld)
}
// There's a brief window here where the old temp dir name could be taken from us.
if err := os.Rename(newDir, dir); err != nil {
return errors.Wrapf(err, "Couldn't rename %v to %v", newDir, dir)
}
// Keep dir, delete oldDir
dirToDelete = dirOld
}
err := pt.prepareProjectDir(dir)
if err != nil {
return errors.Wrapf(err, "Couldn't prepare project in %v", dir)
}
oldStdOut := pt.opts.Stdout
oldStderr := pt.opts.Stderr
oldVerbose := pt.opts.Verbose
if edit.Stdout != nil {
pt.opts.Stdout = edit.Stdout
}
if edit.Stderr != nil {
pt.opts.Stderr = edit.Stderr
}
if edit.Verbose {
pt.opts.Verbose = true
}
defer func() {
pt.opts.Stdout = oldStdOut
pt.opts.Stderr = oldStderr
pt.opts.Verbose = oldVerbose
}()
if !edit.QueryMode {
if err = pt.previewAndUpdate(dir, fmt.Sprintf("edit-%d", i),
edit.ExpectFailure, edit.ExpectNoChanges, edit.ExpectNoChanges); err != nil {
return err
}
} else {
if err = pt.query(dir, fmt.Sprintf("query-%d", i), edit.ExpectFailure); err != nil {
return err
}
}
return pt.performExtraRuntimeValidation(edit.ExtraRuntimeValidation, dir)
}
func (pt *programTester) performExtraRuntimeValidation(
extraRuntimeValidation func(t *testing.T, stack RuntimeValidationStackInfo), dir string) error {
if extraRuntimeValidation == nil {
return nil
}
stackName := pt.opts.GetStackName()
// Create a temporary file name for the stack export
tempDir, err := ioutil.TempDir("", string(stackName))
if err != nil {
return err
}
fileName := path.Join(tempDir, "stack.json")
// Invoke `pulumi stack export`
if err = pt.runPulumiCommand("pulumi-export", []string{"stack", "export", "--file", fileName}, dir); err != nil {
return errors.Wrapf(err, "expected to export stack to file: %s", fileName)
}
// Open the exported JSON file
f, err := os.Open(fileName)
if err != nil {
return errors.Wrapf(err, "expected to be able to open file with stack exports: %s", fileName)
}
defer func() {
contract.IgnoreClose(f)
contract.IgnoreError(os.RemoveAll(tempDir))
}()
// Unmarshal the Deployment
var untypedDeployment apitype.UntypedDeployment
if err = json.NewDecoder(f).Decode(&untypedDeployment); err != nil {
return err
}
var deployment apitype.DeploymentV3
if err = json.Unmarshal(untypedDeployment.Deployment, &deployment); err != nil {
return err
}
// Get the root resource and outputs from the deployment
var rootResource apitype.ResourceV3
var outputs map[string]interface{}
for _, res := range deployment.Resources {
if res.Type == resource.RootStackType {
rootResource = res
outputs = res.Outputs
}
}
// Read the event log.
eventsFile, err := os.Open(pt.eventLog)
if err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "expected to be able to open event log file %s", pt.eventLog)
}
defer contract.IgnoreClose(eventsFile)
decoder, events := json.NewDecoder(eventsFile), []apitype.EngineEvent{}
for {
var event apitype.EngineEvent
if err = decoder.Decode(&event); err != nil {
if err == io.EOF {
break
}
return errors.Wrapf(err, "decoding engine event")
}
events = append(events, event)
}
// Populate stack info object with all of this data to pass to the validation function
stackInfo := RuntimeValidationStackInfo{
StackName: pt.opts.GetStackName(),
Deployment: &deployment,
RootResource: rootResource,
Outputs: outputs,
Events: events,
}
fprintf(pt.opts.Stdout, "Performing extra runtime validation.\n")
extraRuntimeValidation(pt.t, stackInfo)
fprintf(pt.opts.Stdout, "Extra runtime validation complete.\n")
return nil
}
// copyTestToTemporaryDirectory creates a temporary directory to run the test in and copies the test to it.
func (pt *programTester) copyTestToTemporaryDirectory() (string, string, error) {
// Get the source dir and project info.
sourceDir := pt.opts.Dir
projinfo, err := pt.getProjinfo(sourceDir)
if err != nil {
return "", "", err
}
// Set up a prefix so that all output has the test directory name in it. This is important for debugging
// because we run tests in parallel, and so all output will be interleaved and difficult to follow otherwise.
var prefix string
if len(sourceDir) <= 30 {
prefix = fmt.Sprintf("[ %30.30s ] ", sourceDir)
} else {
prefix = fmt.Sprintf("[ %30.30s ] ", sourceDir[len(sourceDir)-30:])
}
stdout := pt.opts.Stdout
if stdout == nil {
stdout = newPrefixer(os.Stdout, prefix)
pt.opts.Stdout = stdout
}
stderr := pt.opts.Stderr
if stderr == nil {
stderr = newPrefixer(os.Stderr, prefix)
pt.opts.Stderr = stderr
}
fprintf(pt.opts.Stdout, "sample: %v\n", sourceDir)
bin, err := pt.getBin()
if err != nil {
return "", "", err
}
fprintf(pt.opts.Stdout, "pulumi: %v\n", bin)
// For most projects, we will copy to a temporary directory. For Go projects, however, we must not perturb
// the source layout, due to GOPATH and vendoring. So, skip it for Go.
var tmpdir, projdir string
if projinfo.Proj.Runtime.Name() == "go" {
projdir = projinfo.Root
} else {
stackName := string(pt.opts.GetStackName())
targetDir, tempErr := ioutil.TempDir("", stackName+"-")
if tempErr != nil {
return "", "", errors.Wrap(tempErr, "Couldn't create temporary directory")
}
// Copy the source project.
if copyErr := fsutil.CopyFile(targetDir, sourceDir, nil); copyErr != nil {
return "", "", copyErr
}
// Set tmpdir so that the caller will clean up afterwards.
tmpdir = targetDir
projdir = targetDir
}
projinfo.Root = projdir
err = pt.prepareProject(projinfo)
if err != nil {
return "", "", errors.Wrapf(err, "Failed to prepare %v", projdir)
}
fprintf(stdout, "projdir: %v\n", projdir)
return tmpdir, projdir, nil
}
func (pt *programTester) getProjinfo(projectDir string) (*engine.Projinfo, error) {
// Load up the package so we know things like what language the project is.
projfile := filepath.Join(projectDir, workspace.ProjectFile+".yaml")
proj, err := workspace.LoadProject(projfile)
if err != nil {
return nil, err
}
return &engine.Projinfo{Proj: proj, Root: projectDir}, nil
}
// prepareProject runs setup necessary to get the project ready for `pulumi` commands.
func (pt *programTester) prepareProject(projinfo *engine.Projinfo) error {
// Based on the language, invoke the right routine to prepare the target directory.
switch rt := projinfo.Proj.Runtime.Name(); rt {
case NodeJSRuntime:
return pt.prepareNodeJSProject(projinfo)
case PythonRuntime:
return pt.preparePythonProject(projinfo)
case GoRuntime:
return pt.prepareGoProject(projinfo)
case DotNetRuntime:
return pt.prepareDotNetProject(projinfo)
default:
return errors.Errorf("unrecognized project runtime: %s", rt)
}
}
// prepareProjectDir runs setup necessary to get the project ready for `pulumi` commands.
func (pt *programTester) prepareProjectDir(projectDir string) error {
projinfo, err := pt.getProjinfo(projectDir)
if err != nil {
return err
}
return pt.prepareProject(projinfo)
}
// prepareNodeJSProject runs setup necessary to get a Node.js project ready for `pulumi` commands.
func (pt *programTester) prepareNodeJSProject(projinfo *engine.Projinfo) error {
if err := pulumi_testing.WriteYarnRCForTest(projinfo.Root); err != nil {
return err
}
// Get the correct pwd to run Yarn in.
cwd, _, err := projinfo.GetPwdMain()
if err != nil {
return err
}
// If the test requested some packages to be overridden, we do two things. First, if the package is listed as a
// direct dependency of the project, we change the version constraint in the package.json. For transitive
// dependeices, we use yarn's "resolutions" feature to force them to a specific version.
if len(pt.opts.Overrides) > 0 {
packageJSON, err := readPackageJSON(cwd)
if err != nil {
return err
}
resolutions := make(map[string]interface{})
for packageName, packageVersion := range pt.opts.Overrides {
for _, section := range []string{"dependencies", "devDependencies"} {
if _, has := packageJSON[section]; has {
entry := packageJSON[section].(map[string]interface{})
if _, has := entry[packageName]; has {
entry[packageName] = packageVersion
}
}
}
fprintf(pt.opts.Stdout, "adding resolution for %s to version %s\n", packageName, packageVersion)
resolutions["**/"+packageName] = packageVersion
}
// Wack any existing resolutions section with our newly computed one.
packageJSON["resolutions"] = resolutions
if err := writePackageJSON(cwd, packageJSON); err != nil {
return err
}
}
// Now ensure dependencies are present.
if err = pt.runYarnCommand("yarn-install", []string{"install"}, cwd); err != nil {
return err
}
if !pt.opts.RunUpdateTest {
if err = pt.yarnLinkPackageDeps(cwd); err != nil {
return err
}
}
if pt.opts.RunBuild {
// And finally compile it using whatever build steps are in the package.json file.
if err = pt.runYarnCommand("yarn-build", []string{"run", "build"}, cwd); err != nil {
return err
}
}
return nil
}
// readPackageJSON unmarshals the package.json file located in pathToPackage.
func readPackageJSON(pathToPackage string) (map[string]interface{}, error) {
f, err := os.Open(filepath.Join(pathToPackage, "package.json"))
if err != nil {
return nil, errors.Wrap(err, "opening package.json")
}
defer contract.IgnoreClose(f)
var ret map[string]interface{}
if err := json.NewDecoder(f).Decode(&ret); err != nil {
return nil, errors.Wrap(err, "decoding package.json")
}
return ret, nil
}
func writePackageJSON(pathToPackage string, metadata map[string]interface{}) error {
// os.Create truncates the already existing file.
f, err := os.Create(filepath.Join(pathToPackage, "package.json"))
if err != nil {
return errors.Wrap(err, "opening package.json")
}
defer contract.IgnoreClose(f)
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
return errors.Wrap(encoder.Encode(metadata), "writing package.json")
}
// preparePythonProject runs setup necessary to get a Python project ready for `pulumi` commands.
func (pt *programTester) preparePythonProject(projinfo *engine.Projinfo) error {
cwd, _, err := projinfo.GetPwdMain()
if err != nil {
return err
}
// Create a new Pipenv environment. This bootstraps a new virtual environment containing the version of Python that
// we requested. Note that this version of Python is sourced from the machine, so you must first install the version
// of Python that you are requesting on the host machine before building a virtualenv for it.
if err = pt.runPipenvCommand("pipenv-new", []string{"--python", "3"}, cwd); err != nil {
return err
}
// Install the package's dependencies. We do this by running `pip` inside the virtualenv that `pipenv` has created.
// We don't use `pipenv install` because we don't want a lock file and prefer the similar model of `pip install`
// which matches what our customers do
err = pt.runPipenvCommand("pipenv-install", []string{"run", "pip", "install", "-r", "requirements.txt"}, cwd)
if err != nil {
return err
}
if !pt.opts.RunUpdateTest {
if err = pt.installPipPackageDeps(cwd); err != nil {
return err
}
}
return nil
}
func (pt *programTester) yarnLinkPackageDeps(cwd string) error {
for _, dependency := range pt.opts.Dependencies {
if err := pt.runYarnCommand("yarn-link", []string{"link", dependency}, cwd); err != nil {
return err
}
}
return nil
}
func (pt *programTester) installPipPackageDeps(cwd string) error {
var err error
for _, dep := range pt.opts.Dependencies {
// If the given filepath isn't absolute, make it absolute. We're about to pass it to pipenv and pipenv is
// operating inside of a random folder in /tmp.
if !path.IsAbs(dep) {
dep, err = filepath.Abs(dep)
if err != nil {
return err
}
}
err := pt.runPipenvCommand("pipenv-install-package", []string{"run", "pip", "install", "-e", dep}, cwd)
if err != nil {
return err
}
}
return nil
}
// prepareGoProject runs setup necessary to get a Go project ready for `pulumi` commands.
func (pt *programTester) prepareGoProject(projinfo *engine.Projinfo) error {
// Go programs are compiled, so we will compile the project first.
goBin, err := pt.getGoBin()
if err != nil {
return errors.Wrap(err, "locating `go` binary")
}
// Ensure GOPATH is known.
gopath := os.Getenv("GOPATH")
if gopath == "" {
usr, userErr := user.Current()
if userErr != nil {
return userErr
}
gopath = filepath.Join(usr.HomeDir, "go")
}
// To compile, simply run `go build -o $GOPATH/bin/<projname> .` from the project's working directory.
cwd, _, err := projinfo.GetPwdMain()
if err != nil {
return err
}
outBin := filepath.Join(gopath, "bin", string(projinfo.Proj.Name))
return pt.runCommand("go-build", []string{goBin, "build", "-o", outBin, "."}, cwd)
}
// prepareDotNetProject runs setup necessary to get a .NET project ready for `pulumi` commands.
func (pt *programTester) prepareDotNetProject(projinfo *engine.Projinfo) error {
dotNetBin, err := pt.getDotNetBin()
if err != nil {
return errors.Wrap(err, "locating `dotnet` binary")
}
cwd, _, err := projinfo.GetPwdMain()
if err != nil {
return err
}
localNuget := os.Getenv("PULUMI_LOCAL_NUGET")
if localNuget == "" {
usr, err := user.Current()
if err != nil {
return errors.Wrap(err, "could not determine current user")
}
localNuget = filepath.Join(usr.HomeDir, ".nuget", "local")
}
// dotnet add package requires a specific version in case of a pre-release, so we have to look it up.
matches, err := filepath.Glob(filepath.Join(localNuget, "Pulumi.?.?.*.nupkg"))
if err != nil {
return errors.Wrap(err, "failed to find a local Pulumi NuGet package")
}
if len(matches) != 1 {
return errors.New(fmt.Sprintf("attempting to find a local Pulumi NuGet package yielded %v results", matches))
}
file := filepath.Base(matches[0])
r := strings.NewReplacer("Pulumi.", "", ".nupkg", "")
version := r.Replace(file)
return pt.runCommand("dotnet-add-package",
[]string{dotNetBin, "add", "package", "Pulumi", "-s", localNuget, "-v", version}, cwd)
}
|
[
"\"PULUMI_TEST_DEBUG_LOG_LEVEL\"",
"\"PULUMI_TEST_DEBUG_UPDATES\"",
"\"PULUMI_TEST_OWNER\"",
"\"PULUMI_ACCESS_TOKEN\"",
"\"PULUMI_TEST_REPORT_CONFIG\"",
"\"PULUMI_TEST_TRACE_ENDPOINT\"",
"\"PULUMI_FAILED_TESTS_DIR\"",
"\"PULUMI_API\"",
"\"PULUMI_ACCESS_TOKEN\"",
"\"GOPATH\"",
"\"PULUMI_LOCAL_NUGET\""
] |
[] |
[
"PULUMI_ACCESS_TOKEN",
"PULUMI_FAILED_TESTS_DIR",
"PULUMI_TEST_DEBUG_UPDATES",
"PULUMI_API",
"PULUMI_LOCAL_NUGET",
"PULUMI_TEST_OWNER",
"GOPATH",
"PULUMI_TEST_DEBUG_LOG_LEVEL",
"PULUMI_TEST_REPORT_CONFIG",
"PULUMI_TEST_TRACE_ENDPOINT"
] |
[]
|
["PULUMI_ACCESS_TOKEN", "PULUMI_FAILED_TESTS_DIR", "PULUMI_TEST_DEBUG_UPDATES", "PULUMI_API", "PULUMI_LOCAL_NUGET", "PULUMI_TEST_OWNER", "GOPATH", "PULUMI_TEST_DEBUG_LOG_LEVEL", "PULUMI_TEST_REPORT_CONFIG", "PULUMI_TEST_TRACE_ENDPOINT"]
|
go
| 10 | 0 | |
Solutions/src/main/java/com/anuragbhandari/hackerrank/RepeatedString.java
|
package com.anuragbhandari.hackerrank;
import java.io.*;
import java.util.*;
public class RepeatedString {
private static final Scanner scanner = new Scanner(System.in);
/**
* Returns the number of occurrences of 'a' in the first n characters of
* infinitely repeated string s.
* @param s The string to be infinitely repeated.
* @param n Number of characters to pick from the beginning of s.
* @return Total occurrences of 'a' in the repeated string.
*/
static long getAOccurrences(String s, long n) {
// Initialize the result variable
long aOccurrencesInRepeatedS = 0;
// Calculate occurrences of 'a' in s
int aOccurrencesInS = 0;
char[] sArray = s.toCharArray();
for (char c : sArray) {
if (c == 'a') {
aOccurrencesInS += 1;
}
}
// Calculate approximate a occurrences in first n chars of repeated string
long numSRepetitionsInN = n / s.length();
aOccurrencesInRepeatedS += numSRepetitionsInN * aOccurrencesInS;
// Calculate exact occurrences in first n chars of repeated string
long numSRemainderCharsInN = n % s.length();
int aOccurrencesInRemainderS = 0;
for (int i=0; i < numSRemainderCharsInN; i++) {
if (sArray[i] == 'a') {
aOccurrencesInRemainderS += 1;
}
}
aOccurrencesInRepeatedS += aOccurrencesInRemainderS;
return aOccurrencesInRepeatedS;
}
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = scanner.nextLine();
long n = scanner.nextLong();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
long result = getAOccurrences(s, n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
[
"\"OUTPUT_PATH\""
] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
java
| 1 | 0 | |
credscontroller/vendor/github.com/hashicorp/vault/plugins/database/mssql/mssql_test.go
|
package mssql
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/hashicorp/vault/sdk/database/dbplugin"
)
func TestMSSQL_Initialize(t *testing.T) {
if os.Getenv("MSSQL_URL") == "" || os.Getenv("VAULT_ACC") != "1" {
t.SkipNow()
}
connURL := os.Getenv("MSSQL_URL")
connectionDetails := map[string]interface{}{
"connection_url": connURL,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
if !db.Initialized {
t.Fatal("Database should be initialized")
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
// Test decoding a string value for max_open_connections
connectionDetails = map[string]interface{}{
"connection_url": connURL,
"max_open_connections": "5",
}
_, err = db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMSSQL_CreateUser(t *testing.T) {
if os.Getenv("MSSQL_URL") == "" || os.Getenv("VAULT_ACC") != "1" {
t.SkipNow()
}
connURL := os.Getenv("MSSQL_URL")
connectionDetails := map[string]interface{}{
"connection_url": connURL,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
// Test with no configured Creation Statement
_, _, err = db.CreateUser(context.Background(), dbplugin.Statements{}, usernameConfig, time.Now().Add(time.Minute))
if err == nil {
t.Fatal("Expected error when no creation statement is provided")
}
statements := dbplugin.Statements{
Creation: []string{testMSSQLRole},
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
}
func TestMSSQL_RotateRootCredentials(t *testing.T) {
if os.Getenv("MSSQL_URL") == "" || os.Getenv("VAULT_ACC") != "1" {
t.SkipNow()
}
connURL := os.Getenv("MSSQL_URL")
connectionDetails := map[string]interface{}{
"connection_url": connURL,
"username": "sa",
"password": "yourStrong(!)Password",
}
db := new()
connProducer := db.SQLConnectionProducer
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
if !connProducer.Initialized {
t.Fatal("Database should be initialized")
}
newConf, err := db.RotateRootCredentials(context.Background(), nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if newConf["password"] == "yourStrong(!)Password" {
t.Fatal("password was not updated")
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMSSQL_RevokeUser(t *testing.T) {
if os.Getenv("MSSQL_URL") == "" || os.Getenv("VAULT_ACC") != "1" {
t.SkipNow()
}
connURL := os.Getenv("MSSQL_URL")
connectionDetails := map[string]interface{}{
"connection_url": connURL,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
statements := dbplugin.Statements{
Creation: []string{testMSSQLRole},
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(2*time.Second))
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Test default revoke statements
err = db.RevokeUser(context.Background(), statements, username)
if err != nil {
t.Fatalf("err: %s", err)
}
if err := testCredsExist(t, connURL, username, password); err == nil {
t.Fatal("Credentials were not revoked")
}
username, password, err = db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(2*time.Second))
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Test custom revoke statement
statements.Revocation = []string{testMSSQLDrop}
err = db.RevokeUser(context.Background(), statements, username)
if err != nil {
t.Fatalf("err: %s", err)
}
if err := testCredsExist(t, connURL, username, password); err == nil {
t.Fatal("Credentials were not revoked")
}
}
func testCredsExist(t testing.TB, connURL, username, password string) error {
// Log in with the new creds
parts := strings.Split(connURL, "@")
connURL = fmt.Sprintf("sqlserver://%s:%s@%s", username, password, parts[1])
db, err := sql.Open("mssql", connURL)
if err != nil {
return err
}
defer db.Close()
return db.Ping()
}
const testMSSQLRole = `
CREATE LOGIN [{{name}}] WITH PASSWORD = '{{password}}';
CREATE USER [{{name}}] FOR LOGIN [{{name}}];
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO [{{name}}];`
const testMSSQLDrop = `
DROP USER [{{name}}];
DROP LOGIN [{{name}}];
`
|
[
"\"MSSQL_URL\"",
"\"VAULT_ACC\"",
"\"MSSQL_URL\"",
"\"MSSQL_URL\"",
"\"VAULT_ACC\"",
"\"MSSQL_URL\"",
"\"MSSQL_URL\"",
"\"VAULT_ACC\"",
"\"MSSQL_URL\"",
"\"MSSQL_URL\"",
"\"VAULT_ACC\"",
"\"MSSQL_URL\""
] |
[] |
[
"MSSQL_URL",
"VAULT_ACC"
] |
[]
|
["MSSQL_URL", "VAULT_ACC"]
|
go
| 2 | 0 | |
skyportal/tests/frontend/test_sources.py
|
import os
from os.path import join as pjoin
import uuid
from io import BytesIO
import pytest
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from PIL import Image, ImageChops
from baselayer.app.config import load_config
from skyportal.tests import api, IS_CI_BUILD
cfg = load_config()
@pytest.mark.flaky(reruns=2)
def test_public_source_page(driver, user, public_source, public_group):
driver.get(f"/become_user/{user.id}") # TODO decorator/context manager?
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
driver.wait_for_xpath(
'//label[contains(text(), "band")]', 10
) # TODO how to check plot?
driver.wait_for_xpath('//label[contains(text(), "Fe III")]')
driver.wait_for_xpath(f'//span[text()="{public_group.name}"]')
@pytest.mark.flaky(reruns=3)
def test_classifications(driver, user, taxonomy_token, public_group, public_source):
if IS_CI_BUILD:
pytest.xfail("Xfailing this test on CI builds.")
simple = {
'class': 'Cepheid',
'tags': ['giant/supergiant', 'instability strip', 'standard candle'],
'other names': ['Cep', 'CEP'],
'subclasses': [
{'class': 'Anomolous', 'other names': ['Anomolous Cepheid', 'BLBOO']},
{
'class': 'Mult-mode',
'other names': ['Double-mode Cepheid', 'Multi-mode Cepheid', 'CEP(B)'],
},
{
'class': 'Classical',
'tags': [],
'other names': [
'Population I Cepheid',
'Type I Cepheid',
'DCEP',
'Delta Cepheid',
'Classical Cepheid',
],
'subclasses': [
{
'class': 'Symmetrical',
'other names': ['DCEPS', 'Delta Cep-type Symmetrical'],
}
],
},
],
}
tax_name = str(uuid.uuid4())
tax_version = "test0.1"
status, data = api(
'POST',
'taxonomy',
data={
'name': tax_name,
'hierarchy': simple,
'group_ids': [public_group.id],
'version': tax_version,
},
token=taxonomy_token,
)
assert status == 200
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
driver.click_xpath('//div[@id="tax-select"]')
driver.click_xpath(
f'//*[text()="{tax_name} ({tax_version})"]', wait_clickable=False
)
driver.click_xpath('//*[@id="classification"]')
driver.wait_for_xpath('//*[@id="classification"]').send_keys(
"Symmetrical", Keys.ENTER
)
driver.click_xpath("//*[@id='classificationSubmitButton']")
# Notification
driver.wait_for_xpath("//*[text()='Classification saved']")
# Button at top of source page
driver.wait_for_xpath(
"//span[contains(@class, 'MuiButton-label') and text()='Symmetrical']"
)
# Scroll up to get entire classifications list component in view
add_comments = driver.find_element_by_xpath("//h6[contains(text(), 'Add comment')]")
driver.scroll_to_element(add_comments)
del_button_xpath = "//button[starts-with(@name, 'deleteClassificationButton')]"
ActionChains(driver).move_to_element(
driver.wait_for_xpath(del_button_xpath)
).perform()
driver.click_xpath(del_button_xpath, wait_clickable=False)
driver.wait_for_xpath_to_disappear("//*[contains(text(), '(P=1)')]")
driver.wait_for_xpath_to_disappear(f"//i[text()='{tax_name}']")
driver.wait_for_xpath_to_disappear(
"//span[contains(@class, 'MuiButton-label') and text()='Symmetrical']"
)
@pytest.mark.flaky(reruns=2)
def test_comments(driver, user, public_source):
if "TRAVIS" in os.environ:
pytest.xfail("Xfailing this test on Travis builds.")
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
driver.click_xpath('//*[@name="submitCommentButton"]')
try:
driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.wait_for_xpath('//span[text()="a few seconds ago"]')
except TimeoutException:
driver.refresh()
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
driver.click_xpath('//*[@name="submitCommentButton"]')
driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.wait_for_xpath('//span[text()="a few seconds ago"]')
@pytest.mark.flaky(reruns=2)
def test_comment_groups_validation(driver, user, public_source):
driver.get(f"/become_user/{user.id}") # TODO decorator/context manager?
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
driver.wait_for_xpath("//*[text()='Customize Group Access']").click()
group_checkbox_xpath = "//input[@name='group_ids[0]']"
assert driver.wait_for_xpath(group_checkbox_xpath).is_selected()
driver.click_xpath(group_checkbox_xpath, wait_clickable=False)
driver.click_xpath('//*[@name="submitCommentButton"]')
driver.wait_for_xpath('//div[contains(.,"Select at least one group")]')
driver.click_xpath(group_checkbox_xpath, wait_clickable=False)
driver.wait_for_xpath_to_disappear('//div[contains(.,"Select at least one group")]')
driver.click_xpath('//*[@name="submitCommentButton"]')
try:
driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.wait_for_xpath('//span[text()="a few seconds ago"]')
except TimeoutException:
driver.refresh()
driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.wait_for_xpath('//span[text()="a few seconds ago"]')
@pytest.mark.flaky(reruns=2)
def test_upload_download_comment_attachment(driver, user, public_source):
if "TRAVIS" in os.environ:
pytest.xfail("Xfailing this test on Travis builds.")
driver.get(f"/become_user/{user.id}") # TODO decorator/context manager?
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
attachment_file = driver.find_element_by_css_selector('input[type=file]')
attachment_file.send_keys(
pjoin(os.path.dirname(os.path.dirname(__file__)), 'data', 'spec.csv')
)
driver.click_xpath('//*[@name="submitCommentButton"]')
try:
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
comment_div = comment_text_div.find_element_by_xpath("..")
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
driver.click_xpath('//a[text()="spec.csv"]')
fpath = str(os.path.abspath(pjoin(cfg['paths.downloads_folder'], 'spec.csv')))
try_count = 1
while not os.path.exists(fpath) and try_count <= 3:
try_count += 1
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
driver.click_xpath('//a[text()="spec.csv"]')
if os.path.exists(fpath):
break
else:
assert os.path.exists(fpath)
try:
with open(fpath) as f:
lines = f.read()
assert lines.split('\n')[0] == 'wavelengths,fluxes,instrument_id'
finally:
os.remove(fpath)
def test_view_only_user_cannot_comment(driver, view_only_user, public_source):
driver.get(f"/become_user/{view_only_user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
driver.wait_for_xpath_to_disappear('//input[@name="text"]')
@pytest.mark.flaky(reruns=2)
def test_delete_comment(driver, user, public_source):
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
driver.click_xpath('//*[@name="submitCommentButton"]')
try:
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
comment_div = comment_text_div.find_element_by_xpath("..")
comment_id = comment_div.get_attribute("name").split("commentDiv")[-1]
delete_button = comment_div.find_element_by_xpath(
f"//*[@name='deleteCommentButton{comment_id}']"
)
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
driver.execute_script("arguments[0].click();", delete_button)
try:
driver.wait_for_xpath_to_disappear(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
try:
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
except TimeoutException:
return
else:
comment_div = comment_text_div.find_element_by_xpath("..")
comment_id = comment_div.get_attribute("name").split("commentDiv")[-1]
delete_button = comment_div.find_element_by_xpath(
f"//*[@name='deleteCommentButton{comment_id}']"
)
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
driver.execute_script("arguments[0].click();", delete_button)
driver.wait_for_xpath_to_disappear(f'//div[text()="{comment_text}"]')
@pytest.mark.flaky(reruns=2)
def test_regular_user_cannot_delete_unowned_comment(
driver, super_admin_user, user, public_source
):
driver.get(f"/become_user/{super_admin_user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
submit_button = driver.find_element_by_xpath('//*[@name="submitCommentButton"]')
submit_button.click()
try:
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
comment_div = comment_text_div.find_element_by_xpath("..")
comment_id = comment_div.get_attribute("name").split("commentDiv")[-1]
delete_button = comment_div.find_element_by_xpath(
f"//*[@name='deleteCommentButton{comment_id}']"
)
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
assert not delete_button.is_displayed()
@pytest.mark.flaky(reruns=2)
def test_super_user_can_delete_unowned_comment(
driver, super_admin_user, user, public_source
):
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
driver.wait_for_xpath(f'//div[text()="{public_source.id}"]')
comment_box = driver.wait_for_xpath("//input[@name='text']")
comment_text = str(uuid.uuid4())
comment_box.send_keys(comment_text)
driver.scroll_to_element_and_click(
driver.find_element_by_xpath('//*[@name="submitCommentButton"]')
)
try:
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
driver.get(f"/become_user/{super_admin_user.id}")
driver.get(f"/source/{public_source.id}")
driver.refresh()
comment_text_div = driver.wait_for_xpath(f'//div[text()="{comment_text}"]')
comment_div = comment_text_div.find_element_by_xpath("..")
comment_id = comment_div.get_attribute("name").split("commentDiv")[-1]
delete_button = comment_div.find_element_by_xpath(
f"//*[@name='deleteCommentButton{comment_id}']"
)
driver.execute_script("arguments[0].scrollIntoView();", comment_div)
ActionChains(driver).move_to_element(comment_div).perform()
driver.execute_script("arguments[0].click();", delete_button)
try:
driver.wait_for_xpath_to_disappear(f'//div[text()="{comment_text}"]')
except TimeoutException:
driver.refresh()
driver.wait_for_xpath_to_disappear(f'//div[text()="{comment_text}"]')
def test_show_starlist(driver, user, public_source):
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
button = driver.wait_for_xpath(f'//span[text()="Show Starlist"]')
button.click()
driver.wait_for_xpath(f"//code/div[text()[contains(., '_off1')]]", timeout=20)
@pytest.mark.flaky(reruns=2)
def test_centroid_plot(
driver, user, public_source, public_group, ztf_camera, upload_data_token
):
if "TRAVIS" in os.environ:
pytest.xfail("Xfailing this test on Travis builds.")
# Put in some actual photometry data first
status, data = api(
'POST',
'photometry',
data={
'obj_id': str(public_source.id),
'mjd': [58000.0, 58001.0, 58002.0],
'instrument_id': ztf_camera.id,
'flux': [12.24, 15.24, 12.24],
'fluxerr': [0.031, 0.029, 0.030],
'filter': ['ztfg', 'ztfg', 'ztfg'],
'zp': [25.0, 30.0, 21.2],
'magsys': ['ab', 'ab', 'ab'],
'ra': [264.19482957057863, 264.1948483167286, 264.19475131195185],
'ra_unc': 0.17,
'dec': [50.54773905413207, 50.547910537435854, 50.547856056708355],
'dec_unc': 0.2,
'group_ids': [public_group.id],
},
token=upload_data_token,
)
assert status == 200
assert data['status'] == 'success'
assert len(data['data']['ids']) == 3
driver.get(f"/become_user/{user.id}")
driver.get(f"/source/{public_source.id}")
try:
# Look for Suspense fallback to show
loading_text = "Loading centroid plot..."
driver.wait_for_xpath(f'//div[text()="{loading_text}"]')
driver.wait_for_xpath_to_disappear(f'//div[text()="{loading_text}"]')
except TimeoutException:
# The plot may have loaded too quickly to catch the Suspense div
driver.wait_for_xpath_to_disappear(f'//div[text()="{loading_text}"]')
finally:
component_class_xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' centroid-plot-div ')]"
vegaplot_div = driver.wait_for_xpath(component_class_xpath)
assert vegaplot_div.is_displayed()
# Since Vega uses a <canvas> element, we can't examine individual
# components of the plot through the DOM, so just compare an image of
# the plot to the saved baseline
generated_plot_data = vegaplot_div.screenshot_as_png
generated_plot = Image.open(BytesIO(generated_plot_data))
expected_plot_path = os.path.abspath(
"skyportal/tests/data/centroid_plot_expected.png"
)
# Use this commented line to save a new version of the expected plot
# if changes have been made to the component:
# generated_plot.save(expected_plot_path)
if not os.path.exists(expected_plot_path):
pytest.fail("Missing centroid plot baseline image for comparison")
expected_plot = Image.open(expected_plot_path)
difference = ImageChops.difference(generated_plot, expected_plot)
assert difference.getbbox() is None
def test_dropdown_facility_change(driver, user, public_source):
driver.get(f"/become_user/{user.id}") # TODO decorator/context manager?
driver.get(f"/source/{public_source.id}")
driver.scroll_to_element_and_click(
driver.wait_for_xpath('//span[text()="Show Starlist"]')
)
driver.wait_for_xpath("//code/div[text()[contains(., 'raoffset')]]", timeout=20)
xpath = '//*[@id="mui-component-select-StarListSelectElement"]'
element = driver.wait_for_xpath(xpath)
ActionChains(driver).move_to_element(element).click_and_hold().perform()
xpath = '//li[@data-value="P200"]'
element = driver.wait_for_xpath(xpath)
ActionChains(driver).move_to_element(element).click_and_hold().perform()
driver.wait_for_xpath("//code/div[text()[contains(., 'dist')]]", timeout=20)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
agent/config/config_windows.go
|
// +build windows
// Copyright 2014-2017 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.
package config
import (
"os"
"path/filepath"
"time"
"github.com/aws/amazon-ecs-agent/agent/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/utils"
)
const (
// AgentCredentialsAddress is used to serve the credentials for tasks.
AgentCredentialsAddress = "127.0.0.1"
// defaultAuditLogFile specifies the default audit log filename
defaultCredentialsAuditLogFile = `log\audit.log`
// When using IAM roles for tasks on Windows, the credential proxy consumes port 80
httpPort = 80
// Remote Desktop / Terminal Services
rdpPort = 3389
// RPC client
rpcPort = 135
// Server Message Block (SMB) over TCP
smbPort = 445
// HTTP port for Windows Remote Management (WinRM) listener
winRMPortHTTP = 5985
// HTTPS port for Windows Remote Management (WinRM) listener
winRMPortHTTPS = 5986
// DNS client
dnsPort = 53
// NetBIOS over TCP/IP
netBIOSPort = 139
// defaultContainerStartTimeout specifies the value for container start timeout duration
defaultContainerStartTimeout = 8 * time.Minute
// minimumContainerStartTimeout specifies the minimum value for starting a container
minimumContainerStartTimeout = 2 * time.Minute
)
// DefaultConfig returns the default configuration for Windows
func DefaultConfig() Config {
programData := utils.DefaultIfBlank(os.Getenv("ProgramData"), `C:\ProgramData`)
ecsRoot := filepath.Join(programData, "Amazon", "ECS")
dataDir := filepath.Join(ecsRoot, "data")
platformVariables := PlatformVariables{
CPUUnbounded: false,
}
return Config{
DockerEndpoint: "npipe:////./pipe/docker_engine",
ReservedPorts: []uint16{
DockerReservedPort,
DockerReservedSSLPort,
AgentIntrospectionPort,
AgentCredentialsPort,
rdpPort,
rpcPort,
smbPort,
winRMPortHTTP,
winRMPortHTTPS,
dnsPort,
netBIOSPort,
},
ReservedPortsUDP: []uint16{},
DataDir: dataDir,
// DataDirOnHost is identical to DataDir for Windows because we do not
// run as a container
DataDirOnHost: dataDir,
ReservedMemory: 0,
AvailableLoggingDrivers: []dockerclient.LoggingDriver{dockerclient.JSONFileDriver, dockerclient.NoneDriver, dockerclient.AWSLogsDriver},
TaskCleanupWaitDuration: DefaultTaskCleanupWaitDuration,
DockerStopTimeout: defaultDockerStopTimeout,
ContainerStartTimeout: defaultContainerStartTimeout,
CredentialsAuditLogFile: filepath.Join(ecsRoot, defaultCredentialsAuditLogFile),
CredentialsAuditLogDisabled: false,
ImageCleanupDisabled: false,
MinimumImageDeletionAge: DefaultImageDeletionAge,
ImageCleanupInterval: DefaultImageCleanupTimeInterval,
NumImagesToDeletePerCycle: DefaultNumImagesToDeletePerCycle,
ContainerMetadataEnabled: false,
TaskCPUMemLimit: ExplicitlyDisabled,
PlatformVariables: platformVariables,
TaskMetadataSteadyStateRate: DefaultTaskMetadataSteadyStateRate,
TaskMetadataBurstRate: DefaultTaskMetadataBurstRate,
SharedVolumeMatchFullConfig: false, //only requiring shared volumes to match on name, which is default docker behavior
}
}
func (cfg *Config) platformOverrides() {
// Enabling task IAM roles for Windows requires the credential proxy to run on port 80,
// so we reserve this port by default when that happens.
if cfg.TaskIAMRoleEnabled {
if cfg.ReservedPorts == nil {
cfg.ReservedPorts = []uint16{}
}
cfg.ReservedPorts = append(cfg.ReservedPorts, httpPort)
}
// ensure TaskResourceLimit is disabled
cfg.TaskCPUMemLimit = ExplicitlyDisabled
cpuUnbounded := utils.ParseBool(os.Getenv("ECS_ENABLE_CPU_UNBOUNDED_WINDOWS_WORKAROUND"), false)
platformVariables := PlatformVariables{
CPUUnbounded: cpuUnbounded,
}
cfg.PlatformVariables = platformVariables
}
// platformString returns platform-specific config data that can be serialized
// to string for debugging
func (cfg *Config) platformString() string {
return ""
}
|
[
"\"ProgramData\"",
"\"ECS_ENABLE_CPU_UNBOUNDED_WINDOWS_WORKAROUND\""
] |
[] |
[
"ProgramData",
"ECS_ENABLE_CPU_UNBOUNDED_WINDOWS_WORKAROUND"
] |
[]
|
["ProgramData", "ECS_ENABLE_CPU_UNBOUNDED_WINDOWS_WORKAROUND"]
|
go
| 2 | 0 | |
Profile_Rest_Api/asgi.py
|
"""
ASGI config for Profile_Rest_Api 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', 'Profile_Rest_Api.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
jira/examples/issue-type-scheme/gets/gets.go
|
package main
import (
"context"
"github.com/ctreminiom/go-atlassian/jira"
"log"
"os"
)
func main() {
var (
host = os.Getenv("HOST")
mail = os.Getenv("MAIL")
token = os.Getenv("TOKEN")
)
atlassian, err := jira.New(nil, host)
if err != nil {
log.Fatal(err)
}
atlassian.Auth.SetBasicAuth(mail, token)
issueTypeSchemes, response, err := atlassian.Issue.Type.Scheme.Gets(context.Background(), nil, 0, 50)
if err != nil {
log.Fatal(err)
}
log.Println("HTTP Endpoint Used", response.Endpoint)
for _, issueTypeScheme := range issueTypeSchemes.Values {
log.Println(issueTypeScheme)
}
}
|
[
"\"HOST\"",
"\"MAIL\"",
"\"TOKEN\""
] |
[] |
[
"MAIL",
"HOST",
"TOKEN"
] |
[]
|
["MAIL", "HOST", "TOKEN"]
|
go
| 3 | 0 | |
admin/admin/wsgi.py
|
"""
WSGI config for admin 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
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv(usecwd=True))
api_key = os.getenv("mqKey")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'admin.settings')
application = get_wsgi_application()
|
[] |
[] |
[
"mqKey"
] |
[]
|
["mqKey"]
|
python
| 1 | 0 | |
config.py
|
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY')
|
[] |
[] |
[
"SECRET_KEY"
] |
[]
|
["SECRET_KEY"]
|
python
| 1 | 0 | |
main.go
|
package main
import (
"encoding/base64"
"fmt"
"net/http"
"os"
"strings"
"time"
"k8s.io/client-go/util/cert"
"github.com/MagalixCorp/magalix-agent/v2/client"
"github.com/MagalixCorp/magalix-agent/v2/entities"
"github.com/MagalixCorp/magalix-agent/v2/executor"
"github.com/MagalixCorp/magalix-agent/v2/kuber"
"github.com/MagalixCorp/magalix-agent/v2/metrics"
"github.com/MagalixCorp/magalix-agent/v2/proto"
"github.com/MagalixCorp/magalix-agent/v2/scanner"
"github.com/MagalixCorp/magalix-agent/v2/utils"
"github.com/MagalixTechnologies/log-go"
"github.com/MagalixTechnologies/uuid-go"
"github.com/docopt/docopt-go"
"github.com/reconquest/karma-go"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
var usage = `agent - magalix services agent.
Usage:
agent -h | --help
agent [options] (--kube-url= | --kube-incluster) [--skip-namespace=]... [--source=]...
Options:
--gateway <address> Connect to specified Magalix Kubernetes Agent gateway.
[default: wss://gateway.agent.magalix.cloud]
--account-id <identifier> Your account ID in Magalix.
[default: $ACCOUNT_ID]
--cluster-id <identifier> Your cluster ID in Magalix.
[default: $CLUSTER_ID]
--client-secret <secret> Unique and secret client token.
[default: $SECRET]
--kube-url <url> Use specified URL and token for access to kubernetes
cluster.
--kube-insecure Insecure skip SSL verify.
--kube-root-ca-cert <filepath> Filepath to root CA cert.
--kube-token <token> Use specified token for access to kubernetes cluster.
--kube-incluster Automatically determine kubernetes clientset
configuration. Works only if program is
running inside kubernetes cluster.
--kube-timeout <duration> Timeout of requests to kubernetes apis.
[default: 30s]
--skip-namespace <pattern> Skip namespace matching a pattern (e.g. system-*),
can be specified multiple times.
--source <source> Specify source for metrics instead of
automatically detected.
Supported sources are:
* kubelet;
--kubelet-port <port> Override kubelet port for
automatically discovered nodes.
[default: 10255]
--kubelet-backoff-sleep <duration> Timeout of backoff policy.
Timeout will be multiplied from 1 to 10.
[default: 300ms]
--kubelet-backoff-max-retries <retries> Max retries of backoff policy, then consider failed.
[default: 5]
--metrics-interval <duration> Metrics request and send interval.
[default: 1m]
--events-buffer-flush-interval <duration> Events batch writer flush interval.
[default: 10s]
--events-buffer-size <size> Events batch writer buffer size.
[default: 20]
--executor-workers <number> Executor concurrent workers count
[default: 5]
--timeout-proto-handshake <duration> Timeout to do a websocket handshake.
[default: 10s]
--timeout-proto-write <duration> Timeout to write a message to websocket channel.
[default: 60s]
--timeout-proto-read <duration> Timeout to read a message from websocket channel.
[default: 60s]
--timeout-proto-reconnect <duration> Timeout between reconnecting retries.
[default: 1s]
--timeout-proto-backoff <duration> Timeout of backoff policy.
Timeout will be multiplied from 1 to 10.
[default: 300ms]
--opt-in-analysis-data Send anonymous data for analysis.
--analysis-data-interval <duration> Analysis data send interval.
[default: 5m]
--packets-v2 Enable v2 packets (without ids). This is deprecated and kept for backward compatability.
--disable-metrics Disable metrics collecting and sending.
--disable-events Disable events collecting and sending.
--disable-scalar Disable in-agent scalar.
--port <port> Port to start the server on for liveness and readiness probes
[default: 80]
--dry-run Disable decision execution.
--no-send-logs Disable sending logs to the backend.
--debug Enable debug messages.
--trace Enable debug and trace messages.
--trace-log <path> Write log messages to specified file
[default: trace.log]
-h --help Show this help.
--version Show version.
`
var version = "[manual build]"
var startID string
const (
entitiesSyncTimeout = time.Minute
)
func getVersion() string {
return strings.Join([]string{
"magalix agent " + version,
"protocol/major: " + fmt.Sprint(client.ProtocolMajorVersion),
"protocol/minor: " + fmt.Sprint(client.ProtocolMinorVersion),
}, "\n")
}
func main() {
startID = uuid.NewV4().String()
args, err := docopt.ParseArgs(usage, nil, getVersion())
if err != nil {
panic(err)
}
logger := log.New(
args["--debug"].(bool),
args["--trace"].(bool),
args["--trace-log"].(string),
)
// we need to disable default exit 1 for FATAL messages because we also
// need to send fatal messages on the remote server and send bye packet
// after fatal message (if we can), therefore all exits will be controlled
// manually
logger.SetExiter(func(int) {})
utils.SetLogger(logger)
logger.Infof(
karma.Describe("version", version).
Describe("args", fmt.Sprintf("%q", utils.GetSanitizedArgs())),
"magalix agent started.....",
)
secret, err := base64.StdEncoding.DecodeString(
utils.ExpandEnv(args, "--client-secret", false),
)
if err != nil {
logger.Fatalf(
err,
"unable to decode base64 secret specified as --client-secret flag",
)
os.Exit(1)
}
// TODO: remove
// a hack to set default timeout for all http requests
http.DefaultClient = &http.Client{
Timeout: 20 * time.Second,
}
var (
accountID = utils.ExpandEnvUUID(args, "--account-id")
clusterID = utils.ExpandEnvUUID(args, "--cluster-id")
)
port := args["--port"].(string)
probes := NewProbesServer(":"+port, logger)
go func() {
err = probes.Start()
if err != nil {
logger.Fatalf(err, "unable to start probes server")
os.Exit(1)
}
}()
kRestConfig, err := getKRestConfig(logger, args)
kube, err := kuber.InitKubernetes(kRestConfig, logger)
if err != nil {
logger.Fatalf(err, "unable to initialize Kubernetes")
os.Exit(1)
}
k8sServerVersion, err := kube.GetServerVersion()
if err != nil {
logger.Warningf(err, "failed to discover server version")
}
connected := make(chan bool)
gwClient, err := client.InitClient(
args, version, startID, accountID, clusterID, secret, k8sServerVersion, logger, connected,
)
defer gwClient.WaitExit()
defer gwClient.Recover()
if err != nil {
logger.Fatalf(err, "unable to connect to gateway")
os.Exit(1)
}
logger.Infof(nil, "Waiting for connection and authorization")
<-connected
logger.Infof(nil, "Connected and authorized")
probes.Authorized = true
initAgent(args, gwClient, kRestConfig, kube, logger, accountID, clusterID)
}
func initAgent(
args docopt.Opts,
gwClient *client.Client,
kRestConfig *rest.Config,
kube *kuber.Kube,
logger *log.Logger,
accountID uuid.UUID,
clusterID uuid.UUID,
) {
logger.Infof(nil, "Initializing Agent")
var (
metricsEnabled = !args["--disable-metrics"].(bool)
// eventsEnabled = !args["--disable-events"].(bool)
//scalarEnabled = !args["--disable-scalar"].(bool)
executorWorkers = utils.MustParseInt(args, "--executor-workers")
dryRun = args["--dry-run"].(bool)
skipNamespaces []string
)
if namespaces, ok := args["--skip-namespace"].([]string); ok {
skipNamespaces = namespaces
}
dynamicClient, err := dynamic.NewForConfig(kRestConfig)
parentsStore := kuber.NewParentsStore()
observer := kuber.NewObserver(
logger,
dynamicClient,
parentsStore,
make(chan struct{}, 0),
time.Minute*5,
)
t := entitiesSyncTimeout
err = observer.WaitForCacheSync(&t)
if err != nil {
logger.Fatalf(err, "unable to start entities watcher")
}
optInAnalysisData := args["--opt-in-analysis-data"].(bool)
analysisDataInterval := utils.MustParseDuration(
args,
"--analysis-data-interval",
)
ew := entities.NewEntitiesWatcher(logger, observer, gwClient)
err = ew.Start()
if err != nil {
logger.Fatalf(err, "unable to start entities watcher")
}
/*if scalarEnabled {
scalar2.InitScalars(logger, kube, observer, dryRun)
}*/
entityScanner := scanner.InitScanner(
gwClient,
scanner.NewKuberFromObserver(ew),
skipNamespaces,
accountID,
clusterID,
optInAnalysisData,
analysisDataInterval,
)
e := executor.InitExecutor(
gwClient,
kube,
entityScanner,
executorWorkers,
dryRun,
)
gwClient.AddListener(proto.PacketKindDecision, e.Listener)
gwClient.AddListener(proto.PacketKindRestart, func(in []byte) (out []byte, err error) {
var restart proto.PacketRestart
if err = proto.DecodeSnappy(in, &restart); err != nil {
return
}
defer gwClient.Done(restart.Status, true)
return nil, nil
})
// @TODO reallow events when we start using them
/* if eventsEnabled {
events.InitEvents(
gwClient,
kube,
skipNamespaces,
entityScanner,
args,
)
} */
if metricsEnabled {
var nodesProvider metrics.NodesProvider
var entitiesProvider metrics.EntitiesProvider
nodesProvider = observer
entitiesProvider = observer
err := metrics.InitMetrics(
gwClient,
nodesProvider,
entitiesProvider,
kube,
optInAnalysisData,
args,
)
if err != nil {
gwClient.Fatalf(err, "unable to initialize metrics sources")
os.Exit(1)
}
}
}
func getKRestConfig(
logger *log.Logger,
args map[string]interface{},
) (config *rest.Config, err error) {
if args["--kube-incluster"].(bool) {
logger.Infof(nil, "initializing kubernetes incluster config")
config, err = rest.InClusterConfig()
if err != nil {
return nil, karma.Format(
err,
"unable to get incluster config",
)
}
} else {
logger.Infof(
nil,
"initializing kubernetes user-defined config",
)
token, _ := args["--kube-token"].(string)
if token == "" {
token = os.Getenv("KUBE_TOKEN")
}
config = &rest.Config{}
config.ContentType = runtime.ContentTypeJSON
config.APIPath = "/api"
config.Host = args["--kube-url"].(string)
config.BearerToken = token
{
tlsClientConfig := rest.TLSClientConfig{}
rootCAFile, ok := args["--kube-root-ca-cert"].(string)
if ok {
if _, err := cert.NewPool(rootCAFile); err != nil {
fmt.Printf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
} else {
tlsClientConfig.CAFile = rootCAFile
}
config.TLSClientConfig = tlsClientConfig
}
}
if args["--kube-insecure"].(bool) {
config.Insecure = true
}
}
config.Timeout = utils.MustParseDuration(args, "--kube-timeout")
return
}
|
[
"\"KUBE_TOKEN\""
] |
[] |
[
"KUBE_TOKEN"
] |
[]
|
["KUBE_TOKEN"]
|
go
| 1 | 0 | |
cmd/abapAddonAssemblyKitCheckCVs_generated.go
|
// Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/SAP/jenkins-library/pkg/validation"
"github.com/spf13/cobra"
)
type abapAddonAssemblyKitCheckCVsOptions struct {
AbapAddonAssemblyKitEndpoint string `json:"abapAddonAssemblyKitEndpoint,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
AddonDescriptorFileName string `json:"addonDescriptorFileName,omitempty"`
AddonDescriptor string `json:"addonDescriptor,omitempty"`
}
type abapAddonAssemblyKitCheckCVsCommonPipelineEnvironment struct {
abap struct {
addonDescriptor string
}
}
func (p *abapAddonAssemblyKitCheckCVsCommonPipelineEnvironment) persist(path, resourceName string) {
content := []struct {
category string
name string
value interface{}
}{
{category: "abap", name: "addonDescriptor", value: p.abap.addonDescriptor},
}
errCount := 0
for _, param := range content {
err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(param.category, param.name), param.value)
if err != nil {
log.Entry().WithError(err).Error("Error persisting piper environment.")
errCount++
}
}
if errCount > 0 {
log.Entry().Error("failed to persist Piper environment")
}
}
// AbapAddonAssemblyKitCheckCVsCommand This step checks the validity of ABAP Software Component Versions.
func AbapAddonAssemblyKitCheckCVsCommand() *cobra.Command {
const STEP_NAME = "abapAddonAssemblyKitCheckCVs"
metadata := abapAddonAssemblyKitCheckCVsMetadata()
var stepConfig abapAddonAssemblyKitCheckCVsOptions
var startTime time.Time
var commonPipelineEnvironment abapAddonAssemblyKitCheckCVsCommonPipelineEnvironment
var logCollector *log.CollectorHook
var splunkClient *splunk.Splunk
telemetryClient := &telemetry.Telemetry{}
var createAbapAddonAssemblyKitCheckCVsCmd = &cobra.Command{
Use: STEP_NAME,
Short: "This step checks the validity of ABAP Software Component Versions.",
Long: `This steps takes the list of ABAP Software Component Versions(repositories) from the addonDescriptor configuration file specified via addonDescriptorFileName (e.g. addon.yml) and checks by calling AAKaaS whether they exist or are a valid successor of an existing Software Component Version.
It resolves the dotted version string into version, support package level and patch level and writes it to the addonDescriptor structure in the Piper commonPipelineEnvironment for usage of subsequent pipeline steps.
<br />
For Terminology refer to the [Scenario Description](https://www.project-piper.io/scenarios/abapEnvironmentAddons/).`,
PreRunE: func(cmd *cobra.Command, _ []string) error {
startTime = time.Now()
log.SetStepName(STEP_NAME)
log.SetVerbose(GeneralConfig.Verbose)
GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
path, _ := os.Getwd()
fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
log.RegisterHook(fatalHook)
err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
if err != nil {
log.SetErrorCategory(log.ErrorConfiguration)
return err
}
log.RegisterSecret(stepConfig.Username)
log.RegisterSecret(stepConfig.Password)
if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
log.RegisterHook(&sentryHook)
}
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
splunkClient = &splunk.Splunk{}
logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
log.RegisterHook(logCollector)
}
validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
if err != nil {
return err
}
if err = validation.ValidateStruct(stepConfig); err != nil {
log.SetErrorCategory(log.ErrorConfiguration)
return err
}
return nil
},
Run: func(_ *cobra.Command, _ []string) {
stepTelemetryData := telemetry.CustomData{}
stepTelemetryData.ErrorCode = "1"
handler := func() {
commonPipelineEnvironment.persist(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
config.RemoveVaultSecretFiles()
stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
stepTelemetryData.PiperCommitHash = GitCommit
telemetryClient.SetData(&stepTelemetryData)
telemetryClient.Send()
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
splunkClient.Send(telemetryClient.GetData(), logCollector)
}
}
log.DeferExitHandler(handler)
defer handler()
telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
splunkClient.Initialize(GeneralConfig.CorrelationID,
GeneralConfig.HookConfig.SplunkConfig.Dsn,
GeneralConfig.HookConfig.SplunkConfig.Token,
GeneralConfig.HookConfig.SplunkConfig.Index,
GeneralConfig.HookConfig.SplunkConfig.SendLogs)
}
abapAddonAssemblyKitCheckCVs(stepConfig, &stepTelemetryData, &commonPipelineEnvironment)
stepTelemetryData.ErrorCode = "0"
log.Entry().Info("SUCCESS")
},
}
addAbapAddonAssemblyKitCheckCVsFlags(createAbapAddonAssemblyKitCheckCVsCmd, &stepConfig)
return createAbapAddonAssemblyKitCheckCVsCmd
}
func addAbapAddonAssemblyKitCheckCVsFlags(cmd *cobra.Command, stepConfig *abapAddonAssemblyKitCheckCVsOptions) {
cmd.Flags().StringVar(&stepConfig.AbapAddonAssemblyKitEndpoint, "abapAddonAssemblyKitEndpoint", `https://apps.support.sap.com`, "Base URL to the Addon Assembly Kit as a Service (AAKaaS) system")
cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "User for the Addon Assembly Kit as a Service (AAKaaS) system")
cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password for the Addon Assembly Kit as a Service (AAKaaS) system")
cmd.Flags().StringVar(&stepConfig.AddonDescriptorFileName, "addonDescriptorFileName", `addon.yml`, "File name of the YAML file which describes the Product Version and corresponding Software Component Versions")
cmd.Flags().StringVar(&stepConfig.AddonDescriptor, "addonDescriptor", os.Getenv("PIPER_addonDescriptor"), "Structure in the commonPipelineEnvironment containing information about the Product Version and corresponding Software Component Versions")
cmd.MarkFlagRequired("abapAddonAssemblyKitEndpoint")
cmd.MarkFlagRequired("username")
cmd.MarkFlagRequired("password")
cmd.MarkFlagRequired("addonDescriptorFileName")
}
// retrieve step metadata
func abapAddonAssemblyKitCheckCVsMetadata() config.StepData {
var theMetaData = config.StepData{
Metadata: config.StepMetadata{
Name: "abapAddonAssemblyKitCheckCVs",
Aliases: []config.Alias{},
Description: "This step checks the validity of ABAP Software Component Versions.",
},
Spec: config.StepSpec{
Inputs: config.StepInputs{
Secrets: []config.StepSecrets{
{Name: "abapAddonAssemblyKitCredentialsId", Description: "CredentialsId stored in Jenkins for the Addon Assembly Kit as a Service (AAKaaS) system", Type: "jenkins"},
},
Parameters: []config.StepParameters{
{
Name: "abapAddonAssemblyKitEndpoint",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
Default: `https://apps.support.sap.com`,
},
{
Name: "username",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_username"),
},
{
Name: "password",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_password"),
},
{
Name: "addonDescriptorFileName",
ResourceRef: []config.ResourceReference{},
Scope: []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"},
Type: "string",
Mandatory: true,
Aliases: []config.Alias{},
Default: `addon.yml`,
},
{
Name: "addonDescriptor",
ResourceRef: []config.ResourceReference{
{
Name: "commonPipelineEnvironment",
Param: "abap/addonDescriptor",
},
},
Scope: []string{"PARAMETERS", "STAGES", "STEPS"},
Type: "string",
Mandatory: false,
Aliases: []config.Alias{},
Default: os.Getenv("PIPER_addonDescriptor"),
},
},
},
Outputs: config.StepOutputs{
Resources: []config.StepResources{
{
Name: "commonPipelineEnvironment",
Type: "piperEnvironment",
Parameters: []map[string]interface{}{
{"name": "abap/addonDescriptor"},
},
},
},
},
},
}
return theMetaData
}
|
[
"\"PIPER_username\"",
"\"PIPER_password\"",
"\"PIPER_addonDescriptor\"",
"\"PIPER_username\"",
"\"PIPER_password\"",
"\"PIPER_addonDescriptor\""
] |
[] |
[
"PIPER_addonDescriptor",
"PIPER_password",
"PIPER_username"
] |
[]
|
["PIPER_addonDescriptor", "PIPER_password", "PIPER_username"]
|
go
| 3 | 0 | |
etiquetarDorsal.py
|
######## Image Object Detection Using Tensorflow-trained Classifier #########
#
# Author: Evan Juras
# Date: 1/15/18
# Description:
# This program uses a TensorFlow-trained classifier to perform object detection.
# It loads the classifier uses it to perform object detection on an image.
# It draws boxes and scores around the objects of interest in the image.
## Some of the code is copied from Google's example at
## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
## and some is copied from Dat Tran's example at
## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py
## but I changed it to make it more understandable to me.
# Import packages
import os
import cv2
import numpy as np
import tensorflow as tf
import sys
os.environ['KMP_DUPLICATE_LIB_OK']='True'
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
sys.path.append("/Users/Lasser/Downloads/Final/")
sys.path.append("/Users/Lasser/Downloads/Final/models2/research")
# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util
# Name of the directory containing the object detection module we're using
MODEL_NAME = 'inference_graph'
IMAGE_NAME = 'test2.jpg'
# Grab path to current working directory
CWD_PATH = os.getcwd()
# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')
# Path to image
PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)
# Number of classes the object detector can identify
NUM_CLASSES = 1
# Load the label map.
# Label maps map indices to category names, so that when our convolution
# network predicts `5`, we know that this corresponds to `king`.
# Here we use internal utility functions, but anything that returns a
# dictionary mapping integers to appropriate string labels would be fine
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
sess = tf.Session(graph=detection_graph)
# Define input and output tensors (i.e. data) for the object detection classifier
# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Output tensors are the detection boxes, scores, and classes
# Each box represents a part of the image where a particular object was detected
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represents level of confidence for each of the objects.
# The score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Load image using OpenCV and
# expand image dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
for _img in ['test2.jpg','test2.jpg']:
PATH_TO_IMAGE = os.path.join(CWD_PATH, _img)
image = cv2.imread(PATH_TO_IMAGE)
image_expanded = np.expand_dims(image, axis=0)
# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_expanded})
# Draw the results of the detection (aka 'visulaize the results')
#print (boxes.shape, scores.shape, classes.shape, num.shape, boxes.shape, boxes.size, num, num_detections)
#print (detection_boxes, detection_scores)
# _img = vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=2, min_score_thresh=0.80)
# All the results have been drawn on image. Now display the image.
#cv2.imshow('Object detector', image)
# Press any key to close the image
#cv2.waitKey(0)
np.squeeze(boxes)
np.squeeze(classes).astype(np.int32)
np.squeeze(scores)
max_boxes_to_draw=20
min_score_thresh=.80
box = tuple(boxes[0].tolist())
box_to_filter = scores[0] > min_score_thresh
#box_to_filter[6]=True
boxes_to_show = (np.array(box)[np.array(box_to_filter)])
box_to_instance_masks_map = ['1','2','3','4','5','6','7']
box_to_display_str_map=['1','2','3','4','5','6','7']
color = 'blue'
for i in boxes_to_show:
print (i)
ymin, xmin, ymax, xmax = i
vis_util.draw_bounding_box_on_image_array(
image,
ymin,
xmin,
ymax,
xmax,
color=color,
thickness=3,
display_str_list=box_to_display_str_map[1],
use_normalized_coordinates=True)
# All the results have been drawn on image. Now display the image.
cv2.imshow('Object detector', image)
# Press any key to close the image
cv2.waitKey(0)
# Clean up
cv2.destroyAllWindows()
|
[] |
[] |
[
"KMP_DUPLICATE_LIB_OK"
] |
[]
|
["KMP_DUPLICATE_LIB_OK"]
|
python
| 1 | 0 | |
auth/auth.go
|
package auth
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/go-chi/jwtauth"
)
type contextKey string
// ContextKey for public key
var (
ContextKey = contextKey("key")
ContextHost = contextKey("host")
defaultHost = "localhost:5005"
)
// Verifier ...
func Verifier(ja *jwtauth.JWTAuth) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return jwtauth.Verify(ja, jwtauth.TokenFromQuery, jwtauth.TokenFromHeader, jwtauth.TokenFromCookie)(next)
}
}
// TokenAuth is a global authenticator interface
var TokenAuth *jwtauth.JWTAuth
// ExpireInHours for jwt
func ExpireInHours(hours int) int64 {
return jwtauth.ExpireIn(time.Duration(hours) * time.Hour)
}
// Init auth
func Init() {
jwtKey := os.Getenv("JWT_KEY")
if jwtKey == "" {
log.Fatal("No JWT key")
}
TokenAuth = jwtauth.New("HS256", []byte(jwtKey), nil)
}
func getHost() string {
host := os.Getenv("HOST")
if host == "" {
host = defaultHost
}
return host
}
// PubKeyContext parses JWT fields
func PubKeyContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context())
pubKey, ok := claims["key"].(string)
fmt.Println(pubKey)
if !ok || pubKey == "" {
http.Error(w, http.StatusText(401), 401)
return
}
ctx := context.WithValue(r.Context(), ContextKey, pubKey)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// HostContext ...
func HostContext(next http.Handler) http.Handler {
host := getHost()
//fmt.Println(host)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ContextHost, host)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
|
[
"\"JWT_KEY\"",
"\"HOST\""
] |
[] |
[
"JWT_KEY",
"HOST"
] |
[]
|
["JWT_KEY", "HOST"]
|
go
| 2 | 0 | |
conf/settings.py
|
# -*- coding: utf-8 -*-
'''
Django settings for Export Readiness project.
Generated by 'django-admin startproject' using Django 1.9.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
'''
import os
from directory_constants import cms
import directory_healthcheck.backends
import environ
import healthcheck.backends
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
env = environ.Env()
for env_file in env.list('ENV_FILES', default=[]):
env.read_env(f'conf/env/{env_file}')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
SECRET_KEY = env.str('SECRET_KEY')
DEBUG = env.bool('DEBUG', False)
# As the app is running behind a host-based router supplied by Heroku or other
# PaaS, we can open ALLOWED_HOSTS
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.contenttypes', # required by DRF and auth, not using DB
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.sitemaps',
'formtools',
'directory_constants',
'directory_sso_api_client',
'core',
'content',
'casestudy',
'finance',
'directory_healthcheck',
'captcha',
'directory_components',
'euexit',
'contact',
'marketaccess',
'community',
'search',
'ukef',
'healthcheck',
'sso',
]
MIDDLEWARE = [
'directory_components.middleware.MaintenanceModeMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'directory_sso_api_client.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'directory_components.middleware.NoCacheMiddlware',
'directory_components.middleware.LocaleQuerystringMiddleware',
'directory_components.middleware.PersistLocaleMiddleware',
'directory_components.middleware.ForceDefaultLocale',
'directory_components.middleware.CountryMiddleware',
]
ROOT_URLCONF = 'conf.urls'
ROOT_URLCONF_REDIRECTS = 'conf.url_redirects'
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.template.context_processors.i18n',
'directory_components.context_processors.sso_processor',
'directory_components.context_processors.ga360',
'directory_components.context_processors.urls_processor',
'directory_components.context_processors.header_footer_processor',
'directory_components.context_processors.feature_flags',
'directory_components.context_processors.analytics',
'directory_components.context_processors.cookie_notice',
],
},
},
]
WSGI_APPLICATION = 'conf.wsgi.application'
VCAP_SERVICES = env.json('VCAP_SERVICES', {})
if 'redis' in VCAP_SERVICES:
REDIS_URL = VCAP_SERVICES['redis'][0]['credentials']['uri']
else:
REDIS_URL = env.str('REDIS_URL', '')
if REDIS_URL:
cache = {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': REDIS_URL,
'OPTIONS': {
'CLIENT_CLASS': "django_redis.client.DefaultClient",
}
}
else:
cache = {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
CACHES = {
'default': cache,
'api_fallback': cache,
'cms_fallback': cache,
}
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-gb'
# https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-LANGUAGE_COOKIE_NAME
LANGUAGE_COOKIE_DEPRECATED_NAME = 'django-language'
# Django's default value for LANGUAGE_COOKIE_DOMAIN is None
LANGUAGE_COOKIE_DOMAIN = env.str('LANGUAGE_COOKIE_DOMAIN', None)
# https://github.com/django/django/blob/master/django/conf/locale/__init__.py
LANGUAGES = [
('en-gb', 'English'), # English
('zh-hans', '简体中文'), # Simplified Chinese
('de', 'Deutsch'), # German
('ja', '日本語'), # Japanese
('es', 'Español'), # Spanish
('pt', 'Português'), # Portuguese
('ar', 'العربيّة'), # Arabic
('fr', 'Français'), # French
]
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
TIME_ZONE = 'UTC'
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
# Static files served with Whitenoise and AWS Cloudfront
# http://whitenoise.evans.io/en/stable/django.html#instructions-for-amazon-cloudfront
# http://whitenoise.evans.io/en/stable/django.html#restricting-cloudfront-to-static-files
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_HOST = env.str('STATIC_HOST', '')
STATIC_URL = STATIC_HOST + '/static/'
STATICFILES_STORAGE = env.str(
'STATICFILES_STORAGE',
'whitenoise.storage.CompressedManifestStaticFilesStorage'
)
# Logging for development
if DEBUG:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
'mohawk': {
'handlers': ['console'],
'level': 'WARNING',
'propagate': False,
},
'requests': {
'handlers': ['console'],
'level': 'WARNING',
'propagate': False,
},
'': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
}
}
# Sentry
if env.str('SENTRY_DSN', ''):
sentry_sdk.init(
dsn=env.str('SENTRY_DSN'),
environment=env.str('SENTRY_ENVIRONMENT'),
integrations=[DjangoIntegration()]
)
# directory-api
DIRECTORY_API_CLIENT_BASE_URL = env.str('API_CLIENT_BASE_URL')
DIRECTORY_API_CLIENT_API_KEY = env.str('API_SIGNATURE_SECRET')
DIRECTORY_API_CLIENT_SENDER_ID = 'directory'
DIRECTORY_API_CLIENT_DEFAULT_TIMEOUT = 15
# directory-sso-proxy
DIRECTORY_SSO_API_CLIENT_BASE_URL = env.str('SSO_API_CLIENT_BASE_URL')
DIRECTORY_SSO_API_CLIENT_API_KEY = env.str('SSO_SIGNATURE_SECRET')
DIRECTORY_SSO_API_CLIENT_SENDER_ID = 'directory'
DIRECTORY_SSO_API_CLIENT_DEFAULT_TIMEOUT = 15
LOGIN_URL = SSO_PROXY_LOGIN_URL = env.str('SSO_PROXY_LOGIN_URL')
SSO_PROXY_LOGOUT_URL = env.str('SSO_PROXY_LOGOUT_URL')
SSO_PROXY_SIGNUP_URL = env.str('SSO_PROXY_SIGNUP_URL')
SSO_PROFILE_URL = env.str('SSO_PROFILE_URL')
SSO_PROXY_REDIRECT_FIELD_NAME = env.str('SSO_PROXY_REDIRECT_FIELD_NAME')
SSO_SESSION_COOKIE = env.str('SSO_SESSION_COOKIE')
SECURE_SSL_REDIRECT = env.bool('SECURE_SSL_REDIRECT', True)
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_HSTS_SECONDS = env.int('SECURE_HSTS_SECONDS', 16070400)
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
# HEADER/FOOTER URLS
DIRECTORY_CONSTANTS_URL_GREAT_DOMESTIC = env.str('DIRECTORY_CONSTANTS_URL_GREAT_DOMESTIC', '')
DIRECTORY_CONSTANTS_URL_INTERNATIONAL = env.str('DIRECTORY_CONSTANTS_URL_INTERNATIONAL', '')
DIRECTORY_CONSTANTS_URL_EXPORT_OPPORTUNITIES = env.str('DIRECTORY_CONSTANTS_URL_EXPORT_OPPORTUNITIES', '')
DIRECTORY_CONSTANTS_URL_SELLING_ONLINE_OVERSEAS = env.str('DIRECTORY_CONSTANTS_URL_SELLING_ONLINE_OVERSEAS', '')
DIRECTORY_CONSTANTS_URL_EVENTS = env.str('DIRECTORY_CONSTANTS_URL_EVENTS', '')
DIRECTORY_CONSTANTS_URL_INVEST = env.str('DIRECTORY_CONSTANTS_URL_INVEST', '')
DIRECTORY_CONSTANTS_URL_FIND_A_SUPPLIER = env.str('DIRECTORY_CONSTANTS_URL_FIND_A_SUPPLIER', '')
DIRECTORY_CONSTANTS_URL_SINGLE_SIGN_ON = env.str('DIRECTORY_CONSTANTS_URL_SINGLE_SIGN_ON', '')
DIRECTORY_CONSTANTS_URL_FIND_A_BUYER = env.str('DIRECTORY_CONSTANTS_URL_FIND_A_BUYER', '')
DIRECTORY_CONSTANTS_URL_GREAT_MAGNA = env.str('DIRECTORY_CONSTANTS_URL_GREAT_MAGNA', 'https://great.gov.uk/')
MAGNA_HEADER = env.bool('MAGNA_HEADER', False)
PRIVACY_COOKIE_DOMAIN = os.getenv('PRIVACY_COOKIE_DOMAIN')
# Exopps url for /export-opportunities redirect
SERVICES_EXOPPS_ACTUAL = env.str('SERVICES_EXOPPS_ACTUAL', '')
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', True)
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
# Google tag manager
GOOGLE_TAG_MANAGER_ID = env.str('GOOGLE_TAG_MANAGER_ID')
GOOGLE_TAG_MANAGER_ENV = env.str('GOOGLE_TAG_MANAGER_ENV', '')
UTM_COOKIE_DOMAIN = env.str('UTM_COOKIE_DOMAIN')
GA360_BUSINESS_UNIT = 'GreatDomestic'
# security
X_FRAME_OPTIONS = 'DENY'
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
# Healthcheck
DIRECTORY_HEALTHCHECK_TOKEN = env.str('HEALTH_CHECK_TOKEN')
DIRECTORY_HEALTHCHECK_BACKENDS = [
directory_healthcheck.backends.APIBackend,
directory_healthcheck.backends.SingleSignOnBackend,
directory_healthcheck.backends.FormsAPIBackend
]
# Google captcha
RECAPTCHA_PUBLIC_KEY = env.str('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = env.str('RECAPTCHA_PRIVATE_KEY')
RECAPTCHA_REQUIRED_SCORE = env.int('RECAPTCHA_REQUIRED_SCORE', 0.5)
# NOCAPTCHA = True turns on version 2 of recaptcha
NOCAPTCHA = env.bool('NOCAPTCHA', True)
# directory CMS
DIRECTORY_CMS_API_CLIENT_BASE_URL = env.str('CMS_URL')
DIRECTORY_CMS_API_CLIENT_API_KEY = env.str('CMS_SIGNATURE_SECRET')
DIRECTORY_CMS_API_CLIENT_SENDER_ID = 'directory'
DIRECTORY_CMS_API_CLIENT_SERVICE_NAME = cms.EXPORT_READINESS
DIRECTORY_CMS_API_CLIENT_DEFAULT_TIMEOUT = 15
DIRECTORY_CMS_SITE_ID = env.str('DIRECTORY_CMS_SITE_ID', 3)
# directory clients
DIRECTORY_CLIENT_CORE_CACHE_EXPIRE_SECONDS = env.int(
'DIRECTORY_CLIENT_CORE_CACHE_EXPIRE_SECONDS',
60 * 60 * 24 * 30 # 30 days
)
# Internal Companies House search
DIRECTORY_CH_SEARCH_CLIENT_BASE_URL = env.str('INTERNAL_CH_BASE_URL', '')
DIRECTORY_CH_SEARCH_CLIENT_API_KEY = env.str('INTERNAL_CH_API_KEY', '')
DIRECTORY_CH_SEARCH_CLIENT_SENDER_ID = env.str('DIRECTORY_CH_SEARCH_CLIENT_SENDER_ID', 'directory')
DIRECTORY_CH_SEARCH_CLIENT_DEFAULT_TIMEOUT = env.str('DIRECTORY_CH_SEARCH_CLIENT_DEFAULT_TIMEOUT', 5)
# geo location
GEOIP_PATH = os.path.join(BASE_DIR, 'core/geolocation_data')
GEOIP_COUNTRY = 'GeoLite2-Country.mmdb'
MAXMIND_LICENCE_KEY = env.str('MAXMIND_LICENCE_KEY')
GEOLOCATION_MAXMIND_DATABASE_FILE_URL = env.str(
'GEOLOCATION_MAXMIND_DATABASE_FILE_URL',
'https://download.maxmind.com/app/geoip_download'
)
# feature flags
FEATURE_FLAGS = {
'PROTOTYPE_PAGES_ON': env.bool('FEATURE_PROTOTYPE_PAGES_ENABLED', False),
'EXPORTING_TO_UK_ON': env.bool('FEATURE_EXPORTING_TO_UK_ON_ENABLED', False),
'MARKET_ACCESS_ON': env.bool('FEATURE_MARKET_ACCESS_ENABLED', False),
'MARKET_ACCESS_LINK_ON': env.bool('FEATURE_MARKET_ACCESS_GOV_LINK_ENABLED', False),
'MAINTENANCE_MODE_ON': env.bool('FEATURE_MAINTENANCE_MODE_ENABLED', False), # used by directory-components
'TEST_SEARCH_API_PAGES_ON': env.bool('FEATURE_TEST_SEARCH_API_PAGES_ENABLED', False),
'CAPITAL_INVEST_CONTACT_IN_TRIAGE_ON': env.bool('FEATURE_CAPITAL_INVEST_CONTACT_IN_TRIAGE_ENABLED', False),
'EXPORT_VOUCHERS_ON': env.bool('FEATURE_EXPORT_VOUCHERS_ENABLED', False),
'INTERNATIONAL_CONTACT_TRIAGE_ON': env.bool('FEATURE_INTERNATIONAL_CONTACT_TRIAGE_ENABLED', False)
}
if FEATURE_FLAGS['TEST_SEARCH_API_PAGES_ON']:
DIRECTORY_HEALTHCHECK_BACKENDS.append(healthcheck.backends.SearchSortBackend)
# UK Export Finance
UKEF_PI_TRACKER_JAVASCRIPT_URL = env.str('UKEF_PI_TRACKER_JAVASCRIPT_URL', 'https://pi.pardot.com/pd.js')
UKEF_FORM_SUBMIT_TRACKER_URL = env.str('UKEF_FORM_SUBMIT_TRACKER_URL')
# directory forms api client
DIRECTORY_FORMS_API_BASE_URL = env.str('DIRECTORY_FORMS_API_BASE_URL')
DIRECTORY_FORMS_API_API_KEY = env.str('DIRECTORY_FORMS_API_API_KEY')
DIRECTORY_FORMS_API_SENDER_ID = env.str('DIRECTORY_FORMS_API_SENDER_ID')
DIRECTORY_FORMS_API_DEFAULT_TIMEOUT = env.int('DIRECTORY_API_FORMS_DEFAULT_TIMEOUT', 5)
DIRECTORY_FORMS_API_ZENDESK_SEVICE_NAME = env.str('DIRECTORY_FORMS_API_ZENDESK_SEVICE_NAME', 'directory')
# Brexit
EU_EXIT_ZENDESK_SUBDOMAIN = env.str('EU_EXIT_ZENDESK_SUBDOMAIN')
EU_EXIT_INTERNATIONAL_CONTACT_URL = env.str(
'EU_EXIT_INTERNATIONAL_CONTACT_URL', '/international/eu-exit-news/contact/'
)
# Contact
INVEST_CONTACT_URL = env.str('INVEST_CONTACT_URL', 'https://invest.great.gov.uk/contact/')
CAPITAL_INVEST_CONTACT_URL = env.str(
'CAPITAL_INVEST_CONTACT_URL', 'https://great.gov.uk/international/content/capital-invest/contact/'
)
FIND_A_SUPPLIER_CONTACT_URL = env.str('FIND_A_SUPPLIER_CONTACT_URL', 'https://trade.great.gov.uk/industries/contact/')
CONTACT_DOMESTIC_ZENDESK_SUBJECT = env.str('CONTACT_DOMESTIC_ZENDESK_SUBJECT', 'great.gov.uk contact form')
CONTACT_INTERNATIONAL_ZENDESK_SUBJECT = env.str(
'CONTACT_DOMESTIC_ZENDESK_SUBJECT',
'great.gov.uk international contact form'
)
CONTACT_SOO_ZENDESK_SUBJECT = env.str(
'CONTACT_DOMESTIC_ZENDESK_SUBJECT',
'great.gov.uk Selling Online Overseas contact form'
)
CONTACT_LOCAL_EXPORT_SUPPORT_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_LOCAL_EXPORT_SUPPORT_AGENT_NOTIFY_TEMPLATE_ID',
'6e6f8a6b-ff31-490d-8dc5-05225fffaf37'
)
CONTACT_LOCAL_EXPORT_SUPPORT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_LOCAL_EXPORT_SUPPORT_NOTIFY_TEMPLATE_ID',
'5d692991-0c57-4ae0-9053-95fd8ddf53eb'
)
CONTACT_EVENTS_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_EVENTS_USER_NOTIFY_TEMPLATE_ID',
'2d5d556a-e0fa-4a9b-81a0-6ed3fcb2e3da'
)
CONTACT_EVENTS_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_EVENTS_AGENT_NOTIFY_TEMPLATE_ID',
'bf11ece5-22e1-4ffd-b2ab-9f0632e6c95b'
)
CONTACT_EVENTS_AGENT_EMAIL_ADDRESS = env.str('CONTACT_EVENTS_AGENT_EMAIL_ADDRESS')
CONTACT_DSO_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_DSO_AGENT_NOTIFY_TEMPLATE_ID',
'bf11ece5-22e1-4ffd-b2ab-9f0632e6c95b'
)
CONTACT_DSO_AGENT_EMAIL_ADDRESS = env.str('CONTACT_DSO_AGENT_EMAIL_ADDRESS')
CONTACT_DSO_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_DSO_USER_NOTIFY_TEMPLATE_ID',
'a6a3db79-944f-4c59-8eeb-2f756019976c'
)
CONTACT_ECOMMERCE_EXPORT_SUPPORT_AGENT_EMAIL_ADDRESS = env.str('CONTACT_ECOMMERCE_EXPORT_SUPPORT_AGENT_EMAIL_ADDRESS')
CONTACT_ECOMMERCE_EXPORT_SUPPORT_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_ECOMMERCE_EXPORT_SUPPORT_AGENT_NOTIFY_TEMPLATE_ID',
'a56114d3-515e-4ee7-bb1a-9a0ceab04378'
)
CONTACT_ECOMMERCE_EXPORT_SUPPORT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_ECOMMERCE_EXPORT_SUPPORT_NOTIFY_TEMPLATE_ID',
'18d807d2-f4cf-4b93-96c1-0d3169bd0906',
)
CONTACT_DIT_AGENT_EMAIL_ADDRESS = env.str('CONTACT_DIT_AGENT_EMAIL_ADDRESS')
CONTACT_INTERNATIONAL_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_INTERNATIONAL_AGENT_NOTIFY_TEMPLATE_ID',
'8bd422e0-3ec4-4b05-9de8-9cf039d258a9'
)
CONTACT_INTERNATIONAL_AGENT_EMAIL_ADDRESS = env.str('CONTACT_INTERNATIONAL_AGENT_EMAIL_ADDRESS')
CONTACT_INTERNATIONAL_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_INTERNATIONAL_USER_NOTIFY_TEMPLATE_ID',
'c07d1fb2-dc0c-40ba-a3e0-3113638e69a3'
)
CONTACT_EXPORTING_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_EXPORTING_USER_NOTIFY_TEMPLATE_ID',
'5abd7372-a92d-4351-bccb-b9a38d353e75'
)
CONTACT_EXPORTING_USER_REPLY_TO_EMAIL_ID = env.str(
'CONTACT_EXPORTING_USER_REPLY_TO_EMAIL_ID',
'ac1b973d-5b49-4d0d-a197-865fd25b4a97'
)
CONTACT_OFFICE_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_OFFICE_AGENT_NOTIFY_TEMPLATE_ID',
'0492eb2b-7daf-4b37-99cd-be3abbb9eb32'
)
CONTACT_OFFICE_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_OFFICE_USER_NOTIFY_TEMPLATE_ID',
'03c031e1-1ee5-43f9-8b24-f6e4cfd56cf1'
)
CONTACT_ENQUIRIES_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_ENQUIRIES_AGENT_NOTIFY_TEMPLATE_ID',
'7a343ec9-7670-4813-9ed4-ae83d3e1f5f7'
)
CONTACT_ENQUIRIES_AGENT_EMAIL_ADDRESS = env.str('CONTACT_ENQUIRIES_AGENT_EMAIL_ADDRESS')
CONTACT_ENQUIRIES_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_ENQUIRIES_USER_NOTIFY_TEMPLATE_ID',
'61c82be6-b140-46fc-aeb2-472df8a94d35'
)
CONTACT_EXPORTING_AGENT_SUBJECT = env.str('CONTACT_EXPORTING_AGENT_SUBJECT', 'A form was submitted on great.gov.uk')
CONTACT_EXPORTING_TO_UK_HMRC_URL = env.str(
'CONTACT_EXPORTING_TO_UK_HRMC_URL',
'https://www.tax.service.gov.uk/shortforms/form/CITEX_CGEF'
)
CONTACT_DEFRA_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_DEFRA_AGENT_NOTIFY_TEMPLATE_ID',
'8823e0be-773e-42b0-8dad-740c94d439d4'
)
CONTACT_DEFRA_AGENT_EMAIL_ADDRESS = env.str('CONTACT_DEFRA_AGENT_EMAIL_ADDRESS')
CONTACT_DEFRA_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_DEFRA_USER_NOTIFY_TEMPLATE_ID',
'05d70d9f-76a6-4c2f-9f62-6ed4154d6dd6'
)
CONTACT_BEIS_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_BEIS_AGENT_NOTIFY_TEMPLATE_ID',
'8823e0be-773e-42b0-8dad-740c94d439d4'
)
CONTACT_BEIS_AGENT_EMAIL_ADDRESS = env.str('CONTACT_BEIS_AGENT_EMAIL_ADDRESS',)
CONTACT_BEIS_USER_NOTIFY_TEMPLATE_ID = env.str(
'CONTACT_BEIS_USER_NOTIFY_TEMPLATE_ID',
'cdc770d8-30e0-42fc-bf11-12385cb40845'
)
# Market Access
MARKET_ACCESS_ZENDESK_SUBJECT = env.str('MARKET_ACCESS_ZENDESK_SUBJECT', 'market access')
MARKET_ACCESS_FORMS_API_ZENDESK_SEVICE_NAME = env.str('MARKET_ACCESS_FORMS_API_ZENDESK_SEVICE_NAME', 'market_access')
# Community
COMMUNITY_ENQUIRIES_USER_NOTIFY_TEMPLATE_ID = env.str(
'COMMUNITY_ENQUIRIES_USER_NOTIFY_TEMPLATE_ID',
'b1a0f719-b00d-4fc4-bc4d-b68ccc50c651'
)
COMMUNITY_ENQUIRIES_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'COMMUNITY_ENQUIRIES_AGENT_NOTIFY_TEMPLATE_ID',
'63748451-6dbf-40ea-90b1-05f1f62c61ac'
)
COMMUNITY_ENQUIRIES_AGENT_EMAIL_ADDRESS = env.str('COMMUNITY_ENQUIRIES_AGENT_EMAIL_ADDRESS',)
# UKEF CONTACT FORM
UKEF_CONTACT_USER_NOTIFY_TEMPLATE_ID = env.str(
'UKEF_CONTACT_USER_NOTIFY_TEMPLATE_ID',
'09677460-1796-4a60-a37c-c1a59068219e'
)
UKEF_CONTACT_AGENT_NOTIFY_TEMPLATE_ID = env.str(
'UKEF_CONTACT_AGENT_NOTIFY_TEMPLATE_ID',
'e24ba486-6337-46ce-aba3-45d1d3a2aa66'
)
UKEF_CONTACT_AGENT_EMAIL_ADDRESS = env.str('UKEF_CONTACT_AGENT_EMAIL_ADDRESS',)
# Activity Stream API
ACTIVITY_STREAM_API_SECRET_KEY = env.str('ACTIVITY_STREAM_API_SECRET_KEY')
ACTIVITY_STREAM_API_ACCESS_KEY = env.str('ACTIVITY_STREAM_API_ACCESS_KEY')
ACTIVITY_STREAM_API_URL = env.str('ACTIVITY_STREAM_API_URL')
ACTIVITY_STREAM_API_IP_WHITELIST = env.str('ACTIVITY_STREAM_API_IP_WHITELIST')
# Export vouchers
EXPORT_VOUCHERS_GOV_NOTIFY_TEMPLATE_ID = env.str(
'EXPORT_VOUCHERS_GOV_NOTIFY_TEMPLATE_ID', 'c9d3ce3a-236a-4d80-a791-a85dbc6ed377'
)
EXPORT_VOUCHERS_AGENT_EMAIL = env.str('EXPORT_VOUCHERS_AGENT_EMAIL')
# Required by directory components (https://github.com/uktrade/directory-components/pull/286/files)
# These cookies are not used in domestic
LANGUAGE_COOKIE_SECURE = env.bool('LANGUAGE_COOKIE_SECURE', True)
COUNTRY_COOKIE_SECURE = env.bool('COUNTRY_COOKIE_SECURE', True)
# Authentication
AUTH_USER_MODEL = 'sso.SSOUser'
AUTHENTICATION_BACKENDS = ['directory_sso_api_client.backends.SSOUserBackend']
SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']
# Application Performance Monitoring
if env.str('ELASTIC_APM_SERVER_URL', ''):
ELASTIC_APM = {
'SERVICE_NAME': env.str('ELASTIC_APM_SERVICE_NAME', 'directory-cms'),
'SECRET_TOKEN': env.str('ELASTIC_APM_SECRET_TOKEN'),
'SERVER_URL': env.str('ELASTIC_APM_SERVER_URL'),
'ENVIRONMENT': env.str('SENTRY_ENVIRONMENT'),
'DEBUG': DEBUG,
}
INSTALLED_APPS.append('elasticapm.contrib.django')
|
[] |
[] |
[
"PRIVACY_COOKIE_DOMAIN"
] |
[]
|
["PRIVACY_COOKIE_DOMAIN"]
|
python
| 1 | 0 | |
louvre/asgi.py
|
"""
ASGI config for louvre 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', 'louvre.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
src/test/api_test.go
|
package main
import (
"fmt"
ts "github.com/lukashes/golang_telesign/src/telesign/rest"
"testing"
)
const (
CustomerID string = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"
SecretKey string = "TE8sTgg45yusumoN6BYsBVkhyRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="
)
func Test_generate_telesign_headers_with_post(tst *testing.T) {
method_name := "POST"
curr_date := "Wed, 14 Dec 2016 18:20:12 -0000"
nonce := "A1592C6F-E384-4CDB-BC42-C3AB970369E9"
resource := "/v1/resource"
body_params_url_encoded := "test=param"
expected_authorization_header := `TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:A0ky++zMbuQv0X7t2XMNY4omcdtwrUhNrn3H+xvomLk=`
actual_headers := ts.GenerateTelesignHeaders(
CustomerID,
SecretKey,
method_name,
resource,
body_params_url_encoded,
curr_date,
nonce,
"unit_test")
if expected_authorization_header != actual_headers["Authorization"] {
fmt.Println("Failed to validate POST Authorization, ", expected_authorization_header, actual_headers["Authorization"])
}
}
func Test_make_string_to_sign_with_post_unicode_content(tst *testing.T) {
method_name := "POST"
curr_date := "Wed, 14 Dec 2016 18:20:12 -0000"
nonce := "A1592C6F-E384-4CDB-BC42-C3AB970369E9"
resource := "/v1/resource"
body_params_url_encoded := "test=%CF%BF"
expected_authorization_header := `TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:XM96Yn9jRqMW9lSmEatzO8U+BEJUS2I4sbTHJzSZSeQ=`
actual_headers := ts.GenerateTelesignHeaders(
CustomerID,
SecretKey,
method_name,
resource,
body_params_url_encoded,
curr_date,
nonce,
"unit_test")
if expected_authorization_header != actual_headers["Authorization"] {
fmt.Println("Failed to validate Unicode Authorization, ", expected_authorization_header, actual_headers["Authorization"])
}
}
func Test_make_string_to_sign_with_get(tst *testing.T) {
method_name := "GET"
curr_date := "Wed, 14 Dec 2016 18:20:12 -0000"
nonce := "A1592C6F-E384-4CDB-BC42-C3AB970369E9"
resource := "/v1/resource"
expected_authorization_header := `TSA FFFFFFFF-EEEE-DDDD-1234-AB1234567890:e52pAhcuAcza7AGLbJX9+W1odHkZx7gcKePveMusLM4=`
actual_headers := ts.GenerateTelesignHeaders(
CustomerID,
SecretKey,
method_name,
resource,
"",
curr_date,
nonce,
"unit_test")
if expected_authorization_header != actual_headers["Authorization"] {
fmt.Println("Failed to validate GET Authorization, ", expected_authorization_header, actual_headers["Authorization"])
}
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
dashboard/app/main.go
|
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"cloud.google.com/go/logging"
"cloud.google.com/go/logging/logadmin"
"github.com/google/syzkaller/dashboard/dashapi"
"github.com/google/syzkaller/pkg/email"
"github.com/google/syzkaller/pkg/html"
"github.com/google/syzkaller/pkg/vcs"
"golang.org/x/net/context"
"google.golang.org/api/iterator"
"google.golang.org/appengine/v2"
db "google.golang.org/appengine/v2/datastore"
"google.golang.org/appengine/v2/log"
"google.golang.org/appengine/v2/memcache"
proto "google.golang.org/genproto/googleapis/appengine/logging/v1"
ltype "google.golang.org/genproto/googleapis/logging/type"
)
// This file contains web UI http handlers.
func initHTTPHandlers() {
http.Handle("/", handlerWrapper(handleMain))
http.Handle("/bug", handlerWrapper(handleBug))
http.Handle("/text", handlerWrapper(handleText))
http.Handle("/admin", handlerWrapper(handleAdmin))
http.Handle("/x/.config", handlerWrapper(handleTextX(textKernelConfig)))
http.Handle("/x/log.txt", handlerWrapper(handleTextX(textCrashLog)))
http.Handle("/x/report.txt", handlerWrapper(handleTextX(textCrashReport)))
http.Handle("/x/repro.syz", handlerWrapper(handleTextX(textReproSyz)))
http.Handle("/x/repro.c", handlerWrapper(handleTextX(textReproC)))
http.Handle("/x/patch.diff", handlerWrapper(handleTextX(textPatch)))
http.Handle("/x/bisect.txt", handlerWrapper(handleTextX(textLog)))
http.Handle("/x/error.txt", handlerWrapper(handleTextX(textError)))
http.Handle("/x/minfo.txt", handlerWrapper(handleTextX(textMachineInfo)))
for ns := range config.Namespaces {
http.Handle("/"+ns, handlerWrapper(handleMain))
http.Handle("/"+ns+"/fixed", handlerWrapper(handleFixed))
http.Handle("/"+ns+"/invalid", handlerWrapper(handleInvalid))
http.Handle("/"+ns+"/graph/bugs", handlerWrapper(handleKernelHealthGraph))
http.Handle("/"+ns+"/graph/lifetimes", handlerWrapper(handleGraphLifetimes))
http.Handle("/"+ns+"/graph/fuzzing", handlerWrapper(handleGraphFuzzing))
http.Handle("/"+ns+"/graph/crashes", handlerWrapper(handleGraphCrashes))
}
http.HandleFunc("/cache_update", cacheUpdate)
}
type uiMainPage struct {
Header *uiHeader
Now time.Time
Decommissioned bool
Managers []*uiManager
Groups []*uiBugGroup
}
type uiTerminalPage struct {
Header *uiHeader
Now time.Time
Bugs *uiBugGroup
}
type uiAdminPage struct {
Header *uiHeader
Log []byte
Managers []*uiManager
Jobs *uiJobList
MemcacheStats *memcache.Statistics
}
type uiManager struct {
Now time.Time
Namespace string
Name string
Link string
CoverLink string
CurrentBuild *uiBuild
FailedBuildBugLink string
FailedSyzBuildBugLink string
LastActive time.Time
CurrentUpTime time.Duration
MaxCorpus int64
MaxCover int64
TotalFuzzingTime time.Duration
TotalCrashes int64
TotalExecs int64
TotalExecsBad bool // highlight TotalExecs in red
}
type uiBuild struct {
Time time.Time
SyzkallerCommit string
SyzkallerCommitLink string
SyzkallerCommitDate time.Time
KernelAlias string
KernelCommit string
KernelCommitLink string
KernelCommitTitle string
KernelCommitDate time.Time
KernelConfigLink string
}
type uiCommit struct {
Hash string
Title string
Link string
Author string
CC []string
Date time.Time
}
type uiBugPage struct {
Header *uiHeader
Now time.Time
Bug *uiBug
BisectCause *uiJob
BisectFix *uiJob
DupOf *uiBugGroup
Dups *uiBugGroup
Similar *uiBugGroup
SampleReport template.HTML
Crashes *uiCrashTable
FixBisections *uiCrashTable
TestPatchJobs *uiJobList
}
type uiBugGroup struct {
Now time.Time
Caption string
Fragment string
Namespace string
ShowNamespace bool
ShowPatch bool
ShowPatched bool
ShowStatus bool
ShowIndex int
Bugs []*uiBug
DispLastAct bool
}
type uiJobList struct {
PerBug bool
Jobs []*uiJob
}
type uiBug struct {
Namespace string
Title string
NumCrashes int64
NumCrashesBad bool
BisectCause BisectStatus
BisectFix BisectStatus
FirstTime time.Time
LastTime time.Time
ReportedTime time.Time
ClosedTime time.Time
ReproLevel dashapi.ReproLevel
ReportingIndex int
Status string
Link string
ExternalLink string
CreditEmail string
Commits []*uiCommit
PatchedOn []string
MissingOn []string
NumManagers int
LastActivity time.Time
}
type uiCrash struct {
Title string
Manager string
Time time.Time
Maintainers string
LogLink string
ReportLink string
ReproSyzLink string
ReproCLink string
MachineInfoLink string
*uiBuild
}
type uiCrashTable struct {
Crashes []*uiCrash
Caption string
}
type uiJob struct {
Type JobType
Flags JobFlags
Created time.Time
BugLink string
ExternalLink string
User string
Reporting string
Namespace string
Manager string
BugTitle string
BugID string
KernelAlias string
KernelCommitLink string
PatchLink string
Attempts int
Started time.Time
Finished time.Time
Duration time.Duration
CrashTitle string
CrashLogLink string
CrashReportLink string
LogLink string
ErrorLink string
Commit *uiCommit // for conclusive bisection
Commits []*uiCommit // for inconclusive bisection
Crash *uiCrash
Reported bool
}
// handleMain serves main page.
func handleMain(c context.Context, w http.ResponseWriter, r *http.Request) error {
hdr, err := commonHeader(c, r, w, "")
if err != nil {
return err
}
accessLevel := accessLevel(c, r)
manager := r.FormValue("manager")
managers, err := loadManagers(c, accessLevel, hdr.Namespace, manager)
if err != nil {
return err
}
groups, err := fetchNamespaceBugs(c, accessLevel, hdr.Namespace, manager)
if err != nil {
return err
}
for _, group := range groups {
group.DispLastAct = true
}
data := &uiMainPage{
Header: hdr,
Decommissioned: config.Namespaces[hdr.Namespace].Decommissioned,
Now: timeNow(c),
Groups: groups,
Managers: managers,
}
return serveTemplate(w, "main.html", data)
}
func handleFixed(c context.Context, w http.ResponseWriter, r *http.Request) error {
return handleTerminalBugList(c, w, r, &TerminalBug{
Status: BugStatusFixed,
Subpage: "/fixed",
ShowPatch: true,
})
}
func handleInvalid(c context.Context, w http.ResponseWriter, r *http.Request) error {
return handleTerminalBugList(c, w, r, &TerminalBug{
Status: BugStatusInvalid,
Subpage: "/invalid",
ShowPatch: false,
})
}
type TerminalBug struct {
Status int
Subpage string
ShowPatch bool
}
func handleTerminalBugList(c context.Context, w http.ResponseWriter, r *http.Request, typ *TerminalBug) error {
accessLevel := accessLevel(c, r)
hdr, err := commonHeader(c, r, w, "")
if err != nil {
return err
}
hdr.Subpage = typ.Subpage
manager := r.FormValue("manager")
bugs, err := fetchTerminalBugs(c, accessLevel, hdr.Namespace, manager, typ)
if err != nil {
return err
}
data := &uiTerminalPage{
Header: hdr,
Now: timeNow(c),
Bugs: bugs,
}
return serveTemplate(w, "terminal.html", data)
}
func handleAdmin(c context.Context, w http.ResponseWriter, r *http.Request) error {
accessLevel := accessLevel(c, r)
if accessLevel != AccessAdmin {
return ErrAccess
}
switch action := r.FormValue("action"); action {
case "":
case "memcache_flush":
if err := memcache.Flush(c); err != nil {
return fmt.Errorf("failed to flush memcache: %v", err)
}
default:
return fmt.Errorf("unknown action %q", action)
}
hdr, err := commonHeader(c, r, w, "")
if err != nil {
return err
}
memcacheStats, err := memcache.Stats(c)
if err != nil {
return err
}
managers, err := loadManagers(c, accessLevel, "", "")
if err != nil {
return err
}
errorLog, err := fetchErrorLogs(c)
if err != nil {
return err
}
jobs, err := loadRecentJobs(c)
if err != nil {
return err
}
data := &uiAdminPage{
Header: hdr,
Log: errorLog,
Managers: managers,
Jobs: &uiJobList{Jobs: jobs},
MemcacheStats: memcacheStats,
}
return serveTemplate(w, "admin.html", data)
}
// handleBug serves page about a single bug (which is passed in id argument).
func handleBug(c context.Context, w http.ResponseWriter, r *http.Request) error {
bug, err := findBugByID(c, r)
if err != nil {
return fmt.Errorf("%v, %w", err, ErrClientNotFound)
}
accessLevel := accessLevel(c, r)
if err := checkAccessLevel(c, r, bug.sanitizeAccess(accessLevel)); err != nil {
return err
}
hdr, err := commonHeader(c, r, w, bug.Namespace)
if err != nil {
return err
}
state, err := loadReportingState(c)
if err != nil {
return err
}
managers, err := managerList(c, bug.Namespace)
if err != nil {
return err
}
var dupOf *uiBugGroup
if bug.DupOf != "" {
dup := new(Bug)
if err := db.Get(c, db.NewKey(c, "Bug", bug.DupOf, 0, nil), dup); err != nil {
return err
}
if accessLevel >= dup.sanitizeAccess(accessLevel) {
dupOf = &uiBugGroup{
Now: timeNow(c),
Caption: "Duplicate of",
Bugs: []*uiBug{createUIBug(c, dup, state, managers)},
}
}
}
uiBug := createUIBug(c, bug, state, managers)
crashes, sampleReport, err := loadCrashesForBug(c, bug)
if err != nil {
return err
}
crashesTable := &uiCrashTable{
Crashes: crashes,
Caption: fmt.Sprintf("Crashes (%d)", bug.NumCrashes),
}
dups, err := loadDupsForBug(c, r, bug, state, managers)
if err != nil {
return err
}
similar, err := loadSimilarBugs(c, r, bug, state)
if err != nil {
return err
}
var bisectCause *uiJob
if bug.BisectCause > BisectPending {
bisectCause, err = getUIJob(c, bug, JobBisectCause)
if err != nil {
return err
}
}
var bisectFix *uiJob
if bug.BisectFix > BisectPending {
bisectFix, err = getUIJob(c, bug, JobBisectFix)
if err != nil {
return err
}
}
testPatchJobs, err := loadTestPatchJobs(c, bug)
if err != nil {
return err
}
data := &uiBugPage{
Header: hdr,
Now: timeNow(c),
Bug: uiBug,
BisectCause: bisectCause,
BisectFix: bisectFix,
DupOf: dupOf,
Dups: dups,
Similar: similar,
SampleReport: sampleReport,
Crashes: crashesTable,
TestPatchJobs: &uiJobList{
PerBug: true,
Jobs: testPatchJobs,
},
}
// bug.BisectFix is set to BisectNot in two cases :
// - no fix bisections have been performed on the bug
// - fix bisection was performed but resulted in a crash on HEAD
if bug.BisectFix == BisectNot {
fixBisections, err := loadFixBisectionsForBug(c, bug)
if err != nil {
return err
}
if len(fixBisections) != 0 {
data.FixBisections = &uiCrashTable{
Crashes: fixBisections,
Caption: "Fix bisection attempts",
}
}
}
if isJSONRequested(r) {
w.Header().Set("Content-Type", "application/json")
return writeJSONVersionOf(w, data)
}
return serveTemplate(w, "bug.html", data)
}
func isJSONRequested(request *http.Request) bool {
return request.FormValue("json") == "1"
}
func writeJSONVersionOf(writer http.ResponseWriter, bugPage *uiBugPage) error {
data, err := json.MarshalIndent(
GetExtAPIDescrForBugPage(bugPage),
"",
"\t")
if err != nil {
return err
}
_, err = writer.Write(data)
return err
}
func findBugByID(c context.Context, r *http.Request) (*Bug, error) {
if id := r.FormValue("id"); id != "" {
bug := new(Bug)
bugKey := db.NewKey(c, "Bug", id, 0, nil)
err := db.Get(c, bugKey, bug)
return bug, err
}
if extID := r.FormValue("extid"); extID != "" {
bug, _, err := findBugByReportingID(c, extID)
return bug, err
}
return nil, fmt.Errorf("mandatory parameter id/extid is missing")
}
func getUIJob(c context.Context, bug *Bug, jobType JobType) (*uiJob, error) {
job, crash, jobKey, _, err := loadBisectJob(c, bug, jobType)
if err != nil {
return nil, err
}
build, err := loadBuild(c, bug.Namespace, crash.BuildID)
if err != nil {
return nil, err
}
return makeUIJob(job, jobKey, bug, crash, build), nil
}
// handleText serves plain text blobs (crash logs, reports, reproducers, etc).
func handleTextImpl(c context.Context, w http.ResponseWriter, r *http.Request, tag string) error {
var id int64
if x := r.FormValue("x"); x != "" {
xid, err := strconv.ParseUint(x, 16, 64)
if err != nil || xid == 0 {
return fmt.Errorf("failed to parse text id: %v: %w", err, ErrClientBadRequest)
}
id = int64(xid)
} else {
// Old link support, don't remove.
xid, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
if err != nil || xid == 0 {
return fmt.Errorf("failed to parse text id: %v: %w", err, ErrClientBadRequest)
}
id = xid
}
bug, crash, err := checkTextAccess(c, r, tag, id)
if err != nil {
return err
}
data, ns, err := getText(c, tag, id)
if err != nil {
if strings.Contains(err.Error(), "datastore: no such entity") {
err = fmt.Errorf("%v: %w", err, ErrClientBadRequest)
}
return err
}
if err := checkAccessLevel(c, r, config.Namespaces[ns].AccessLevel); err != nil {
return err
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
// Unfortunately filename does not work in chrome on linux due to:
// https://bugs.chromium.org/p/chromium/issues/detail?id=608342
w.Header().Set("Content-Disposition", "inline; filename="+textFilename(tag))
augmentRepro(c, w, tag, bug, crash)
w.Write(data)
return nil
}
func augmentRepro(c context.Context, w http.ResponseWriter, tag string, bug *Bug, crash *Crash) {
if tag == textReproSyz || tag == textReproC {
// Users asked for the bug link in reproducers (in case you only saved the repro link).
if bug != nil {
prefix := "#"
if tag == textReproC {
prefix = "//"
}
fmt.Fprintf(w, "%v %v/bug?id=%v\n", prefix, appURL(c), bug.keyHash())
}
}
if tag == textReproSyz {
// Add link to documentation and repro opts for syzkaller reproducers.
w.Write([]byte(syzReproPrefix))
if crash != nil {
fmt.Fprintf(w, "#%s\n", crash.ReproOpts)
}
}
}
func handleText(c context.Context, w http.ResponseWriter, r *http.Request) error {
return handleTextImpl(c, w, r, r.FormValue("tag"))
}
func handleTextX(tag string) contextHandler {
return func(c context.Context, w http.ResponseWriter, r *http.Request) error {
return handleTextImpl(c, w, r, tag)
}
}
func textFilename(tag string) string {
switch tag {
case textKernelConfig:
return ".config"
case textCrashLog:
return "log.txt"
case textCrashReport:
return "report.txt"
case textReproSyz:
return "repro.syz"
case textReproC:
return "repro.c"
case textPatch:
return "patch.diff"
case textLog:
return "bisect.txt"
case textError:
return "error.txt"
case textMachineInfo:
return "minfo.txt"
default:
panic(fmt.Sprintf("unknown tag %v", tag))
}
}
func fetchNamespaceBugs(c context.Context, accessLevel AccessLevel, ns, manager string) ([]*uiBugGroup, error) {
bugs, err := loadVisibleBugs(c, accessLevel, ns, manager)
if err != nil {
return nil, err
}
state, err := loadReportingState(c)
if err != nil {
return nil, err
}
managers, err := managerList(c, ns)
if err != nil {
return nil, err
}
groups := make(map[int][]*uiBug)
bugMap := make(map[string]*uiBug)
var dups []*Bug
for _, bug := range bugs {
if accessLevel < bug.sanitizeAccess(accessLevel) {
continue
}
if bug.Status == BugStatusDup {
dups = append(dups, bug)
continue
}
uiBug := createUIBug(c, bug, state, managers)
bugMap[bug.keyHash()] = uiBug
id := uiBug.ReportingIndex
if len(uiBug.Commits) != 0 {
id = -1
}
groups[id] = append(groups[id], uiBug)
}
for _, dup := range dups {
bug := bugMap[dup.DupOf]
if bug == nil {
continue // this can be an invalid bug which we filtered above
}
mergeUIBug(c, bug, dup)
}
cfg := config.Namespaces[ns]
var uiGroups []*uiBugGroup
for index, bugs := range groups {
sort.Slice(bugs, func(i, j int) bool {
if bugs[i].Namespace != bugs[j].Namespace {
return bugs[i].Namespace < bugs[j].Namespace
}
if bugs[i].ClosedTime != bugs[j].ClosedTime {
return bugs[i].ClosedTime.After(bugs[j].ClosedTime)
}
return bugs[i].ReportedTime.After(bugs[j].ReportedTime)
})
caption, fragment, showPatched := "", "", false
switch index {
case -1:
caption, showPatched = "fix pending", true
fragment = "pending"
case len(cfg.Reporting) - 1:
caption, showPatched = "open", false
fragment = "open"
default:
reporting := &cfg.Reporting[index]
caption, showPatched = reporting.DisplayTitle, false
fragment = reporting.Name
}
uiGroups = append(uiGroups, &uiBugGroup{
Now: timeNow(c),
Caption: caption,
Fragment: fragment,
Namespace: ns,
ShowPatched: showPatched,
ShowIndex: index,
Bugs: bugs,
})
}
sort.Slice(uiGroups, func(i, j int) bool {
return uiGroups[i].ShowIndex > uiGroups[j].ShowIndex
})
return uiGroups, nil
}
func loadVisibleBugs(c context.Context, accessLevel AccessLevel, ns, manager string) ([]*Bug, error) {
// Load open and dup bugs in in 2 separate queries.
// Ideally we load them in one query with a suitable filter,
// but unfortunately status values don't allow one query (<BugStatusFixed || >BugStatusInvalid).
// Ideally we also have separate status for "dup of a closed bug" as we don't need to fetch them.
// Potentially changing "dup" to "dup of a closed bug" can be done in background.
// But 2 queries is still much faster than fetching all bugs and we can do this in parallel.
errc := make(chan error)
var dups []*Bug
go func() {
filter := func(query *db.Query) *db.Query {
query = query.Filter("Namespace=", ns).
Filter("Status=", BugStatusDup)
if manager != "" {
query = query.Filter("HappenedOn=", manager)
}
return query
}
var err error
dups, _, err = loadAllBugs(c, filter)
errc <- err
}()
filter := func(query *db.Query) *db.Query {
query = query.Filter("Namespace=", ns).
Filter("Status<", BugStatusFixed)
if manager != "" {
query = query.Filter("HappenedOn=", manager)
}
return query
}
bugs, _, err := loadAllBugs(c, filter)
if err != nil {
return nil, err
}
if err := <-errc; err != nil {
return nil, err
}
return append(bugs, dups...), nil
}
func fetchTerminalBugs(c context.Context, accessLevel AccessLevel,
ns, manager string, typ *TerminalBug) (*uiBugGroup, error) {
bugs, _, err := loadAllBugs(c, func(query *db.Query) *db.Query {
query = query.Filter("Namespace=", ns).
Filter("Status=", typ.Status)
if manager != "" {
query = query.Filter("HappenedOn=", manager)
}
return query
})
if err != nil {
return nil, err
}
state, err := loadReportingState(c)
if err != nil {
return nil, err
}
managers, err := managerList(c, ns)
if err != nil {
return nil, err
}
res := &uiBugGroup{
Now: timeNow(c),
ShowPatch: typ.ShowPatch,
Namespace: ns,
}
for _, bug := range bugs {
if accessLevel < bug.sanitizeAccess(accessLevel) {
continue
}
res.Bugs = append(res.Bugs, createUIBug(c, bug, state, managers))
}
sort.Slice(res.Bugs, func(i, j int) bool {
return res.Bugs[i].ClosedTime.After(res.Bugs[j].ClosedTime)
})
return res, nil
}
func loadDupsForBug(c context.Context, r *http.Request, bug *Bug, state *ReportingState, managers []string) (
*uiBugGroup, error) {
bugHash := bug.keyHash()
var dups []*Bug
_, err := db.NewQuery("Bug").
Filter("Status=", BugStatusDup).
Filter("DupOf=", bugHash).
GetAll(c, &dups)
if err != nil {
return nil, err
}
var results []*uiBug
accessLevel := accessLevel(c, r)
for _, dup := range dups {
if accessLevel < dup.sanitizeAccess(accessLevel) {
continue
}
results = append(results, createUIBug(c, dup, state, managers))
}
group := &uiBugGroup{
Now: timeNow(c),
Caption: "duplicates",
ShowPatched: true,
ShowStatus: true,
Bugs: results,
}
return group, nil
}
func loadSimilarBugs(c context.Context, r *http.Request, bug *Bug, state *ReportingState) (*uiBugGroup, error) {
managers := make(map[string][]string)
var results []*uiBug
accessLevel := accessLevel(c, r)
domain := config.Namespaces[bug.Namespace].SimilarityDomain
dedup := make(map[string]bool)
dedup[bug.keyHash()] = true
for _, title := range bug.AltTitles {
var similar []*Bug
_, err := db.NewQuery("Bug").
Filter("AltTitles=", title).
GetAll(c, &similar)
if err != nil {
return nil, err
}
for _, similar := range similar {
if accessLevel < similar.sanitizeAccess(accessLevel) ||
config.Namespaces[similar.Namespace].SimilarityDomain != domain ||
dedup[similar.keyHash()] {
continue
}
dedup[similar.keyHash()] = true
if managers[similar.Namespace] == nil {
mgrs, err := managerList(c, similar.Namespace)
if err != nil {
return nil, err
}
managers[similar.Namespace] = mgrs
}
results = append(results, createUIBug(c, similar, state, managers[similar.Namespace]))
}
}
group := &uiBugGroup{
Now: timeNow(c),
Caption: "similar bugs",
ShowNamespace: true,
ShowPatched: true,
ShowStatus: true,
Bugs: results,
}
return group, nil
}
func createUIBug(c context.Context, bug *Bug, state *ReportingState, managers []string) *uiBug {
reportingIdx, status, link := 0, "", ""
var reported time.Time
var err error
if bug.Status == BugStatusOpen {
_, _, _, _, reportingIdx, status, link, err = needReport(c, "", state, bug)
reported = bug.Reporting[reportingIdx].Reported
if err != nil {
status = err.Error()
}
if status == "" {
status = "???"
}
} else {
for i := range bug.Reporting {
bugReporting := &bug.Reporting[i]
if i == len(bug.Reporting)-1 ||
bug.Status == BugStatusInvalid && !bugReporting.Closed.IsZero() &&
bug.Reporting[i+1].Closed.IsZero() ||
(bug.Status == BugStatusFixed || bug.Status == BugStatusDup) &&
bugReporting.Closed.IsZero() {
reportingIdx = i
reported = bugReporting.Reported
link = bugReporting.Link
switch bug.Status {
case BugStatusInvalid:
status = "closed as invalid"
if bugReporting.Auto {
status = "auto-" + status
}
case BugStatusFixed:
status = "fixed"
case BugStatusDup:
status = "closed as dup"
default:
status = fmt.Sprintf("unknown (%v)", bug.Status)
}
status = fmt.Sprintf("%v on %v", status, html.FormatTime(bug.Closed))
break
}
}
}
creditEmail, err := email.AddAddrContext(ownEmail(c), bug.Reporting[reportingIdx].ID)
if err != nil {
log.Errorf(c, "failed to generate credit email: %v", err)
}
id := bug.keyHash()
uiBug := &uiBug{
Namespace: bug.Namespace,
Title: bug.displayTitle(),
BisectCause: bug.BisectCause,
BisectFix: bug.BisectFix,
NumCrashes: bug.NumCrashes,
FirstTime: bug.FirstTime,
LastTime: bug.LastTime,
ReportedTime: reported,
ClosedTime: bug.Closed,
ReproLevel: bug.ReproLevel,
ReportingIndex: reportingIdx,
Status: status,
Link: bugLink(id),
ExternalLink: link,
CreditEmail: creditEmail,
NumManagers: len(managers),
LastActivity: bug.LastActivity,
}
updateBugBadness(c, uiBug)
if len(bug.Commits) != 0 {
for i, com := range bug.Commits {
cfg := config.Namespaces[bug.Namespace]
info := bug.getCommitInfo(i)
uiBug.Commits = append(uiBug.Commits, &uiCommit{
Hash: info.Hash,
Title: com,
Link: vcs.CommitLink(cfg.Repos[0].URL, info.Hash),
})
}
for _, mgr := range managers {
found := false
for _, mgr1 := range bug.PatchedOn {
if mgr == mgr1 {
found = true
break
}
}
if found {
uiBug.PatchedOn = append(uiBug.PatchedOn, mgr)
} else {
uiBug.MissingOn = append(uiBug.MissingOn, mgr)
}
}
sort.Strings(uiBug.PatchedOn)
sort.Strings(uiBug.MissingOn)
}
return uiBug
}
func mergeUIBug(c context.Context, bug *uiBug, dup *Bug) {
bug.NumCrashes += dup.NumCrashes
bug.BisectCause = mergeBisectStatus(bug.BisectCause, dup.BisectCause)
bug.BisectFix = mergeBisectStatus(bug.BisectFix, dup.BisectFix)
if bug.LastTime.Before(dup.LastTime) {
bug.LastTime = dup.LastTime
}
if bug.ReproLevel < dup.ReproLevel {
bug.ReproLevel = dup.ReproLevel
}
updateBugBadness(c, bug)
}
func mergeBisectStatus(a, b BisectStatus) BisectStatus {
// The statuses are stored in the datastore, so we can't reorder them.
// But if one of bisections is Yes, then we want to show Yes.
bisectPriority := [bisectStatusLast]int{0, 1, 2, 6, 5, 4, 3}
if bisectPriority[a] >= bisectPriority[b] {
return a
}
return b
}
func updateBugBadness(c context.Context, bug *uiBug) {
bug.NumCrashesBad = bug.NumCrashes >= 10000 && timeNow(c).Sub(bug.LastTime) < 24*time.Hour
}
func loadCrashesForBug(c context.Context, bug *Bug) ([]*uiCrash, template.HTML, error) {
bugKey := bug.key(c)
// We can have more than maxCrashes crashes, if we have lots of reproducers.
crashes, _, err := queryCrashesForBug(c, bugKey, 2*maxCrashes+200)
if err != nil || len(crashes) == 0 {
return nil, "", err
}
builds := make(map[string]*Build)
var results []*uiCrash
for _, crash := range crashes {
build := builds[crash.BuildID]
if build == nil {
build, err = loadBuild(c, bug.Namespace, crash.BuildID)
if err != nil {
return nil, "", err
}
builds[crash.BuildID] = build
}
results = append(results, makeUICrash(crash, build))
}
sampleReport, _, err := getText(c, textCrashReport, crashes[0].Report)
if err != nil {
return nil, "", err
}
sampleBuild := builds[crashes[0].BuildID]
linkifiedReport := linkifyReport(sampleReport, sampleBuild.KernelRepo, sampleBuild.KernelCommit)
return results, linkifiedReport, nil
}
func linkifyReport(report []byte, repo, commit string) template.HTML {
escaped := template.HTMLEscapeString(string(report))
return template.HTML(sourceFileRe.ReplaceAllStringFunc(escaped, func(match string) string {
sub := sourceFileRe.FindStringSubmatch(match)
line, _ := strconv.Atoi(sub[3])
url := vcs.FileLink(repo, commit, sub[2], line)
return fmt.Sprintf("%v<a href='%v'>%v:%v</a>%v", sub[1], url, sub[2], sub[3], sub[4])
}))
}
var sourceFileRe = regexp.MustCompile("( |\t|\n)([a-zA-Z0-9/_-]+\\.(?:h|c|cc|cpp|s|S|go|rs)):([0-9]+)( |!|\t|\n)")
func loadFixBisectionsForBug(c context.Context, bug *Bug) ([]*uiCrash, error) {
bugKey := bug.key(c)
jobs, _, err := queryJobsForBug(c, bugKey, JobBisectFix)
if err != nil {
return nil, err
}
var results []*uiCrash
for _, job := range jobs {
crash, err := queryCrashForJob(c, job, bugKey)
if err != nil {
return nil, err
}
if crash == nil {
continue
}
build, err := loadBuild(c, bug.Namespace, job.BuildID)
if err != nil {
return nil, err
}
results = append(results, makeUICrash(crash, build))
}
return results, nil
}
func makeUICrash(crash *Crash, build *Build) *uiCrash {
ui := &uiCrash{
Title: crash.Title,
Manager: crash.Manager,
Time: crash.Time,
Maintainers: strings.Join(crash.Maintainers, ", "),
LogLink: textLink(textCrashLog, crash.Log),
ReportLink: textLink(textCrashReport, crash.Report),
ReproSyzLink: textLink(textReproSyz, crash.ReproSyz),
ReproCLink: textLink(textReproC, crash.ReproC),
MachineInfoLink: textLink(textMachineInfo, crash.MachineInfo),
}
if build != nil {
ui.uiBuild = makeUIBuild(build)
}
return ui
}
func makeUIBuild(build *Build) *uiBuild {
return &uiBuild{
Time: build.Time,
SyzkallerCommit: build.SyzkallerCommit,
SyzkallerCommitLink: vcs.LogLink(vcs.SyzkallerRepo, build.SyzkallerCommit),
SyzkallerCommitDate: build.SyzkallerCommitDate,
KernelAlias: kernelRepoInfo(build).Alias,
KernelCommit: build.KernelCommit,
KernelCommitLink: vcs.LogLink(build.KernelRepo, build.KernelCommit),
KernelCommitTitle: build.KernelCommitTitle,
KernelCommitDate: build.KernelCommitDate,
KernelConfigLink: textLink(textKernelConfig, build.KernelConfig),
}
}
func loadManagers(c context.Context, accessLevel AccessLevel, ns, manager string) ([]*uiManager, error) {
now := timeNow(c)
date := timeDate(now)
managers, managerKeys, err := loadManagerList(c, accessLevel, ns, manager)
if err != nil {
return nil, err
}
var buildKeys []*db.Key
var statsKeys []*db.Key
for i, mgr := range managers {
if mgr.CurrentBuild != "" {
buildKeys = append(buildKeys, buildKey(c, mgr.Namespace, mgr.CurrentBuild))
}
if timeDate(mgr.LastAlive) == date {
statsKeys = append(statsKeys,
db.NewKey(c, "ManagerStats", "", int64(date), managerKeys[i]))
}
}
builds := make([]*Build, len(buildKeys))
if err := db.GetMulti(c, buildKeys, builds); err != nil {
return nil, err
}
uiBuilds := make(map[string]*uiBuild)
for _, build := range builds {
uiBuilds[build.Namespace+"|"+build.ID] = makeUIBuild(build)
}
stats := make([]*ManagerStats, len(statsKeys))
if err := db.GetMulti(c, statsKeys, stats); err != nil {
return nil, fmt.Errorf("fetching manager stats: %v", err)
}
var fullStats []*ManagerStats
for _, mgr := range managers {
if timeDate(mgr.LastAlive) != date {
fullStats = append(fullStats, &ManagerStats{})
continue
}
fullStats = append(fullStats, stats[0])
stats = stats[1:]
}
var results []*uiManager
for i, mgr := range managers {
stats := fullStats[i]
link := mgr.Link
if accessLevel < AccessUser {
link = ""
}
uptime := mgr.CurrentUpTime
if now.Sub(mgr.LastAlive) > 6*time.Hour {
uptime = 0
}
ui := &uiManager{
Now: timeNow(c),
Namespace: mgr.Namespace,
Name: mgr.Name,
Link: link,
CoverLink: config.CoverPath + mgr.Name + ".html",
CurrentBuild: uiBuilds[mgr.Namespace+"|"+mgr.CurrentBuild],
FailedBuildBugLink: bugLink(mgr.FailedBuildBug),
FailedSyzBuildBugLink: bugLink(mgr.FailedSyzBuildBug),
LastActive: mgr.LastAlive,
CurrentUpTime: uptime,
MaxCorpus: stats.MaxCorpus,
MaxCover: stats.MaxCover,
TotalFuzzingTime: stats.TotalFuzzingTime,
TotalCrashes: stats.TotalCrashes,
TotalExecs: stats.TotalExecs,
TotalExecsBad: stats.TotalExecs == 0,
}
results = append(results, ui)
}
sort.Slice(results, func(i, j int) bool {
if results[i].Namespace != results[j].Namespace {
return results[i].Namespace < results[j].Namespace
}
return results[i].Name < results[j].Name
})
return results, nil
}
func loadManagerList(c context.Context, accessLevel AccessLevel, ns, manager string) ([]*Manager, []*db.Key, error) {
managers, keys, err := loadAllManagers(c, ns)
if err != nil {
return nil, nil, err
}
var filtered []*Manager
var filteredKeys []*db.Key
for i, mgr := range managers {
cfg := config.Namespaces[mgr.Namespace]
if accessLevel < cfg.AccessLevel {
continue
}
if ns == "" && cfg.Decommissioned {
continue
}
if manager != "" && manager != mgr.Name {
continue
}
filtered = append(filtered, mgr)
filteredKeys = append(filteredKeys, keys[i])
}
return filtered, filteredKeys, nil
}
func loadRecentJobs(c context.Context) ([]*uiJob, error) {
var jobs []*Job
keys, err := db.NewQuery("Job").
Order("-Created").
Limit(80).
GetAll(c, &jobs)
if err != nil {
return nil, err
}
var results []*uiJob
for i, job := range jobs {
results = append(results, makeUIJob(job, keys[i], nil, nil, nil))
}
return results, nil
}
func loadTestPatchJobs(c context.Context, bug *Bug) ([]*uiJob, error) {
bugKey := bug.key(c)
var jobs []*Job
keys, err := db.NewQuery("Job").
Ancestor(bugKey).
Filter("Type=", JobTestPatch).
Filter("Finished>=", time.Time{}).
Order("-Finished").
GetAll(c, &jobs)
if err != nil {
return nil, err
}
var results []*uiJob
for i, job := range jobs {
var build *Build
if job.BuildID != "" {
if build, err = loadBuild(c, bug.Namespace, job.BuildID); err != nil {
return nil, err
}
}
results = append(results, makeUIJob(job, keys[i], nil, nil, build))
}
return results, nil
}
func makeUIJob(job *Job, jobKey *db.Key, bug *Bug, crash *Crash, build *Build) *uiJob {
kernelRepo, kernelCommit := job.KernelRepo, job.KernelBranch
if build != nil {
kernelRepo, kernelCommit = build.KernelRepo, build.KernelCommit
}
ui := &uiJob{
Type: job.Type,
Flags: job.Flags,
Created: job.Created,
BugLink: bugLink(jobKey.Parent().StringID()),
ExternalLink: job.Link,
User: job.User,
Reporting: job.Reporting,
Namespace: job.Namespace,
Manager: job.Manager,
BugTitle: job.BugTitle,
KernelAlias: kernelRepoInfoRaw(job.Namespace, job.KernelRepo, job.KernelBranch).Alias,
KernelCommitLink: vcs.CommitLink(kernelRepo, kernelCommit),
PatchLink: textLink(textPatch, job.Patch),
Attempts: job.Attempts,
Started: job.Started,
Finished: job.Finished,
CrashTitle: job.CrashTitle,
CrashLogLink: textLink(textCrashLog, job.CrashLog),
CrashReportLink: textLink(textCrashReport, job.CrashReport),
LogLink: textLink(textLog, job.Log),
ErrorLink: textLink(textError, job.Error),
Reported: job.Reported,
}
if !job.Finished.IsZero() {
ui.Duration = job.Finished.Sub(job.Started)
}
if job.Type == JobBisectCause || job.Type == JobBisectFix {
// We don't report these yet (or at all), see pollCompletedJobs.
if len(job.Commits) != 1 ||
bug != nil && (len(bug.Commits) != 0 || bug.Status != BugStatusOpen) {
ui.Reported = true
}
}
for _, com := range job.Commits {
ui.Commits = append(ui.Commits, &uiCommit{
Hash: com.Hash,
Title: com.Title,
Author: fmt.Sprintf("%v <%v>", com.AuthorName, com.Author),
CC: strings.Split(com.CC, "|"),
Date: com.Date,
Link: vcs.CommitLink(kernelRepo, com.Hash),
})
}
if len(ui.Commits) == 1 {
ui.Commit = ui.Commits[0]
ui.Commits = nil
}
if crash != nil {
ui.Crash = makeUICrash(crash, build)
}
return ui
}
func fetchErrorLogs(c context.Context) ([]byte, error) {
if !appengine.IsAppEngine() {
return nil, nil
}
const (
maxLines = 100
maxLineLen = 1000
)
projID := os.Getenv("GOOGLE_CLOUD_PROJECT")
adminClient, err := logadmin.NewClient(c, projID)
if err != nil {
return nil, fmt.Errorf("failed to create the logging client: %v", err)
}
defer adminClient.Close()
const name = "appengine.googleapis.com%2Frequest_log"
lastWeek := time.Now().Add(-1 * 7 * 24 * time.Hour).Format(time.RFC3339)
iter := adminClient.Entries(c,
logadmin.Filter(
fmt.Sprintf(`logName = "projects/%s/logs/%s" AND timestamp > "%s" AND severity>="ERROR"`,
projID, name, lastWeek)),
logadmin.NewestFirst(),
)
var entries []*logging.Entry
for len(entries) < maxLines {
entry, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
entries = append(entries, entry)
}
var lines []string
for _, entry := range entries {
requestLog := entry.Payload.(*proto.RequestLog)
for _, logLine := range requestLog.Line {
if logLine.GetSeverity() < ltype.LogSeverity_ERROR {
continue
}
line := fmt.Sprintf("%v: %v %v %v \"%v\"",
entry.Timestamp.Format(time.Stamp),
requestLog.GetStatus(),
requestLog.GetMethod(),
requestLog.GetResource(),
logLine.GetLogMessage())
line = strings.Replace(line, "\n", " ", -1)
line = strings.Replace(line, "\r", "", -1)
if len(line) > maxLineLen {
line = line[:maxLineLen]
}
line = line + "\n"
lines = append(lines, line)
}
}
buf := new(bytes.Buffer)
for i := len(lines) - 1; i >= 0; i-- {
buf.WriteString(lines[i])
}
return buf.Bytes(), nil
}
func bugLink(id string) string {
if id == "" {
return ""
}
return "/bug?id=" + id
}
|
[
"\"GOOGLE_CLOUD_PROJECT\""
] |
[] |
[
"GOOGLE_CLOUD_PROJECT"
] |
[]
|
["GOOGLE_CLOUD_PROJECT"]
|
go
| 1 | 0 | |
pkg/controller/utils/utils.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 utils
import (
"os"
"strconv"
"time"
"github.com/Pallinder/go-randomdata"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog"
loadbalancing_v1alpha1 "plenus.io/plenuslb/pkg/apis/loadbalancing/v1alpha1"
)
// ServiceIsLoadBalancer returns true if the given service is of type load balancer
func ServiceIsLoadBalancer(service *v1.Service) bool {
if service != nil && service.Spec.Type == v1.ServiceTypeLoadBalancer {
return true
}
return false
}
// ServiceHasExternalIPs return true if the service has at least one external ip
func ServiceHasExternalIPs(service *v1.Service) (bool, []string) {
if len(service.Spec.ExternalIPs) > 0 {
return true, service.Spec.ExternalIPs
}
return false, []string{}
}
// ContainsString tells whether a contains x.
func ContainsString(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
// PoolHasAddress checks if the given persistent ip pool ad a specific address
func PoolHasAddress(pool *loadbalancing_v1alpha1.PersistentIPPool, address string) bool {
for _, poolAddress := range pool.Spec.Addresses {
if poolAddress == address {
return true
}
}
return false
}
// GetClusterName returns a cluster name from the CLUSTER_NAME
// or a silly name if the env variable is not provided
func GetClusterName() string {
clusterName := os.Getenv("CLUSTER_NAME")
if clusterName == "" {
return randomdata.SillyName()
}
return clusterName
}
// DefaultObjectBackoff is the default backoff for a generic object
var DefaultObjectBackoff = wait.Backoff{
Steps: 10,
Duration: 100 * time.Millisecond,
Factor: 2.0,
Jitter: 0.1,
}
// DefaultAPIBackoff is the default backoff for external apis
var DefaultAPIBackoff = wait.Backoff{
Steps: 10,
Duration: 10 * time.Millisecond,
Factor: 2.0,
Jitter: 0.1,
}
// ForeverBackoff holds parameters applied to a Backoff function.
type ForeverBackoff struct {
// The initial duration.
Duration time.Duration
// Duration is multiplied by factor each iteration, if factor is not zero
// and the limits imposed by Steps and Cap have not been reached.
// Should not be negative.
// The jitter does not contribute to the updates to the duration parameter.
Factor float64
// The sleep at each iteration is the duration plus an additional
// amount chosen uniformly at random from the interval between
// zero and `jitter*duration`.
Jitter float64
// The remaining number of iterations in which the duration
// parameter may change (but progress can be stopped earlier by
// hitting the cap). If not positive, the duration is not
// changed. Used for exponential backoff in combination with
// Factor and Cap.
Steps int
// A limit on revised values of the duration parameter. If a
// multiplication by the factor parameter would make the duration
// exceed the cap then the duration is set to the cap
Cap time.Duration
}
// Step (1) returns an amount of time to sleep determined by the
// original Duration and Jitter and (2) mutates the provided Backoff
// to update its Steps and Duration.
func (b *ForeverBackoff) Step() time.Duration {
if b.Steps < 1 {
if b.Jitter > 0 {
return wait.Jitter(b.Duration, b.Jitter)
}
return b.Duration
}
b.Steps--
duration := b.Duration
// calculate the next step
if b.Factor != 0 {
b.Duration = time.Duration(float64(b.Duration) * b.Factor)
if b.Cap > 0 && b.Duration > b.Cap {
b.Duration = b.Cap
}
}
if b.Jitter > 0 {
duration = wait.Jitter(duration, b.Jitter)
}
return duration
}
// ExponentialBackoffWithForeverCap repeats a condition check with exponential backoff.
//
// It repeatedly checks the condition and then sleeps, using `backoff.Step()`
// to determine the length of the sleep and adjust Duration and Steps.
// Stops and returns as soon as:
// 1. the condition check returns true or an error,
// 2. `backoff.Steps` checks of the condition have been done, or
// 3. a sleep truncated by the cap on duration has been completed.
// In case (1) the returned error is what the condition function returned.
// In all other cases, ErrWaitTimeout is returned.
func ExponentialBackoffWithForeverCap(backoff ForeverBackoff, condition wait.ConditionFunc) error {
for backoff.Steps > 0 {
if ok, err := condition(); err != nil || ok {
return err
}
if backoff.Steps == 1 {
break
}
step := backoff.Step()
time.Sleep(step)
}
return wait.ErrWaitTimeout
}
// OnErrorForever executes the provided function repeatedly, retrying if the server returns a specified
// error. Callers should preserve previous executions if they wish to retry changes. It performs an
// exponential backoff with forever cap.
//
// var pod *api.Pod
// err := retry.OnErrorForever(DefaultBackoff, errors.IsConflict, func() (err error) {
// pod, err = c.Pods("mynamespace").UpdateStatus(podStatus)
// return
// })
// if err != nil {
// // may be conflict if max retries were hit
// return err
// }
// ...
//
func OnErrorForever(backoff ForeverBackoff, errorFunc func(error) bool, fn func() error) error {
var lastConflictErr error
err := ExponentialBackoffWithForeverCap(backoff, func() (bool, error) {
err := fn()
switch {
case err == nil:
return true, nil
case errorFunc(err):
lastConflictErr = err
return false, nil
default:
return false, err
}
})
if err == wait.ErrWaitTimeout {
err = lastConflictErr
}
return err
}
// ErrorBackoff is the backoff for allocations in error state
var ErrorBackoff = ForeverBackoff{
Steps: 552,
// Steps: 20,
Duration: 1 * time.Second,
Factor: 1.2,
Jitter: 0.2,
Cap: 5 * time.Minute,
}
func HealthPort() int32 {
if customPort := os.Getenv("HEALTH_PORT"); customPort != "" {
i64, err := strconv.ParseInt(customPort, 10, 32)
if err != nil {
klog.Fatal(err)
}
return int32(i64)
}
return 8080
}
|
[
"\"CLUSTER_NAME\"",
"\"HEALTH_PORT\""
] |
[] |
[
"CLUSTER_NAME",
"HEALTH_PORT"
] |
[]
|
["CLUSTER_NAME", "HEALTH_PORT"]
|
go
| 2 | 0 | |
zenodo_uploader.py
|
import os
import argparse
import requests
import yaml
import json
def upload_to_zenodo(
file_name_to_upload,
config_file,
zenodo_server="https://sandbox.zenodo.org/api/deposit/depositions",
):
filename = os.path.abspath(file_name_to_upload)
if not os.path.isfile(filename):
raise FileNotFoundError(
f"The file, specified for uploading does not exist: {filename}"
)
config_name = os.path.abspath(config_file)
if not os.path.isfile(config_name):
raise FileNotFoundError(
f"The file with metadata, specified for uploading does not exist: {config_name}"
)
headers = {"Content-Type": "application/json"}
params = {"access_token": os.getenv("ZENODO_ACCESS_TOKEN", "")}
r = requests.post(
zenodo_server,
params=params,
json={},
headers=headers,
)
if r.status_code != 201:
raise RuntimeError(f"The status code for the request is {r.status_code}.\nMessage: {r.text}")
return_json = r.json()
deposition_id = return_json["id"]
bucket_url = return_json["links"]["bucket"]
filebase = os.path.basename(file_name_to_upload)
file_url = return_json["links"]["html"].replace('deposit', 'record')
print(f"Uploading {filename} to Zenodo. This may take some time...")
with open(filename, "rb") as fp:
r = requests.put(f"{bucket_url}/{filebase}", data=fp, params=params)
if r.status_code != 200:
raise RuntimeError(f"The status code for the request is {r.status_code}.\nMessage: {r.text}")
print(f"\nFile Uploaded successfully!\nFile link: {file_url}")
print(f"Uploading metadata for {filename} ...")
with open(config_file) as fp:
data = yaml.safe_load(fp)
r = requests.put(
f"{zenodo_server}/{deposition_id}",
params=params,
data=json.dumps(data["zenodo_metadata"]),
headers=headers,
)
if r.status_code != 200:
raise RuntimeError(f"The status code for the request is {r.status_code}.\nMessage: {r.text}")
print(f"Publishing {filebase}...")
r = requests.post(f"{zenodo_server}/{deposition_id}/actions/publish", params=params)
if r.status_code != 202:
raise RuntimeError(f"The status code for the request is {r.status_code}.\nMessage: {r.text}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=("Upload files to Zenodo."))
parser.add_argument(
"-f", "--file", dest="file_name_to_upload", help="path to the file to be uploaded",
)
parser.add_argument(
"-c", "--config-file", dest="config_file", help="config file with metadata information"
)
args = parser.parse_args()
upload_to_zenodo(args.file_name_to_upload, args.config_file)
|
[] |
[] |
[
"ZENODO_ACCESS_TOKEN"
] |
[]
|
["ZENODO_ACCESS_TOKEN"]
|
python
| 1 | 0 | |
src/lib/kombi/Task/ImageSequence/FFmpegTask.py
|
import os
import subprocess
from collections import OrderedDict
from ..Task import Task
class FFmpegTask(Task):
"""
Abstracted ffmpeg task.
Options:
- optional: scale (float), videoCoded, pixelFormat and bitRate
- required: sourceColorSpace, targetColorSpace and frameRate (float)
"""
__ffmpegExecutable = os.environ.get('KOMBI_FFMPEG_EXECUTABLE', 'ffmpeg')
__defaultScale = 1.0
__defaultVideoCodec = "libx264"
__defaultPixelFormat = "yuvj420p"
__defaultBitRate = 115
def __init__(self, *args, **kwargs):
"""
Create a ffmpeg object.
"""
super(FFmpegTask, self).__init__(*args, **kwargs)
self.setOption('scale', self.__defaultScale)
self.setOption('videoCodec', self.__defaultVideoCodec)
self.setOption('pixelFormat', self.__defaultPixelFormat)
self.setOption('bitRate', self.__defaultBitRate)
def _perform(self):
"""
Perform the task.
"""
# collecting all crawlers that have the same target file path
movFiles = OrderedDict()
for crawler in self.crawlers():
targetFilePath = self.target(crawler)
if targetFilePath not in movFiles:
movFiles[targetFilePath] = []
movFiles[targetFilePath].append(crawler)
# calling ffmpeg
for movFile in movFiles.keys():
sequenceCrawlers = movFiles[movFile]
crawler = sequenceCrawlers[0]
# executing ffmpeg
self.__executeFFmpeg(
sequenceCrawlers,
movFile
)
# default result based on the target filePath
return super(FFmpegTask, self)._perform()
def __executeFFmpeg(self, sequenceCrawlers, outputFilePath):
"""
Execute ffmpeg.
"""
crawler = sequenceCrawlers[0]
startFrame = crawler.var('frame')
# building an image sequence name that ffmpeg understands that is a file
# sequence (aka foo.%04d.ext)
inputSequence = os.path.join(
os.path.dirname(crawler.var('filePath')),
'{name}.%0{padding}d.{ext}'.format(
name=crawler.var('name'),
padding=crawler.var('padding'),
ext=crawler.var('ext')
)
)
# trying to create the directory automatically in case it
# does not exist yet
try:
os.makedirs(
os.path.dirname(
outputFilePath
)
)
except OSError:
pass
# arguments passed to ffmpeg
arguments = [
# error level
'-loglevel error',
# frame rate
'-framerate {0}'.format(
self.option('frameRate')
),
# start frame
'-start_number {0}'.format(
startFrame
),
# input sequence
'-i "{0}"'.format(
inputSequence
),
# video codec
'-vcodec {0}'.format(
self.option('videoCodec')
),
# bit rate
'-b {0}M -minrate {0}M -maxrate {0}M'.format(
self.option('bitRate')
),
# target color
'-color_primaries {0}'.format(
self.option('targetColorSpace')
),
'-colorspace {0}'.format(
self.option('targetColorSpace')
),
# source color
'-color_trc {0}'.format(
self.option('sourceColorSpace')
),
# pixel format
'-pix_fmt {0}'.format(
self.option('pixelFormat')
),
# scale (default 1.0)
'-vf scale=iw*{0}:ih*{0}'.format(
self.option('scale')
),
# target mov file
'-y "{0}"'.format(
outputFilePath
)
]
# ffmpeg command
ffmpegCommand = '{} {}'.format(
self.__ffmpegExecutable,
' '.join(arguments),
)
# calling ffmpeg
process = subprocess.Popen(
ffmpegCommand,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ,
shell=True
)
# capturing the output
output, error = process.communicate()
# in case of any errors
if error:
raise Exception(error)
# registering task
Task.register(
'ffmpeg',
FFmpegTask
)
|
[] |
[] |
[
"KOMBI_FFMPEG_EXECUTABLE"
] |
[]
|
["KOMBI_FFMPEG_EXECUTABLE"]
|
python
| 1 | 0 | |
termenv.go
|
package termenv
import (
"errors"
"os"
"github.com/mattn/go-isatty"
)
var (
// ErrStatusReport gets returned when the terminal can't be queried.
ErrStatusReport = errors.New("unable to retrieve status report")
)
// Profile is a color profile: Ascii, ANSI, ANSI256, or TrueColor.
type Profile int
const (
// Control Sequence Introducer
CSI = "\x1b["
// Operating System Command
OSC = "\x1b]"
// Ascii, uncolored profile.
Ascii = Profile(iota) //nolint:revive
// ANSI, 4-bit color profile
ANSI
// ANSI256, 8-bit color profile
ANSI256
// TrueColor, 24-bit color profile
TrueColor
)
func isTTY(fd uintptr) bool {
if len(os.Getenv("CI")) > 0 {
return false
}
return isatty.IsTerminal(fd)
}
// ColorProfile returns the supported color profile:
// Ascii, ANSI, ANSI256, or TrueColor.
func ColorProfile() Profile {
if !isTTY(os.Stdout.Fd()) {
return Ascii
}
return colorProfile()
}
// ForegroundColor returns the terminal's default foreground color.
func ForegroundColor() Color {
if !isTTY(os.Stdout.Fd()) {
return NoColor{}
}
return foregroundColor()
}
// BackgroundColor returns the terminal's default background color.
func BackgroundColor() Color {
if !isTTY(os.Stdout.Fd()) {
return NoColor{}
}
return backgroundColor()
}
// HasDarkBackground returns whether terminal uses a dark-ish background.
func HasDarkBackground() bool {
c := ConvertToRGB(BackgroundColor())
_, _, l := c.Hsl()
return l < 0.5
}
// EnvNoColor returns true if the environment variables explicitly disable color output
// by setting NO_COLOR (https://no-color.org/)
// or CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/)
// If NO_COLOR is set, this will return true, ignoring CLICOLOR/CLICOLOR_FORCE
// If CLICOLOR=="0", it will be true only if CLICOLOR_FORCE is also "0" or is unset.
func EnvNoColor() bool {
return os.Getenv("NO_COLOR") != "" || (os.Getenv("CLICOLOR") == "0" && !cliColorForced())
}
// EnvColorProfile returns the color profile based on environment variables set
// Supports NO_COLOR (https://no-color.org/)
// and CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/)
// If none of these environment variables are set, this behaves the same as ColorProfile()
// It will return the Ascii color profile if EnvNoColor() returns true
// If the terminal does not support any colors, but CLICOLOR_FORCE is set and not "0"
// then the ANSI color profile will be returned.
func EnvColorProfile() Profile {
if EnvNoColor() {
return Ascii
}
p := ColorProfile()
if cliColorForced() && p == Ascii {
return ANSI
}
return p
}
func cliColorForced() bool {
if forced := os.Getenv("CLICOLOR_FORCE"); forced != "" {
return forced != "0"
}
return false
}
|
[
"\"CI\"",
"\"NO_COLOR\"",
"\"CLICOLOR\"",
"\"CLICOLOR_FORCE\""
] |
[] |
[
"CLICOLOR_FORCE",
"CLICOLOR",
"CI",
"NO_COLOR"
] |
[]
|
["CLICOLOR_FORCE", "CLICOLOR", "CI", "NO_COLOR"]
|
go
| 4 | 0 | |
target_s3_csv/s3.py
|
#!/usr/bin/env python3
import os
import backoff
import boto3
import singer
from botocore.exceptions import ClientError
LOGGER = singer.get_logger('target_s3_csv')
def retry_pattern():
return backoff.on_exception(backoff.expo,
ClientError,
max_tries=5,
on_backoff=log_backoff_attempt,
factor=10)
def log_backoff_attempt(details):
LOGGER.info("Error detected communicating with Amazon, triggering backoff: %d try", details.get("tries"))
@retry_pattern()
def create_client(config):
LOGGER.info("Attempting to create AWS session")
# Get the required parameters from config file and/or environment variables
aws_access_key_id = config.get('aws_access_key_id') or os.environ.get('AWS_ACCESS_KEY_ID')
aws_secret_access_key = config.get('aws_secret_access_key') or os.environ.get('AWS_SECRET_ACCESS_KEY')
aws_session_token = config.get('aws_session_token') or os.environ.get('AWS_SESSION_TOKEN')
aws_profile = config.get('aws_profile') or os.environ.get('AWS_PROFILE')
# AWS credentials based authentication
if aws_access_key_id and aws_secret_access_key:
aws_session = boto3.session.Session(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token
)
# AWS Profile based authentication
else:
aws_session = boto3.session.Session(profile_name=aws_profile)
return aws_session.client('s3')
# pylint: disable=too-many-arguments
@retry_pattern()
def upload_file(filename, s3_client, bucket, s3_key,
encryption_type=None, encryption_key=None):
if encryption_type is None or encryption_type.lower() == "none":
# No encryption config (defaults to settings on the bucket):
encryption_desc = ""
encryption_args = None
else:
if encryption_type.lower() == "kms":
encryption_args = {"ServerSideEncryption": "aws:kms"}
if encryption_key:
encryption_desc = (
" using KMS encryption key ID '{}'"
.format(encryption_key)
)
encryption_args["SSEKMSKeyId"] = encryption_key
else:
encryption_desc = " using default KMS encryption"
else:
raise NotImplementedError(
"Encryption type '{}' is not supported. "
"Expected: 'none' or 'KMS'"
.format(encryption_type)
)
LOGGER.info(
"Uploading {} to bucket {} at {}{}"
.format(filename, bucket, s3_key, encryption_desc)
)
s3_client.upload_file(filename, bucket, s3_key, ExtraArgs=encryption_args)
os.remove(filename)
|
[] |
[] |
[
"AWS_PROFILE",
"AWS_SESSION_TOKEN",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY"
] |
[]
|
["AWS_PROFILE", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"]
|
python
| 4 | 0 | |
cloud/edgecontroller/pkg/controller/utils/kubeclient.go
|
package utils
import (
"github.com/kubeedge/kubeedge/common/beehive/pkg/common/log"
"k8s.io/client-go/kubernetes"
)
// KubeClient from config
func KubeClient() (*kubernetes.Clientset, error) {
kubeConfig, err := KubeConfig()
if err != nil {
log.LOGGER.Warnf("get kube config failed with error: %s", err)
return nil, err
}
return kubernetes.NewForConfig(kubeConfig)
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
dev/dev_runner.py
|
#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
import time
from spinnaker.configurator import InstallationParameters
from spinnaker.fetch import AWS_METADATA_URL
from spinnaker.fetch import GOOGLE_METADATA_URL
from spinnaker.fetch import GOOGLE_INSTANCE_METADATA_URL
from spinnaker.fetch import is_aws_instance
from spinnaker.fetch import is_google_instance
from spinnaker.fetch import check_fetch
from spinnaker.fetch import fetch
from spinnaker.run import run_quick
from spinnaker.yaml_util import YamlBindings
from spinnaker.validate_configuration import ValidateConfig
from spinnaker import spinnaker_runner
def populate_aws_yml(content):
aws_dict = {'enabled': False}
if is_aws_instance():
zone = (check_fetch(AWS_METADATA_URL + '/placement/availability-zone')
.content)
aws_dict['enabled'] = 'true'
aws_dict['defaultRegion'] = zone[:-1]
elif os.path.exists(os.path.join(os.environ['HOME'], '.aws/credentials')):
aws_dict['enabled'] = 'true'
aws_dict['defaultRegion'] = 'us-east-1'
bindings = YamlBindings()
bindings.import_dict({'providers': {'aws': aws_dict}})
content = bindings.transform_yaml_source(content, 'providers.aws.enabled')
content = bindings.transform_yaml_source(content,
'providers.aws.defaultRegion')
return content
def populate_google_yml(content):
credentials = {'project': '', 'jsonPath': ''}
google_dict = {'enabled': False,
'defaultRegion': 'us-central1',
'defaultZone': 'us-central1-f',}
google_dict['primaryCredentials'] = credentials
front50_dict = {}
if is_google_instance():
zone = os.path.basename(
check_fetch(GOOGLE_INSTANCE_METADATA_URL + '/zone',
google=True).content)
google_dict['enabled'] = 'true'
google_dict['defaultRegion'] = zone[:-2]
google_dict['defaultZone'] = zone
credentials['project'] = check_fetch(
GOOGLE_METADATA_URL + '/project/project-id', google=True).content
front50_dict['storage_bucket'] = '${{{env}:{default}}}'.format(
env='SPINNAKER_DEFAULT_STORAGE_BUCKET',
default=credentials['project'].replace(':', '-').replace('.', '-'))
bindings = YamlBindings()
bindings.import_dict({'providers': {'google': google_dict}})
bindings.import_dict({'services': {'front50': front50_dict}})
content = bindings.transform_yaml_source(content, 'providers.google.enabled')
content = bindings.transform_yaml_source(
content, 'providers.google.defaultRegion')
content = bindings.transform_yaml_source(
content, 'providers.google.defaultZone')
content = bindings.transform_yaml_source(
content, 'providers.google.primaryCredentials.project')
content = bindings.transform_yaml_source(
content, 'providers.google.primaryCredentials.jsonPath')
content = bindings.transform_yaml_source(
content, 'services.front50.storage_bucket')
return content
class DevInstallationParameters(InstallationParameters):
"""Specialization of the normal production InstallationParameters.
This is a developer deployment where the paths are setup to run directly
out of this repository rather than a standard system installation.
Also, custom configuration parameters come from the $HOME/.spinnaker
rather than the normal installation location of /opt/spinnaker/config.
"""
DEV_SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
SUBSYSTEM_ROOT_DIR = os.getcwd()
USER_CONFIG_DIR = os.path.join(os.environ['HOME'], '.spinnaker')
LOG_DIR = os.path.join(SUBSYSTEM_ROOT_DIR, 'logs')
SPINNAKER_INSTALL_DIR = os.path.abspath(
os.path.join(DEV_SCRIPT_DIR, '..'))
INSTALLED_CONFIG_DIR = os.path.abspath(
os.path.join(DEV_SCRIPT_DIR, '../config'))
UTILITY_SCRIPT_DIR = os.path.abspath(
os.path.join(DEV_SCRIPT_DIR, '../runtime'))
EXTERNAL_DEPENDENCY_SCRIPT_DIR = os.path.abspath(
os.path.join(DEV_SCRIPT_DIR, '../runtime'))
DECK_INSTALL_DIR = os.path.join(SUBSYSTEM_ROOT_DIR, 'deck')
HACK_DECK_SETTINGS_FILENAME = 'settings.js'
DECK_PORT = 9000
class DevRunner(spinnaker_runner.Runner):
"""Specialization of the normal spinnaker runner for development use.
This class has different behaviors than the normal runner.
It follows similar heuristics for launching and stopping jobs,
however, the details differ in fundamental ways.
* The subsystems are run from their source (using gradle)
and will attempt to rebuild before running.
* Spinnaker will be reconfigured on each invocation.
The runner will display all the events to the subsystem error logs
to the console for as long as this script is running. When the script
terminates, the console will no longer show the error log, but the processes
will remain running, and continue logging to the logs directory.
"""
@staticmethod
def maybe_generate_clean_user_local():
"""Generate a spinnaker-local.yml file without environment variables refs"""
user_dir = DevInstallationParameters.USER_CONFIG_DIR
user_config_path = os.path.join(user_dir, 'spinnaker-local.yml')
if os.path.exists(user_config_path):
return
if not os.path.exists(user_dir):
os.mkdir(user_dir)
with open('{config_dir}/default-spinnaker-local.yml'.format(
config_dir=DevInstallationParameters.INSTALLED_CONFIG_DIR),
'r') as f:
content = f.read()
content = populate_aws_yml(content)
content = populate_google_yml(content)
with open(user_config_path, 'w') as f:
f.write(content)
os.chmod(user_config_path, 0600)
change_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
'install', 'change_cassandra.sh')
got = run_quick(change_path
+ ' --echo=inMemory --front50=gcs'
+ ' --change_defaults=false --change_local=true',
echo=False)
def __init__(self, installation_parameters=None):
self.maybe_generate_clean_user_local()
installation = installation_parameters or DevInstallationParameters
super(DevRunner, self).__init__(installation)
def start_subsystem(self, subsystem, environ=None):
"""Starts the specified subsystem.
Args:
subsystem [string]: The repository name of the subsystem to run.
"""
print 'Starting {subsystem}'.format(subsystem=subsystem)
command = os.path.join(
self.installation.SUBSYSTEM_ROOT_DIR,
subsystem,
'start_dev.sh')
return self.run_daemon(command, [command], environ=environ)
def tail_error_logs(self):
"""Start a background tail job of all the component error logs."""
log_dir = self.installation.LOG_DIR
try:
os.makedirs(log_dir)
except OSError:
pass
tail_jobs = []
for subsystem in self.get_all_subsystem_names():
path = os.path.join(log_dir, subsystem + '.err')
if not os.path.exists(path):
open(path, 'w').close()
tail_jobs.append(self.start_tail(path))
return tail_jobs
def get_deck_pid(self):
"""Return the process id for deck, or None."""
program='deck/node_modules/.bin/webpack-dev-server'
stdout, stderr = subprocess.Popen(
'ps -fwwwC node', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, close_fds=True).communicate()
match = re.search('(?m)^[^ ]+ +([0-9]+) .*/{program}'.format(
program=program), stdout)
return int(match.group(1)) if match else None
def start_deck(self):
"""Start subprocess for deck."""
pid = self.get_deck_pid()
if pid:
print 'Deck is already running as pid={pid}'.format(pid=pid)
return pid
path = os.path.join(self.installation.SUBSYSTEM_ROOT_DIR,
'deck/start_dev.sh')
return self.run_daemon(path, [path])
def stop_deck(self):
"""Stop subprocess for deck."""
pid = self.get_deck_pid()
if pid:
print 'Terminating deck in pid={pid}'.format(pid=pid)
os.kill(pid, signal.SIGTERM)
else:
print 'deck was not running'
def start_all(self, options):
"""Starts all the components then logs stderr to the console forever.
The subsystems are in forked processes disassociated from this, so will
continue running even after this process exists. Only the stderr logging
to console will stop once this process is terminated. However, the
logging will still continue into the LOG_DIR.
"""
ValidateConfig(self.configurator).check_validate()
self.configurator.update_deck_settings()
ignore_tail_jobs = self.tail_error_logs()
super(DevRunner, self).start_all(options)
deck_port = self.installation.DECK_PORT
print 'Waiting for deck to start on port {port}'.format(port=deck_port)
# Tail the log file while we wait and run.
# But the log file might not yet exist if deck hasn't started yet.
# So wait for the log file to exist before starting to tail it.
# Deck cant be ready yet if it hasn't started yet anyway.
deck_log_path = os.path.join(self.installation.LOG_DIR, 'deck.log')
while not os.path.exists(deck_log_path):
time.sleep(0.1)
ignore_tail_jobs.append(self.start_tail(deck_log_path))
# Don't just wait for port to be ready, but for deck to respond
# because it takes a long time to startup once port is ready.
while True:
code, ignore = fetch('http://localhost:{port}/'.format(port=deck_port))
if code == 200:
break
else:
time.sleep(0.1)
print """Spinnaker is now ready on port {port}.
You can ^C (ctrl-c) to finish the script, which will stop emitting errors.
Spinnaker will continue until you run ./spinnaker/dev/stop_dev.sh
""".format(port=deck_port)
while True:
time.sleep(3600)
def program_to_subsystem(self, program):
return program
def subsystem_to_program(self, subsystem):
return subsystem
if __name__ == '__main__':
if not os.path.exists('deck'):
sys.stderr.write('This script needs to be run from the root of'
' your build directory.\n')
sys.exit(-1)
DevRunner.main()
|
[] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
python
| 1 | 0 | |
test/integration/maincluster_test.go
|
package integration
import (
"fmt"
"log"
"os"
"reflect"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/kubernetes-incubator/kube-aws/builtin"
"github.com/kubernetes-incubator/kube-aws/cfnstack"
"github.com/kubernetes-incubator/kube-aws/core/root"
"github.com/kubernetes-incubator/kube-aws/core/root/config"
"github.com/kubernetes-incubator/kube-aws/pkg/api"
"github.com/kubernetes-incubator/kube-aws/pkg/model"
"github.com/kubernetes-incubator/kube-aws/test/helper"
)
type ConfigTester func(c *config.Config, t *testing.T)
type ClusterTester func(c *root.Cluster, t *testing.T)
// Integration testing with real AWS services including S3, KMS, CloudFormation
func TestMainClusterConfig(t *testing.T) {
kubeAwsSettings := newKubeAwsSettingsFromEnv(t)
s3URI, s3URIExists := os.LookupEnv("KUBE_AWS_S3_DIR_URI")
if !s3URIExists || s3URI == "" {
s3URI = "s3://mybucket/mydir"
t.Logf(`Falling back s3URI to a stub value "%s" for tests of validating stack templates. No assets will actually be uploaded to S3`, s3URI)
} else {
log.Printf("s3URI is %s", s3URI)
}
s3Loc, err := cfnstack.S3URIFromString(s3URI)
if err != nil {
t.Errorf("failed to parse s3 uri: %v", err)
t.FailNow()
}
s3Bucket := s3Loc.Bucket()
s3Dir := s3Loc.KeyComponents()[0]
firstAz := kubeAwsSettings.region + "c"
hasDefaultEtcdSettings := func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
Tenancy: "default",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
}
hasDefaultExperimentalFeatures := func(c *config.Config, t *testing.T) {
expected := api.Experimental{
Admission: api.Admission{
AlwaysPullImages: api.AlwaysPullImages{
Enabled: false,
},
EventRateLimit: api.EventRateLimit{
Enabled: true,
Limits: `- type: Namespace
qps: 250
burst: 500
cacheSize: 4096
- type: User
qps: 50
burst: 250`,
},
},
AuditLog: api.AuditLog{
Enabled: false,
LogPath: "/var/log/kube-apiserver-audit.log",
MaxAge: 30,
MaxBackup: 1,
MaxSize: 100,
},
Authentication: api.Authentication{
Webhook: api.Webhook{
Enabled: false,
CacheTTL: "5m0s",
Config: "",
},
},
AwsEnvironment: api.AwsEnvironment{
Enabled: false,
},
AwsNodeLabels: api.AwsNodeLabels{
Enabled: false,
},
EphemeralImageStorage: api.EphemeralImageStorage{
Enabled: false,
Disk: "xvdb",
Filesystem: "xfs",
},
GpuSupport: api.GpuSupport{
Enabled: false,
Version: "",
InstallImage: "shelmangroup/coreos-nvidia-driver-installer:latest",
},
LoadBalancer: api.LoadBalancer{
Enabled: false,
},
Oidc: api.Oidc{
Enabled: false,
IssuerUrl: "https://accounts.google.com",
ClientId: "kubernetes",
UsernameClaim: "email",
GroupsClaim: "groups",
},
CloudControllerManager: api.CloudControllerManager{
Enabled: false,
},
ContainerStorageInterface: api.ContainerStorageInterface{
Enabled: false,
CSIProvisioner: api.Image{
Repo: "quay.io/k8scsi/csi-provisioner",
Tag: api.CSIDefaultProvisionerImageTag,
},
CSIAttacher: api.Image{
Repo: "quay.io/k8scsi/csi-attacher",
Tag: api.CSIDefaultAttacherImageTag,
},
CSILivenessProbe: api.Image{
Repo: "quay.io/k8scsi/livenessprobe",
Tag: api.CSIDefaultLivenessProbeImageTag,
},
CSINodeDriverRegistrar: api.Image{
Repo: "quay.io/k8scsi/csi-node-driver-registrar",
Tag: api.CSIDefaultNodeDriverRegistrarTag,
},
AmazonEBSDriver: api.Image{
Repo: "amazon/aws-ebs-csi-driver",
Tag: api.CSIDefaultAmazonEBSDriverImageTag,
},
},
NodeDrainer: api.NodeDrainer{
Enabled: false,
DrainTimeout: 5,
},
}
actual := c.Experimental
if !reflect.DeepEqual(expected, actual) {
t.Errorf("experimental settings didn't match :\nexpected=%v\nactual=%v", expected, actual)
}
if !c.WaitSignal.Enabled() {
t.Errorf("waitSignal should be enabled but was not: %v", c.WaitSignal)
}
if c.WaitSignal.MaxBatchSize(1) != 1 {
t.Errorf("waitSignal.maxBatchSize should be 1 but was %d: %v", c.WaitSignal.MaxBatchSize(1), c.WaitSignal)
}
}
everyPublicSubnetHasRouteToIGW := func(c *config.Config, t *testing.T) {
for i, s := range c.PublicSubnets() {
if !s.ManageRouteToInternet() {
t.Errorf("Public subnet %d should have a route to the IGW but it doesn't: %+v", i, s)
}
}
}
hasDefaultLaunchSpecifications := func(c *config.Config, t *testing.T) {
expected := []api.LaunchSpecification{
{
WeightedCapacity: 1,
InstanceType: "c4.large",
SpotPrice: "",
RootVolume: api.NewGp2RootVolume(30),
},
{
WeightedCapacity: 2,
InstanceType: "c4.xlarge",
SpotPrice: "",
RootVolume: api.NewGp2RootVolume(60),
},
}
p := c.NodePools[0]
actual := p.WorkerNodePool.SpotFleet.LaunchSpecifications
if !reflect.DeepEqual(expected, actual) {
t.Errorf(
"LaunchSpecifications didn't match: expected=%v actual=%v",
expected,
actual,
)
}
globalSpotPrice := p.WorkerNodePool.SpotFleet.SpotPrice
if globalSpotPrice != "0.06" {
t.Errorf("Default spot price is expected to be 0.06 but was: %s", globalSpotPrice)
}
}
spotFleetBasedNodePoolHasWaitSignalDisabled := func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
if !p.SpotFleet.Enabled() {
t.Errorf("1st node pool is expected to be a spot fleet based one but was not: %+v", p)
}
if p.WaitSignal.Enabled() {
t.Errorf(
"WaitSignal should be enabled but was not: %v",
p.WaitSignal,
)
}
}
asgBasedNodePoolHasWaitSignalEnabled := func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
if p.SpotFleet.Enabled() {
t.Errorf("1st node pool is expected to be an asg-based one but was not: %+v", p)
}
if !p.WaitSignal.Enabled() {
t.Errorf(
"WaitSignal should be disabled but was not: %v",
p.WaitSignal,
)
}
}
hasDefaultNodePoolRollingStrategy := func(c *config.Config, t *testing.T) {
s := c.NodePools[0].NodePoolRollingStrategy
if s != "AvailabilityZone" {
t.Errorf("Default nodePool rolling strategy should be 'AvailabilityZone' but is not: %v", s)
}
}
hasSpecificNodePoolRollingStrategy := func(expRollingStrategy string) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
actRollingStrategy := c.NodePools[0].NodePoolRollingStrategy
if actRollingStrategy != expRollingStrategy {
t.Errorf("The nodePool Rolling Strategy (%s) does not match with the expected one: %s", actRollingStrategy, expRollingStrategy)
}
}
}
hasWorkerAndNodePoolStrategy := func(expWorkerStrategy, expNodePoolStrategy string) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
actWorkerStrategy := c.NodePools[0].NodePoolRollingStrategy
actNodePoolStrategy := c.NodePools[1].NodePoolRollingStrategy
if expWorkerStrategy != actWorkerStrategy {
t.Errorf("The nodePool Rolling Strategy (%s) does not match with the expected one: %s", actWorkerStrategy, expWorkerStrategy)
}
if expNodePoolStrategy != actNodePoolStrategy {
t.Errorf("The nodePool Rolling Strategy (%s) does not match with the expected one: %s", actNodePoolStrategy, expNodePoolStrategy)
}
}
}
hasPrivateSubnetsWithManagedNGWs := func(numExpectedNum int) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
for i, s := range c.PrivateSubnets() {
if !s.ManageNATGateway() {
t.Errorf("NAT gateway for the existing private subnet #%d should be created by kube-aws but was not", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
}
}
hasSpecificNumOfManagedNGWsWithUnmanagedEIPs := func(ngwExpectedNum int) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
ngwActualNum := len(c.NATGateways())
if ngwActualNum != ngwExpectedNum {
t.Errorf("Number of NAT gateways(%d) doesn't match with the expexted one: %d", ngwActualNum, ngwExpectedNum)
}
for i, n := range c.NATGateways() {
if !n.ManageNATGateway() {
t.Errorf("NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
if n.ManageEIP() {
t.Errorf("EIP for NGW #%d is expected to be unmanaged by kube-aws but was not: %+v", i, n)
}
if !n.ManageRoute() {
t.Errorf("Routes for NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
}
}
}
hasSpecificNumOfManagedNGWsAndEIPs := func(ngwExpectedNum int) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
ngwActualNum := len(c.NATGateways())
if ngwActualNum != ngwExpectedNum {
t.Errorf("Number of NAT gateways(%d) doesn't match with the expexted one: %d", ngwActualNum, ngwExpectedNum)
}
for i, n := range c.NATGateways() {
if !n.ManageNATGateway() {
t.Errorf("NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
if !n.ManageEIP() {
t.Errorf("EIP for NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
if !n.ManageRoute() {
t.Errorf("Routes for NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
}
}
}
hasTwoManagedNGWsAndEIPs := hasSpecificNumOfManagedNGWsAndEIPs(2)
hasNoManagedNGWsButSpecificNumOfRoutesToUnmanagedNGWs := func(ngwExpectedNum int) func(c *config.Config, t *testing.T) {
return func(c *config.Config, t *testing.T) {
ngwActualNum := len(c.NATGateways())
if ngwActualNum != ngwExpectedNum {
t.Errorf("Number of NAT gateways(%d) doesn't match with the expexted one: %d", ngwActualNum, ngwExpectedNum)
}
for i, n := range c.NATGateways() {
if n.ManageNATGateway() {
t.Errorf("NGW #%d is expected to be unmanaged by kube-aws but was not: %+v", i, n)
}
if n.ManageEIP() {
t.Errorf("EIP for NGW #%d is expected to be unmanaged by kube-aws but was not: %+v", i, n)
}
if !n.ManageRoute() {
t.Errorf("Routes for NGW #%d is expected to be managed by kube-aws but was not: %+v", i, n)
}
}
}
}
hasNoNGWsOrEIPsOrRoutes := func(c *config.Config, t *testing.T) {
ngwActualNum := len(c.NATGateways())
ngwExpectedNum := 0
if ngwActualNum != ngwExpectedNum {
t.Errorf("Number of NAT gateways(%d) doesn't match with the expexted one: %d", ngwActualNum, ngwExpectedNum)
}
}
hasDefaultCluster := func(c *root.Cluster, t *testing.T) {
assets, err := c.EnsureAllAssetsGenerated()
if err != nil {
t.Errorf("failed to list assets: %v", err)
t.FailNow()
}
t.Run("Assets/RootStackTemplate", func(t *testing.T) {
cluster := kubeAwsSettings.clusterName
stack := kubeAwsSettings.clusterName
file := "stack.json"
expected := api.Asset{
Content: "",
AssetLocation: api.AssetLocation{
ID: api.NewAssetID(stack, file),
Bucket: s3Bucket,
Key: s3Dir + "/kube-aws/clusters/" + cluster + "/exported/stacks/" + stack + "/" + file,
Path: stack + "/stack.json",
},
}
actual, err := assets.FindAssetByStackAndFileName(stack, file)
if err != nil {
t.Errorf("failed to find asset: %v", err)
}
if expected.ID != actual.ID {
t.Errorf(
"Asset id didn't match: expected=%v actual=%v",
expected.ID,
actual.ID,
)
}
if expected.Key != actual.Key {
t.Errorf(
"Asset key didn't match: expected=%v actual=%v",
expected.Key,
actual.Key,
)
}
})
t.Run("Assets/ControlplaneStackTemplate", func(t *testing.T) {
cluster := kubeAwsSettings.clusterName
stack := "control-plane"
file := "stack.json"
expected := api.Asset{
Content: builtin.String("stack-templates/control-plane.json.tmpl"),
AssetLocation: api.AssetLocation{
ID: api.NewAssetID(stack, file),
Bucket: s3Bucket,
Key: s3Dir + "/kube-aws/clusters/" + cluster + "/exported/stacks/" + stack + "/" + file,
Path: stack + "/stack.json",
},
}
actual, err := assets.FindAssetByStackAndFileName(stack, file)
if err != nil {
t.Errorf("failed to find asset: %v", err)
}
if expected.ID != actual.ID {
t.Errorf(
"Asset id didn't match: expected=%v actual=%v",
expected.ID,
actual.ID,
)
}
if expected.Key != actual.Key {
t.Errorf(
"Asset key didn't match: expected=%v actual=%v",
expected.Key,
actual.Key,
)
}
})
}
mainClusterYaml := kubeAwsSettings.mainClusterYaml()
minimalValidConfigYaml := kubeAwsSettings.minimumValidClusterYamlWithAZ("c")
configYamlWithoutExernalDNSName := kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
availabilityZone: us-west-1c
`
validCases := []struct {
context string
configYaml string
assertConfig []ConfigTester
assertCluster []ClusterTester
}{
{
context: "WithAddons",
configYaml: minimalValidConfigYaml + `
addons:
rescheduler:
enabled: true
metricsServer:
enabled: true
worker:
nodePools:
- name: pool1
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
asgBasedNodePoolHasWaitSignalEnabled,
func(c *config.Config, t *testing.T) {
expected := api.Addons{
Rescheduler: api.Rescheduler{
Enabled: true,
},
MetricsServer: api.MetricsServer{
Enabled: true,
},
APIServerAggregator: api.APIServerAggregator{
Enabled: true,
},
}
actual := c.Addons
if !reflect.DeepEqual(expected, actual) {
t.Errorf("addons didn't match : expected=%+v actual=%+v", expected, actual)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithAPIEndpointLBAPIAccessAllowedSourceCIDRsSpecified",
configYaml: configYamlWithoutExernalDNSName + `
apiEndpoints:
- name: default
dnsName: k8s.example.com
loadBalancer:
apiAccessAllowedSourceCIDRs:
- 1.2.3.255/32
hostedZone:
id: a1b2c4
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
l := len(c.APIEndpointConfigs[0].LoadBalancer.APIAccessAllowedSourceCIDRs)
if l != 1 {
t.Errorf("unexpected size of apiEndpoints[0].loadBalancer.apiAccessAllowedSourceCIDRs: %d", l)
t.FailNow()
}
actual := c.APIEndpointConfigs[0].LoadBalancer.APIAccessAllowedSourceCIDRs[0].String()
expected := "1.2.3.255/32"
if actual != expected {
t.Errorf("unexpected cidr in apiEndpoints[0].loadBalancer.apiAccessAllowedSourceCIDRs[0]. expected = %s, actual = %s", expected, actual)
}
},
},
},
{
context: "WithAPIEndpointLBAPIAccessAllowedSourceCIDRsOmitted",
configYaml: configYamlWithoutExernalDNSName + `
apiEndpoints:
- name: default
dnsName: k8s.example.com
loadBalancer:
hostedZone:
id: a1b2c4
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
l := len(c.APIEndpointConfigs[0].LoadBalancer.APIAccessAllowedSourceCIDRs)
if l != 1 {
t.Errorf("unexpected size of apiEndpoints[0].loadBalancer.apiAccessAllowedSourceCIDRs: %d", l)
t.FailNow()
}
actual := c.APIEndpointConfigs[0].LoadBalancer.APIAccessAllowedSourceCIDRs[0].String()
expected := "0.0.0.0/0"
if actual != expected {
t.Errorf("unexpected cidr in apiEndpoints[0].loadBalancer.apiAccessAllowedSourceCIDRs[0]. expected = %s, actual = %s", expected, actual)
}
},
},
},
{
context: "WithKubeProxyIPVSModeDisabledByDefault",
configYaml: minimalValidConfigYaml,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if c.KubeProxy.IPVSMode.Enabled != false {
t.Errorf("kube-proxy IPVS mode must be disabled by default")
}
expectedScheduler := "rr"
if c.KubeProxy.IPVSMode.Scheduler != expectedScheduler {
t.Errorf("IPVS scheduler should be by default set to: %s (actual = %s)", expectedScheduler, c.KubeProxy.IPVSMode.Scheduler)
}
expectedSyncPeriod := "60s"
if c.KubeProxy.IPVSMode.SyncPeriod != expectedSyncPeriod {
t.Errorf("Sync period should be by default set to: %s (actual = %s)", expectedSyncPeriod, c.KubeProxy.IPVSMode.SyncPeriod)
}
expectedMinSyncPeriod := "10s"
if c.KubeProxy.IPVSMode.MinSyncPeriod != expectedMinSyncPeriod {
t.Errorf("Minimal sync period should be by default set to: %s (actual = %s)", expectedMinSyncPeriod, c.KubeProxy.IPVSMode.MinSyncPeriod)
}
},
},
},
{
context: "WithKubeProxyIPVSModeEnabled",
configYaml: minimalValidConfigYaml + `
kubeProxy:
ipvsMode:
enabled: true
scheduler: lc
syncPeriod: 90s
minSyncPeriod: 15s
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if c.KubeProxy.IPVSMode.Enabled != true {
t.Errorf("kube-proxy IPVS mode must be enabled")
}
expectedScheduler := "lc"
if c.KubeProxy.IPVSMode.Scheduler != expectedScheduler {
t.Errorf("IPVS scheduler should be set to: %s (actual = %s)", expectedScheduler, c.KubeProxy.IPVSMode.Scheduler)
}
expectedSyncPeriod := "90s"
if c.KubeProxy.IPVSMode.SyncPeriod != expectedSyncPeriod {
t.Errorf("Sync period should be set to: %s (actual = %s)", expectedSyncPeriod, c.KubeProxy.IPVSMode.SyncPeriod)
}
expectedMinSyncPeriod := "15s"
if c.KubeProxy.IPVSMode.MinSyncPeriod != expectedMinSyncPeriod {
t.Errorf("Minimal sync period should be set to: %s (actual = %s)", expectedMinSyncPeriod, c.KubeProxy.IPVSMode.MinSyncPeriod)
}
},
},
},
{
// See https://github.com/kubernetes-incubator/kube-aws/issues/365
context: "WithClusterNameContainsHyphens",
configYaml: kubeAwsSettings.withClusterName("my-cluster").minimumValidClusterYaml(),
},
{
context: "WithcustomApiServerSettings",
configYaml: minimalValidConfigYaml + `
customApiServerSettings:
additionalDnsSans:
- my.host.com
additionalIPAddressSans:
- 0.0.0.0
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
expectedDnsSans := []string{"my.host.com"}
actualDnsSans := c.CustomApiServerSettings.AdditionalDnsSANs
if !reflect.DeepEqual(expectedDnsSans, actualDnsSans) {
t.Errorf("additionalDnsSans didn't match : expected=%v actual=%v", expectedDnsSans, actualDnsSans)
}
expectedIPSans := []string{"0.0.0.0"}
actualIPSans := c.CustomApiServerSettings.AdditionalIPAddresses
if !reflect.DeepEqual(expectedIPSans, actualIPSans) {
t.Errorf("additionalIPAddressSans didn't match : expected=%v actual=%v", expectedIPSans, actualIPSans)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithCustomSettings",
configYaml: minimalValidConfigYaml + `
customSettings:
stack-type: control-plane
worker:
nodePools:
- name: pool1
customSettings:
stack-type: node-pool
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
asgBasedNodePoolHasWaitSignalEnabled,
func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
{
expected := map[string]interface{}{
"stack-type": "control-plane",
}
actual := c.CustomSettings
if !reflect.DeepEqual(expected, actual) {
t.Errorf("customSettings didn't match : expected=%v actual=%v", expected, actual)
}
}
{
expected := map[string]interface{}{
"stack-type": "node-pool",
}
actual := p.CustomSettings
if !reflect.DeepEqual(expected, actual) {
t.Errorf("customSettings didn't match : expected=%v actual=%v", expected, actual)
}
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithDifferentReleaseChannels",
configYaml: minimalValidConfigYaml + `
releaseChannel: stable
worker:
nodePools:
- name: pool1
releaseChannel: alpha
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
asgBasedNodePoolHasWaitSignalEnabled,
},
assertCluster: []ClusterTester{
func(c *root.Cluster, t *testing.T) {
cp := c.ControlPlane().Config.AMI
np := c.NodePools()[0].NodePoolConfig.AMI
if cp == "" {
t.Error("the default AMI ID should not be empty but it was")
}
if np == "" {
t.Error("the AMI ID for the node pool should not be empty but it was")
}
if cp == np {
t.Errorf("the default AMI ID and the AMI ID for the node pool should not match but they did: default=%s, nodepool=%s", cp, np)
}
},
},
},
{
context: "WithElasticFileSystemId",
configYaml: minimalValidConfigYaml + `
elasticFileSystemId: efs-12345
worker:
nodePools:
- name: pool1
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if c.NodePools[0].ElasticFileSystemID != "efs-12345" {
t.Errorf("The value of worker.nodePools[0].elasticFileSystemId should match the one for the top-leve elasticFileSystemId, but it wan't: worker.nodePools[0].elasticFileSystemId=%s", c.NodePools[0].ElasticFileSystemID)
}
},
},
},
{
context: "WithElasticFileSystemIdInSpecificNodePool",
configYaml: mainClusterYaml + `
subnets:
- name: existing1
id: subnet-12345
availabilityZone: us-west-1a
worker:
nodePools:
- name: pool1
subnets:
- name: existing1
elasticFileSystemId: efs-12345
- name: pool2
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if c.NodePools[0].ElasticFileSystemID != "efs-12345" {
t.Errorf("Unexpected worker.nodePools[0].elasticFileSystemId: %s", c.NodePools[0].ElasticFileSystemID)
}
if c.NodePools[1].ElasticFileSystemID != "" {
t.Errorf("Unexpected worker.nodePools[1].elasticFileSystemId: %s", c.NodePools[1].ElasticFileSystemID)
}
},
},
},
{
context: "WithEtcdDataVolumeEncrypted",
configYaml: minimalValidConfigYaml + `
etcd:
dataVolume:
encrypted: true
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if !c.Etcd.DataVolume.Encrypted {
t.Errorf("Etcd data volume should be encrypted but was not: %v", c.Etcd)
}
},
},
},
{
context: "WithEtcdDataVolumeEncryptedKMSKeyARN",
configYaml: minimalValidConfigYaml + `
etcd:
dataVolume:
encrypted: true
kmsKeyArn: arn:aws:kms:eu-west-1:XXX:key/XXX
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
expected := "arn:aws:kms:eu-west-1:XXX:key/XXX"
if c.Etcd.KMSKeyARN() != expected {
t.Errorf("Etcd data volume KMS Key ARN didn't match : expected=%v actual=%v", expected, c.Etcd.KMSKeyARN())
}
if !c.Etcd.DataVolume.Encrypted {
t.Error("Etcd data volume should be encrypted but was not")
}
},
},
},
{
context: "WithEtcdMemberIdentityProviderEIP",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eip
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
MemberIdentityProvider: "eip",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
Tenancy: "default",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveEIP() {
t.Errorf(
"NodeShouldHaveEIP returned unexpected value: %v",
actual.NodeShouldHaveEIP(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENI",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Cluster: api.EtcdCluster{
MemberIdentityProvider: "eni",
Version: "v3.3.17",
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENIWithCustomDomain",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
internalDomainName: internal.example.com
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
MemberIdentityProvider: "eni",
InternalDomainName: "internal.example.com",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENIWithCustomFQDNs",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
internalDomainName: internal.example.com
nodes:
- fqdn: etcd1a.internal.example.com
- fqdn: etcd1b.internal.example.com
- fqdn: etcd1c.internal.example.com
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
MemberIdentityProvider: "eni",
InternalDomainName: "internal.example.com",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Nodes: []api.EtcdNode{
api.EtcdNode{
FQDN: "etcd1a.internal.example.com",
},
api.EtcdNode{
FQDN: "etcd1b.internal.example.com",
},
api.EtcdNode{
FQDN: "etcd1c.internal.example.com",
},
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENIWithCustomNames",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
internalDomainName: internal.example.com
nodes:
- name: etcd1a
- name: etcd1b
- name: etcd1c
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
MemberIdentityProvider: "eni",
InternalDomainName: "internal.example.com",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Nodes: []api.EtcdNode{
api.EtcdNode{
Name: "etcd1a",
},
api.EtcdNode{
Name: "etcd1b",
},
api.EtcdNode{
Name: "etcd1c",
},
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENIWithoutRecordSets",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
internalDomainName: internal.example.com
manageRecordSets: false
nodes:
- name: etcd1a
- name: etcd1b
- name: etcd1c
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
manageRecordSets := false
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
ManageRecordSets: &manageRecordSets,
MemberIdentityProvider: "eni",
InternalDomainName: "internal.example.com",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Nodes: []api.EtcdNode{
api.EtcdNode{
Name: "etcd1a",
},
api.EtcdNode{
Name: "etcd1b",
},
api.EtcdNode{
Name: "etcd1c",
},
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithEtcdMemberIdentityProviderENIWithHostedZoneID",
configYaml: minimalValidConfigYaml + `
etcd:
memberIdentityProvider: eni
internalDomainName: internal.example.com
hostedZone:
id: hostedzone-abcdefg
nodes:
- name: etcd1a
- name: etcd1b
- name: etcd1c
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnet(firstAz, "10.0.0.0/24")
subnet1.Name = "Subnet0"
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
HostedZone: api.Identifier{ID: "hostedzone-abcdefg"},
MemberIdentityProvider: "eni",
InternalDomainName: "internal.example.com",
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Nodes: []api.EtcdNode{
api.EtcdNode{
Name: "etcd1a",
},
api.EtcdNode{
Name: "etcd1b",
},
api.EtcdNode{
Name: "etcd1c",
},
},
Subnets: api.Subnets{
subnet1,
},
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if diff := cmp.Diff(actual, expected); diff != "" {
t.Errorf("EtcdSettings didn't match: %s", diff)
}
if !actual.NodeShouldHaveSecondaryENI() {
t.Errorf(
"NodeShouldHaveSecondaryENI returned unexpected value: %v",
actual.NodeShouldHaveSecondaryENI(),
)
}
},
},
assertCluster: []ClusterTester{
hasDefaultCluster,
},
},
{
context: "WithExperimentalFeatures",
configYaml: minimalValidConfigYaml + `
experimental:
admission:
alwaysPullImages:
enabled: true
auditLog:
enabled: true
logPath: "/var/log/audit.log"
maxAge: 100
maxBackup: 10
maxSize: 5
authentication:
webhook:
enabled: true
cacheTTL: "1234s"
configBase64: "e30k"
awsEnvironment:
enabled: true
environment:
CFNSTACK: '{ "Ref" : "AWS::StackId" }'
awsNodeLabels:
enabled: true
ephemeralImageStorage:
enabled: true
gpuSupport:
enabled: true
version: "375.66"
installImage: "shelmangroup/coreos-nvidia-driver-installer:latest"
kubeletOpts: '--image-gc-low-threshold 60 --image-gc-high-threshold 70'
loadBalancer:
enabled: true
names:
- manuallymanagedlb
securityGroupIds:
- sg-12345678
targetGroup:
enabled: true
arns:
- arn:aws:elasticloadbalancing:eu-west-1:xxxxxxxxxxxx:targetgroup/manuallymanagedetg/xxxxxxxxxxxxxxxx
securityGroupIds:
- sg-12345678
oidc:
enabled: true
oidc-issuer-url: "https://accounts.google.com"
oidc-client-id: "kubernetes"
oidc-username-claim: "email"
oidc-groups-claim: "groups"
nodeDrainer:
enabled: true
drainTimeout: 3
cloudWatchLogging:
enabled: true
amazonSsmAgent:
enabled: true
worker:
nodePools:
- name: pool1
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
asgBasedNodePoolHasWaitSignalEnabled,
func(c *config.Config, t *testing.T) {
expected := api.Experimental{
Admission: api.Admission{
AlwaysPullImages: api.AlwaysPullImages{
Enabled: true,
},
EventRateLimit: api.EventRateLimit{
Enabled: true,
Limits: `- type: Namespace
qps: 250
burst: 500
cacheSize: 4096
- type: User
qps: 50
burst: 250`,
},
},
AuditLog: api.AuditLog{
Enabled: true,
LogPath: "/var/log/audit.log",
MaxAge: 100,
MaxBackup: 10,
MaxSize: 5,
},
Authentication: api.Authentication{
Webhook: api.Webhook{
Enabled: true,
CacheTTL: "1234s",
Config: "e30k",
},
},
AwsEnvironment: api.AwsEnvironment{
Enabled: true,
Environment: map[string]string{
"CFNSTACK": `{ "Ref" : "AWS::StackId" }`,
},
},
AwsNodeLabels: api.AwsNodeLabels{
Enabled: true,
},
EphemeralImageStorage: api.EphemeralImageStorage{
Enabled: true,
Disk: "xvdb",
Filesystem: "xfs",
},
GpuSupport: api.GpuSupport{
Enabled: true,
Version: "375.66",
InstallImage: "shelmangroup/coreos-nvidia-driver-installer:latest",
},
KubeletOpts: "--image-gc-low-threshold 60 --image-gc-high-threshold 70",
LoadBalancer: api.LoadBalancer{
Enabled: true,
Names: []string{"manuallymanagedlb"},
SecurityGroupIds: []string{"sg-12345678"},
},
TargetGroup: api.TargetGroup{
Enabled: true,
Arns: []string{"arn:aws:elasticloadbalancing:eu-west-1:xxxxxxxxxxxx:targetgroup/manuallymanagedetg/xxxxxxxxxxxxxxxx"},
SecurityGroupIds: []string{"sg-12345678"},
},
Oidc: api.Oidc{
Enabled: true,
IssuerUrl: "https://accounts.google.com",
ClientId: "kubernetes",
UsernameClaim: "email",
GroupsClaim: "groups",
},
CloudControllerManager: api.CloudControllerManager{
Enabled: false,
},
ContainerStorageInterface: api.ContainerStorageInterface{
Enabled: false,
CSIProvisioner: api.Image{
Repo: "quay.io/k8scsi/csi-provisioner",
Tag: api.CSIDefaultProvisionerImageTag,
},
CSIAttacher: api.Image{
Repo: "quay.io/k8scsi/csi-attacher",
Tag: api.CSIDefaultAttacherImageTag,
},
CSILivenessProbe: api.Image{
Repo: "quay.io/k8scsi/livenessprobe",
Tag: api.CSIDefaultLivenessProbeImageTag,
},
CSINodeDriverRegistrar: api.Image{
Repo: "quay.io/k8scsi/csi-node-driver-registrar",
Tag: api.CSIDefaultNodeDriverRegistrarTag,
},
AmazonEBSDriver: api.Image{
Repo: "amazon/aws-ebs-csi-driver",
Tag: api.CSIDefaultAmazonEBSDriverImageTag,
},
},
NodeDrainer: api.NodeDrainer{
Enabled: true,
DrainTimeout: 3,
},
}
actual := c.Experimental
if !reflect.DeepEqual(expected, actual) {
t.Errorf("experimental settings didn't match : expected=%+v actual=%+v", expected, actual)
}
p := c.NodePools[0]
if reflect.DeepEqual(expected, p.Experimental) {
t.Errorf("experimental settings shouldn't be inherited to a node pool but it did : toplevel=%v nodepool=%v", expected, p.Experimental)
}
},
},
},
{
context: "WithExperimentalFeaturesForWorkerNodePool",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
auditLog:
enabled: true
maxage: 100
logpath: "/var/log/audit.log"
awsEnvironment:
enabled: true
environment:
CFNSTACK: '{ "Ref" : "AWS::StackId" }'
awsNodeLabels:
enabled: true
ephemeralImageStorage:
enabled: true
loadBalancer:
enabled: true
names:
- manuallymanagedlb
securityGroupIds:
- sg-12345678
targetGroup:
enabled: true
arns:
- arn:aws:elasticloadbalancing:eu-west-1:xxxxxxxxxxxx:targetgroup/manuallymanagedetg/xxxxxxxxxxxxxxxx
securityGroupIds:
- sg-12345678
# Ignored, uses global setting
nodeDrainer:
enabled: true
drainTimeout: 5
nodeLabels:
kube-aws.coreos.com/role: worker
taints:
- key: reservation
value: spot
effect: NoSchedule
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
asgBasedNodePoolHasWaitSignalEnabled,
func(c *config.Config, t *testing.T) {
expected := api.Experimental{
AwsEnvironment: api.AwsEnvironment{
Enabled: true,
Environment: map[string]string{
"CFNSTACK": `{ "Ref" : "AWS::StackId" }`,
},
},
AwsNodeLabels: api.AwsNodeLabels{
Enabled: true,
},
EphemeralImageStorage: api.EphemeralImageStorage{
Enabled: true,
Disk: "xvdb",
Filesystem: "xfs",
},
LoadBalancer: api.LoadBalancer{
Enabled: true,
Names: []string{"manuallymanagedlb"},
SecurityGroupIds: []string{"sg-12345678"},
},
TargetGroup: api.TargetGroup{
Enabled: true,
Arns: []string{"arn:aws:elasticloadbalancing:eu-west-1:xxxxxxxxxxxx:targetgroup/manuallymanagedetg/xxxxxxxxxxxxxxxx"},
SecurityGroupIds: []string{"sg-12345678"},
},
NodeDrainer: api.NodeDrainer{
Enabled: false,
DrainTimeout: 0,
},
}
p := c.NodePools[0]
if reflect.DeepEqual(expected, p.Experimental) {
t.Errorf("experimental settings for node pool didn't match : expected=%v actual=%v", expected, p.Experimental)
}
expectedNodeLabels := api.NodeLabels{
"kube-aws.coreos.com/role": "worker",
}
actualNodeLabels := c.NodePools[0].NodeLabels()
if !reflect.DeepEqual(expectedNodeLabels, actualNodeLabels) {
t.Errorf("worker node labels didn't match: expected=%v, actual=%v", expectedNodeLabels, actualNodeLabels)
}
expectedTaints := api.Taints{
{Key: "reservation", Value: "spot", Effect: "NoSchedule"},
}
actualTaints := c.NodePools[0].Taints
if !reflect.DeepEqual(expectedTaints, actualTaints) {
t.Errorf("worker node taints didn't match: expected=%v, actual=%v", expectedTaints, actualTaints)
}
},
},
},
{
context: "WithControllerIAMDefaultManageExternally",
configYaml: minimalValidConfigYaml,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
expectedValue := false
if c.Controller.IAMConfig.Role.ManageExternally != expectedValue {
t.Errorf("controller's iam.role.manageExternally didn't match : expected=%v actual=%v", expectedValue, c.Controller.IAMConfig.Role.ManageExternally)
}
},
},
},
{
context: "WithControllerIAMEnabledManageExternally",
configYaml: minimalValidConfigYaml + `
controller:
iam:
role:
name: myrole1
manageExternally: true
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
expectedManageExternally := true
expectedRoleName := "myrole1"
if expectedRoleName != c.Controller.IAMConfig.Role.Name {
t.Errorf("controller's iam.role.name didn't match : expected=%v actual=%v", expectedRoleName, c.Controller.IAMConfig.Role.Name)
}
if expectedManageExternally != c.Controller.IAMConfig.Role.ManageExternally {
t.Errorf("controller's iam.role.manageExternally didn't matchg : expected=%v actual=%v", expectedManageExternally, c.Controller.IAMConfig.Role.ManageExternally)
}
},
},
},
{
context: "WithControllerIAMEnabledStrictName",
configYaml: minimalValidConfigYaml + `
controller:
iam:
role:
name: myrole1
strictName: true
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
expectedRoleName := "myrole1"
if expectedRoleName != c.Controller.IAMConfig.Role.Name {
t.Errorf("controller's iam.role.name didn't match : expected=%v actual=%v", expectedRoleName, c.Controller.IAMConfig.Role.Name)
}
},
},
},
{
context: "WithWaitSignalDisabled",
configYaml: minimalValidConfigYaml + `
waitSignal:
enabled: false
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
if c.WaitSignal.Enabled() {
t.Errorf("waitSignal should be disabled but was not: %v", c.WaitSignal)
}
},
},
},
{
context: "WithWaitSignalEnabled",
configYaml: minimalValidConfigYaml + `
waitSignal:
enabled: true
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
if !c.WaitSignal.Enabled() {
t.Errorf("waitSignal should be enabled but was not: %v", c.WaitSignal)
}
},
},
},
{
context: "WithNodePoolWithWaitSignalDisabled",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
waitSignal:
enabled: false
- name: pool2
waitSignal:
enabled: false
maxBatchSize: 2
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
if c.NodePools[0].WaitSignal.Enabled() {
t.Errorf("waitSignal should be disabled for node pool at index %d but was not", 0)
}
if c.NodePools[1].WaitSignal.Enabled() {
t.Errorf("waitSignal should be disabled for node pool at index %d but was not", 1)
}
},
},
},
{
context: "WithNodePoolWithWaitSignalEnabled",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
waitSignal:
enabled: true
- name: pool2
waitSignal:
enabled: true
maxBatchSize: 2
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
if !c.NodePools[0].WaitSignal.Enabled() {
t.Errorf("waitSignal should be enabled for node pool at index %d but was not", 0)
}
if c.NodePools[0].WaitSignal.MaxBatchSize(1) != 1 {
t.Errorf("waitSignal.maxBatchSize should be 1 for node pool at index %d but was %d", 0, c.NodePools[0].WaitSignal.MaxBatchSize(1))
}
if !c.NodePools[1].WaitSignal.Enabled() {
t.Errorf("waitSignal should be enabled for node pool at index %d but was not", 1)
}
if c.NodePools[1].WaitSignal.MaxBatchSize(1) != 2 {
t.Errorf("waitSignal.maxBatchSize should be 2 for node pool at index %d but was %d", 1, c.NodePools[1].WaitSignal.MaxBatchSize(1))
}
},
},
},
{
context: "WithDefaultNodePoolRollingStrategy",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
`,
assertConfig: []ConfigTester{
hasDefaultNodePoolRollingStrategy,
},
},
{
context: "WithSpecificNodePoolRollingStrategy",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
nodePoolRollingStrategy: Sequential`,
assertConfig: []ConfigTester{
hasSpecificNodePoolRollingStrategy("Sequential"),
},
},
{
context: "WithSpecificWorkerRollingStrategy",
configYaml: minimalValidConfigYaml + `
worker:
nodePoolRollingStrategy: Sequential
nodePools:
- name: pool1`,
assertConfig: []ConfigTester{
hasSpecificNodePoolRollingStrategy("Sequential"),
},
},
{
context: "WithWorkerAndNodePoolStrategy",
configYaml: minimalValidConfigYaml + `
worker:
nodePoolRollingStrategy: Sequential
nodePools:
- name: pool1
- name: pool2
nodePoolRollingStrategy: Parallel
`,
assertConfig: []ConfigTester{
hasWorkerAndNodePoolStrategy("Sequential", "Parallel"),
},
},
{
context: "WithMinimalValidConfig",
configYaml: minimalValidConfigYaml,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
},
},
{
context: "WithVaryingWorkerCountPerNodePool",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
- name: pool2
count: 2
- name: pool3
count: 0
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if c.NodePools[0].Count != 1 {
t.Errorf("default worker count should be 1 but was: %d", c.NodePools[0].Count)
}
if c.NodePools[1].Count != 2 {
t.Errorf("worker count should be set to 2 but was: %d", c.NodePools[1].Count)
}
if c.NodePools[2].Count != 0 {
t.Errorf("worker count should be be set to 0 but was: %d", c.NodePools[2].Count)
}
},
},
},
{
context: "WithVaryingWorkerASGSizePerNodePool",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
- name: pool2
count: 2
- name: pool3
autoScalingGroup:
minSize: 0
maxSize: 10
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if c.NodePools[0].MaxCount() != 1 {
t.Errorf("worker max count should be 1 but was: %d", c.NodePools[0].MaxCount())
}
if c.NodePools[0].MinCount() != 1 {
t.Errorf("worker min count should be 1 but was: %d", c.NodePools[0].MinCount())
}
if c.NodePools[1].MaxCount() != 2 {
t.Errorf("worker max count should be 2 but was: %d", c.NodePools[1].MaxCount())
}
if c.NodePools[1].MinCount() != 2 {
t.Errorf("worker min count should be 2 but was: %d", c.NodePools[1].MinCount())
}
if c.NodePools[2].MaxCount() != 10 {
t.Errorf("worker max count should be 10 but was: %d", c.NodePools[2].MaxCount())
}
if c.NodePools[2].MinCount() != 0 {
t.Errorf("worker min count should be 0 but was: %d", c.NodePools[2].MinCount())
}
},
},
},
{
context: "WithMultiAPIEndpoints",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: privateSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
- name: privateSubnet2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: publicSubnet2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
worker:
# cant be possibly "unversioned" one w/ existing elb because doing so would result in a worker kubelet has chances to
# connect to multiple masters from different clusters!
apiEndpointName: versionedPrivate
# btw apiEndpointName can be defaulted to a private/public managed(hence unstable/possibly versioned but not stable/unversioned)
# elb/round-robin if and only if there is only one. However we dont do the complex defaulting like that for now.
adminAPIEndpointName: versionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
id: elb-internet-facing
##you cant configure existing elb like below
#private: true
#subnets:
#- name: privateSubnet1
##hostedZone must be omitted when elb id is specified.
##in other words, it your responsibility to create an alias record for the elb
#hostedZone:
# id: hostedzone-private
- name: unversionedPrivate
dnsName: api.internal.example.com
loadBalancer:
id: elb-internal
- name: versionedPublic
dnsName: v1api.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
- name: versionedPrivate
dnsName: v1api.internal.example.com
loadBalancer:
private: true
subnets:
- name: privateSubnet1
hostedZone:
id: hostedzone-private
- name: versionedPublicAlt
dnsName: v1apialt.example.com
loadBalancer:
# "private: false" implies all the private subnets defined in the top-level "subnets"
#subnets:
#- name: publicSubnet1
#- name: publicSubnet2
hostedZone:
id: hostedzone-public
- name: versionedPrivateAlt
dnsName: v1apialt.internal.example.com
loadBalancer:
private: true
# "private: true" implies all the private subnets defined in the top-level "subnets"
#subnets:
#- name: privateSubnet1
#- name: privateSubnet2
hostedZone:
id: hostedzone-private
- name: addedToCertCommonNames
dnsName: api-alt.example.com
loadBalancer:
managed: false
- name: elbOnly
dnsName: registerme.example.com
loadBalancer:
recordSetManaged: false
`,
assertCluster: []ClusterTester{
func(rootCluster *root.Cluster, t *testing.T) {
c := rootCluster.ControlPlane().Config
private1 := api.NewPrivateSubnet("us-west-1a", "10.0.1.0/24")
private1.Name = "privateSubnet1"
private2 := api.NewPrivateSubnet("us-west-1b", "10.0.2.0/24")
private2.Name = "privateSubnet2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "publicSubnet1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "publicSubnet2"
//private1 := api.NewPrivateSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-PrivateSubnet1"}}`)
//private1.Name = "privateSubnet1"
//
//private2 := api.NewPrivateSubnetFromFn("us-west-1b", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-PrivateSubnet2"}}`)
//private2.Name = "privateSubnet2"
//
//public1 := api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-PublicSubnet1"}}`)
//public1.Name = "publicSubnet1"
//
//public2 := api.NewPublicSubnetFromFn("us-west-1b", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-PublicSubnet2"}}`)
//public2.Name = "publicSubnet2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%+v actual=%+v", subnets, c.AllSubnets())
}
publicSubnets := api.Subnets{
public1,
public2,
}
privateSubnets := api.Subnets{
private1,
private2,
}
unversionedPublic := c.APIEndpoints["unversionedPublic"]
unversionedPrivate := c.APIEndpoints["unversionedPrivate"]
versionedPublic := c.APIEndpoints["versionedPublic"]
versionedPrivate := c.APIEndpoints["versionedPrivate"]
versionedPublicAlt := c.APIEndpoints["versionedPublicAlt"]
versionedPrivateAlt := c.APIEndpoints["versionedPrivateAlt"]
addedToCertCommonNames := c.APIEndpoints["addedToCertCommonNames"]
elbOnly := c.APIEndpoints["elbOnly"]
if len(unversionedPublic.LoadBalancer.Subnets) != 0 {
t.Errorf("unversionedPublic: subnets shuold be empty but was not: actual=%+v", unversionedPublic.LoadBalancer.Subnets)
}
if !unversionedPublic.LoadBalancer.Enabled() {
t.Errorf("unversionedPublic: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", unversionedPublic.LoadBalancer)
}
if len(unversionedPrivate.LoadBalancer.Subnets) != 0 {
t.Errorf("unversionedPrivate: subnets shuold be empty but was not: actual=%+v", unversionedPrivate.LoadBalancer.Subnets)
}
if !unversionedPrivate.LoadBalancer.Enabled() {
t.Errorf("unversionedPrivate: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", unversionedPrivate.LoadBalancer)
}
if diff := cmp.Diff(versionedPublic.LoadBalancer.Subnets, api.Subnets{public1}); diff != "" {
t.Errorf("versionedPublic: subnets didn't match: %s", diff)
}
if !versionedPublic.LoadBalancer.Enabled() {
t.Errorf("versionedPublic: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", versionedPublic.LoadBalancer)
}
if diff := cmp.Diff(versionedPrivate.LoadBalancer.Subnets, api.Subnets{private1}); diff != "" {
t.Errorf("versionedPrivate: subnets didn't match: %s", diff)
}
if !versionedPrivate.LoadBalancer.Enabled() {
t.Errorf("versionedPrivate: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", versionedPrivate.LoadBalancer)
}
if diff := cmp.Diff(versionedPublicAlt.LoadBalancer.Subnets, publicSubnets); diff != "" {
t.Errorf("versionedPublicAlt: subnets didn't match: %s", diff)
}
if !versionedPublicAlt.LoadBalancer.Enabled() {
t.Errorf("versionedPublicAlt: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", versionedPublicAlt.LoadBalancer)
}
if diff := cmp.Diff(versionedPrivateAlt.LoadBalancer.Subnets, privateSubnets); diff != "" {
t.Errorf("versionedPrivateAlt: subnets didn't match: %s", diff)
}
if !versionedPrivateAlt.LoadBalancer.Enabled() {
t.Errorf("versionedPrivateAlt: it should be enabled as the lb to which controller nodes are added, but it was not: loadBalancer=%+v", versionedPrivateAlt.LoadBalancer)
}
if len(addedToCertCommonNames.LoadBalancer.Subnets) != 0 {
t.Errorf("addedToCertCommonNames: subnets should be empty but was not: actual=%+v", addedToCertCommonNames.LoadBalancer.Subnets)
}
if addedToCertCommonNames.LoadBalancer.Enabled() {
t.Errorf("addedToCertCommonNames: it should not be enabled as the lb to which controller nodes are added, but it was: loadBalancer=%+v", addedToCertCommonNames.LoadBalancer)
}
if diff := cmp.Diff(elbOnly.LoadBalancer.Subnets, publicSubnets); diff != "" {
t.Errorf("elbOnly: subnets didn't match: %s", diff)
}
if !elbOnly.LoadBalancer.Enabled() {
t.Errorf("elbOnly: it should be enabled but it was not: loadBalancer=%+v", elbOnly.LoadBalancer)
}
if elbOnly.LoadBalancer.ManageELBRecordSet() {
t.Errorf("elbOnly: record set should not be managed but it was: loadBalancer=%+v", elbOnly.LoadBalancer)
}
if diff := cmp.Diff(c.ExternalDNSNames(), []string{"api-alt.example.com", "api.example.com", "api.internal.example.com", "registerme.example.com", "v1api.example.com", "v1api.internal.example.com", "v1apialt.example.com", "v1apialt.internal.example.com"}); diff != "" {
t.Errorf("unexpected external DNS names: %s", diff)
}
if !reflect.DeepEqual(c.APIEndpoints.ManagedELBLogicalNames(), []string{"APIEndpointElbOnlyELB", "APIEndpointVersionedPrivateAltELB", "APIEndpointVersionedPrivateELB", "APIEndpointVersionedPublicAltELB", "APIEndpointVersionedPublicELB"}) {
t.Errorf("unexpected managed ELB logical names: %s", strings.Join(c.APIEndpoints.ManagedELBLogicalNames(), ", "))
}
},
},
},
{
context: "WithNetworkTopologyExplicitSubnets",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
# routeTableId must be omitted
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-275962332
# routeTableId: rtb-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
controller:
subnets:
- name: private1
- name: private2
loadBalancer:
subnets:
- name: public1
- name: public2
private: false
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
everyPublicSubnetHasRouteToIGW,
hasTwoManagedNGWsAndEIPs,
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnet("us-west-1a", "10.0.1.0/24")
private1.Name = "private1"
private2 := api.NewPrivateSubnet("us-west-1b", "10.0.2.0/24")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%v actual=%v", subnets, c.AllSubnets())
}
publicSubnets := api.Subnets{
public1,
public2,
}
importedPublicSubnets := api.Subnets{
api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-Public1"}}`),
}
p := c.NodePools[0]
if !reflect.DeepEqual(p.Subnets, importedPublicSubnets) {
t.Errorf("Worker subnets didn't match: expected=%v actual=%v", importedPublicSubnets, p.Subnets)
}
privateSubnets := api.Subnets{
private1,
private2,
}
if !reflect.DeepEqual(c.Controller.Subnets, privateSubnets) {
t.Errorf("Controller subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.Subnets)
}
if !reflect.DeepEqual(c.Controller.LoadBalancer.Subnets, publicSubnets) {
t.Errorf("Controller loadbalancer subnets didn't match: expected=%v actual=%v", publicSubnets, c.Controller.LoadBalancer.Subnets)
}
if diff := cmp.Diff(c.Etcd.Subnets, privateSubnets); diff != "" {
t.Errorf("Etcd subnets didn't match: %s", diff)
}
for i, s := range c.PrivateSubnets() {
if !s.ManageNATGateway() {
t.Errorf("NAT gateway for the private subnet #%d should be created by kube-aws but it is not going to be", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyImplicitSubnets",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
# routeTableId must be omitted
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-275962332
# routeTableId: rtb-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
everyPublicSubnetHasRouteToIGW,
hasTwoManagedNGWsAndEIPs,
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnet("us-west-1a", "10.0.1.0/24")
private1.Name = "private1"
private2 := api.NewPrivateSubnet("us-west-1b", "10.0.2.0/24")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%v actual=%v", subnets, c.AllSubnets())
}
publicSubnets := api.Subnets{
public1,
public2,
}
if !reflect.DeepEqual(c.Controller.Subnets, publicSubnets) {
t.Errorf("Controller subnets didn't match: expected=%v actual=%v", publicSubnets, c.Controller.Subnets)
}
if !reflect.DeepEqual(c.Controller.LoadBalancer.Subnets, publicSubnets) {
t.Errorf("Controller loadbalancer subnets didn't match: expected=%v actual=%v", publicSubnets, c.Controller.LoadBalancer.Subnets)
}
if !reflect.DeepEqual(c.Etcd.Subnets, publicSubnets) {
t.Errorf("Etcd subnets didn't match: expected=%v actual=%v", publicSubnets, c.Etcd.Subnets)
}
for i, s := range c.PrivateSubnets() {
if !s.ManageNATGateway() {
t.Errorf("NAT gateway for the private subnet #%d should be created by kube-aws but it is not going to be", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyControllerPrivateLB",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
# routeTableId must be omitted
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-275962332
# routeTableId: rtb-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
controller:
subnets:
- name: private1
- name: private2
loadBalancer:
private: true
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
everyPublicSubnetHasRouteToIGW,
hasTwoManagedNGWsAndEIPs,
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnet("us-west-1a", "10.0.1.0/24")
private1.Name = "private1"
private2 := api.NewPrivateSubnet("us-west-1b", "10.0.2.0/24")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%v actual=%v", subnets, c.AllSubnets())
}
importedPublicSubnets := api.Subnets{
api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-Public1"}}`),
}
p := c.NodePools[0]
if !reflect.DeepEqual(p.Subnets, importedPublicSubnets) {
t.Errorf("Worker subnets didn't match: expected=%v actual=%v", importedPublicSubnets, p.Subnets)
}
privateSubnets := api.Subnets{
private1,
private2,
}
if !reflect.DeepEqual(c.Controller.Subnets, privateSubnets) {
t.Errorf("Controller subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.Subnets)
}
if !reflect.DeepEqual(c.Controller.LoadBalancer.Subnets, privateSubnets) {
t.Errorf("Controller loadbalancer subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.LoadBalancer.Subnets)
}
if !reflect.DeepEqual(c.Etcd.Subnets, privateSubnets) {
t.Errorf("Etcd subnets didn't match: expected=%v actual=%v", privateSubnets, c.Etcd.Subnets)
}
for i, s := range c.PrivateSubnets() {
if !s.ManageNATGateway() {
t.Errorf("NAT gateway for the private subnet #%d should be created by kube-aws but it is not going to be", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyControllerPublicLB",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
# routeTableId must be omitted
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-275962332
# routeTableId: rtb-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
everyPublicSubnetHasRouteToIGW,
hasTwoManagedNGWsAndEIPs,
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnet("us-west-1a", "10.0.1.0/24")
private1.Name = "private1"
private2 := api.NewPrivateSubnet("us-west-1b", "10.0.2.0/24")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
publicSubnets := api.Subnets{
public1,
public2,
}
privateSubnets := api.Subnets{
private1,
private2,
}
importedPublicSubnets := api.Subnets{
api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-Public1"}}`),
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%v actual=%v", subnets, c.AllSubnets())
}
p := c.NodePools[0]
if !reflect.DeepEqual(p.Subnets, importedPublicSubnets) {
t.Errorf("Worker subnets didn't match: expected=%v actual=%v", importedPublicSubnets, p.Subnets)
}
if !reflect.DeepEqual(c.Controller.Subnets, publicSubnets) {
t.Errorf("Controller subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.Subnets)
}
if !reflect.DeepEqual(c.Controller.LoadBalancer.Subnets, publicSubnets) {
t.Errorf("Controller loadbalancer subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.LoadBalancer.Subnets)
}
if !reflect.DeepEqual(c.Etcd.Subnets, privateSubnets) {
t.Errorf("Etcd subnets didn't match: expected=%v actual=%v", privateSubnets, c.Etcd.Subnets)
}
for i, s := range c.PrivateSubnets() {
if !s.ManageNATGateway() {
t.Errorf("NAT gateway for the private subnet #%d should be created by kube-aws but it is not going to be", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyExistingVaryingSubnets",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
id: subnet-1
private: true
- name: private2
availabilityZone: us-west-1b
idFromStackOutput: mycluster-private-subnet-1
private: true
- name: public1
availabilityZone: us-west-1a
id: subnet-2
- name: public2
availabilityZone: us-west-1b
idFromStackOutput: mycluster-public-subnet-1
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasNoNGWsOrEIPsOrRoutes,
func(c *config.Config, t *testing.T) {
private1 := api.NewExistingPrivateSubnet("us-west-1a", "subnet-1")
private1.Name = "private1"
private2 := api.NewImportedPrivateSubnet("us-west-1b", "mycluster-private-subnet-1")
private2.Name = "private2"
public1 := api.NewExistingPublicSubnet("us-west-1a", "subnet-2")
public1.Name = "public1"
public2 := api.NewImportedPublicSubnet("us-west-1b", "mycluster-public-subnet-1")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
controllerPublicSubnets := api.Subnets{
public1,
public2,
}
nodepoolPublicSubnets := api.Subnets{
public1,
}
privateSubnets := api.Subnets{
private1,
private2,
}
if !reflect.DeepEqual(c.AllSubnets(), subnets) {
t.Errorf("Managed subnets didn't match: expected=%v actual=%v", subnets, c.AllSubnets())
}
p := c.NodePools[0]
if !reflect.DeepEqual(p.Subnets, nodepoolPublicSubnets) {
t.Errorf("Worker subnets didn't match: expected=%v actual=%v", nodepoolPublicSubnets, p.Subnets)
}
if !reflect.DeepEqual(c.Controller.Subnets, controllerPublicSubnets) {
t.Errorf("Controller subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.Subnets)
}
if !reflect.DeepEqual(c.Controller.LoadBalancer.Subnets, controllerPublicSubnets) {
t.Errorf("Controller loadbalancer subnets didn't match: expected=%v actual=%v", privateSubnets, c.Controller.LoadBalancer.Subnets)
}
if !reflect.DeepEqual(c.Etcd.Subnets, privateSubnets) {
t.Errorf("Etcd subnets didn't match: expected=%v actual=%v", privateSubnets, c.Etcd.Subnets)
}
for i, s := range c.PrivateSubnets() {
if s.ManageNATGateway() {
t.Errorf("NAT gateway for the existing private subnet #%d should not be created by kube-aws", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyAllExistingPrivateSubnets",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + fmt.Sprintf(`
vpc:
id: vpc-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
id: subnet-1
private: true
- name: private2
availabilityZone: us-west-1b
idFromStackOutput: mycluster-private-subnet-1
private: true
controller:
subnets:
- name: private1
- name: private2
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: private1
- name: pool2
subnets:
- name: private2
apiEndpoints:
- name: public
dnsName: "%s"
loadBalancer:
hostedZone:
id: hostedzone-xxxx
private: true
`, kubeAwsSettings.externalDNSName),
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasNoNGWsOrEIPsOrRoutes,
},
},
{
context: "WithNetworkTopologyAllExistingPublicSubnets",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
subnets:
- name: public1
availabilityZone: us-west-1a
id: subnet-2
- name: public2
availabilityZone: us-west-1b
idFromStackOutput: mycluster-public-subnet-1
etcd:
subnets:
- name: public1
- name: public2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasNoNGWsOrEIPsOrRoutes,
},
},
{
context: "WithNetworkTopologyExistingNATGateways",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
natGateway:
id: ngw-11111111
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
natGateway:
id: ngw-22222222
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasNoManagedNGWsButSpecificNumOfRoutesToUnmanagedNGWs(2),
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnetWithPreconfiguredNATGateway("us-west-1a", "10.0.1.0/24", "ngw-11111111")
private1.Name = "private1"
private2 := api.NewPrivateSubnetWithPreconfiguredNATGateway("us-west-1b", "10.0.2.0/24", "ngw-22222222")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
publicSubnets := api.Subnets{
public1,
public2,
}
privateSubnets := api.Subnets{
private1,
private2,
}
importedPublicSubnets := api.Subnets{
api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-Public1"}}`),
}
if diff := cmp.Diff(c.AllSubnets(), subnets); diff != "" {
t.Errorf("Managed subnets didn't match: %s", diff)
}
p := c.NodePools[0]
if diff := cmp.Diff(p.Subnets, importedPublicSubnets); diff != "" {
t.Errorf("Worker subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Controller.Subnets, publicSubnets); diff != "" {
t.Errorf("Controller subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Controller.LoadBalancer.Subnets, publicSubnets); diff != "" {
t.Errorf("Controller loadbalancer subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Etcd.Subnets, privateSubnets); diff != "" {
t.Errorf("Etcd subnets didn't match: %s", diff)
}
for i, s := range c.PrivateSubnets() {
if s.ManageNATGateway() {
t.Errorf("NAT gateway for the existing private subnet #%d should not be created by kube-aws", i)
}
if s.ManageRouteToInternet() {
t.Errorf("Route to IGW shouldn't be created for a private subnet: %v", s)
}
}
},
},
},
{
context: "WithNetworkTopologyExistingNATGatewayEIPs",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
private: true
natGateway:
eipAllocationId: eipalloc-11111111
- name: private2
availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
private: true
natGateway:
eipAllocationId: eipalloc-22222222
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.3.0/24"
- name: public2
availabilityZone: us-west-1b
instanceCIDR: "10.0.4.0/24"
etcd:
subnets:
- name: private1
- name: private2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasSpecificNumOfManagedNGWsWithUnmanagedEIPs(2),
hasPrivateSubnetsWithManagedNGWs(2),
func(c *config.Config, t *testing.T) {
private1 := api.NewPrivateSubnetWithPreconfiguredNATGatewayEIP("us-west-1a", "10.0.1.0/24", "eipalloc-11111111")
private1.Name = "private1"
private2 := api.NewPrivateSubnetWithPreconfiguredNATGatewayEIP("us-west-1b", "10.0.2.0/24", "eipalloc-22222222")
private2.Name = "private2"
public1 := api.NewPublicSubnet("us-west-1a", "10.0.3.0/24")
public1.Name = "public1"
public2 := api.NewPublicSubnet("us-west-1b", "10.0.4.0/24")
public2.Name = "public2"
subnets := api.Subnets{
private1,
private2,
public1,
public2,
}
publicSubnets := api.Subnets{
public1,
public2,
}
privateSubnets := api.Subnets{
private1,
private2,
}
importedPublicSubnets := api.Subnets{
api.NewPublicSubnetFromFn("us-west-1a", `{"Fn::ImportValue":{"Fn::Sub":"${NetworkStackName}-Public1"}}`),
}
if diff := cmp.Diff(c.AllSubnets(), subnets); diff != "" {
t.Errorf("Managed subnets didn't match: %s", diff)
}
p := c.NodePools[0]
if diff := cmp.Diff(p.Subnets, importedPublicSubnets); diff != "" {
t.Errorf("Worker subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Controller.Subnets, publicSubnets); diff != "" {
t.Errorf("Controller subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Controller.LoadBalancer.Subnets, publicSubnets); diff != "" {
t.Errorf("Controller loadbalancer subnets didn't match: %s", diff)
}
if diff := cmp.Diff(c.Etcd.Subnets, privateSubnets); diff != "" {
t.Errorf("Etcd subnets didn't match: %s", diff)
}
},
},
},
{
context: "WithNetworkTopologyVaryingPublicSubnets",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
#required only for the managed subnet "public1"
# "public2" is assumed to have an existing route table and an igw already associated to it
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
- name: public2
availabilityZone: us-west-1b
id: subnet-2
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: public1
- name: public2
worker:
nodePools:
- name: pool1
subnets:
- name: public1
- name: pool2
subnets:
- name: public2
`,
assertConfig: []ConfigTester{},
},
{
context: "WithSpotFleetEnabled",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
targetCapacity: 10
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasDefaultLaunchSpecifications,
spotFleetBasedNodePoolHasWaitSignalDisabled,
},
},
{
context: "WithSpotFleetEnabledWithCustomIamRole",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
targetCapacity: 10
iamFleetRoleArn: custom-iam-role
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
hasDefaultLaunchSpecifications,
spotFleetBasedNodePoolHasWaitSignalDisabled,
},
},
{
context: "WithSpotFleetWithCustomGp2RootVolumeSettings",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
targetCapacity: 10
unitRootVolumeSize: 40
launchSpecifications:
- weightedCapacity: 1
instanceType: c4.large
- weightedCapacity: 2
instanceType: c4.xlarge
rootVolume:
size: 100
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
spotFleetBasedNodePoolHasWaitSignalDisabled,
func(c *config.Config, t *testing.T) {
expected := []api.LaunchSpecification{
{
WeightedCapacity: 1,
InstanceType: "c4.large",
SpotPrice: "",
// RootVolumeSize was not specified in the configYaml but should default to workerRootVolumeSize * weightedCapacity
// RootVolumeType was not specified in the configYaml but should default to "gp2"
RootVolume: api.NewGp2RootVolume(40),
},
{
WeightedCapacity: 2,
InstanceType: "c4.xlarge",
SpotPrice: "",
RootVolume: api.NewGp2RootVolume(100),
},
}
p := c.NodePools[0]
actual := p.WorkerNodePool.SpotFleet.LaunchSpecifications
if !reflect.DeepEqual(expected, actual) {
t.Errorf(
"LaunchSpecifications didn't match: expected=%v actual=%v",
expected,
actual,
)
}
},
},
},
{
context: "WithSpotFleetWithCustomInstanceTypes",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
targetCapacity: 10
unitRootVolumeSize: 40
launchSpecifications:
- weightedCapacity: 1
instanceType: m4.large
- weightedCapacity: 2
instanceType: m4.xlarge
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
spotFleetBasedNodePoolHasWaitSignalDisabled,
func(c *config.Config, t *testing.T) {
expected := []api.LaunchSpecification{
{
WeightedCapacity: 1,
InstanceType: "m4.large",
SpotPrice: "",
// RootVolumeType was not specified in the configYaml but should default to gp2:
RootVolume: api.NewGp2RootVolume(40),
},
{
WeightedCapacity: 2,
InstanceType: "m4.xlarge",
SpotPrice: "",
RootVolume: api.NewGp2RootVolume(80),
},
}
p := c.NodePools[0]
actual := p.WorkerNodePool.SpotFleet.LaunchSpecifications
if !reflect.DeepEqual(expected, actual) {
t.Errorf(
"LaunchSpecifications didn't match: expected=%v actual=%v",
expected,
actual,
)
}
},
},
},
{
context: "WithSpotFleetWithCustomIo1RootVolumeSettings",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
targetCapacity: 10
rootVolumeType: io1
unitRootVolumeSize: 40
unitRootVolumeIOPS: 100
launchSpecifications:
- weightedCapacity: 1
instanceType: c4.large
- weightedCapacity: 2
instanceType: c4.xlarge
rootVolume:
iops: 500
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
spotFleetBasedNodePoolHasWaitSignalDisabled,
func(c *config.Config, t *testing.T) {
expected := []api.LaunchSpecification{
{
WeightedCapacity: 1,
InstanceType: "c4.large",
SpotPrice: "",
// RootVolumeSize was not specified in the configYaml but should default to workerRootVolumeSize * weightedCapacity
// RootVolumeIOPS was not specified in the configYaml but should default to workerRootVolumeIOPS * weightedCapacity
// RootVolumeType was not specified in the configYaml but should default to "io1"
RootVolume: api.NewIo1RootVolume(40, 100),
},
{
WeightedCapacity: 2,
InstanceType: "c4.xlarge",
SpotPrice: "",
// RootVolumeType was not specified in the configYaml but should default to:
RootVolume: api.NewIo1RootVolume(80, 500),
},
}
p := c.NodePools[0]
actual := p.WorkerNodePool.SpotFleet.LaunchSpecifications
if !reflect.DeepEqual(expected, actual) {
t.Errorf(
"LaunchSpecifications didn't match: expected=%v actual=%v",
expected,
actual,
)
}
},
},
},
{
context: "WithVpcIdSpecified",
configYaml: minimalValidConfigYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
vpcId := "vpc-1a2b3c4d"
if c.VPC.ID != vpcId {
t.Errorf("vpc id didn't match: expected=%v actual=%v", vpcId, c.VPC.ID)
}
igwId := "igw-1a2b3c4d"
if c.InternetGateway.ID != igwId {
t.Errorf("internet gateway id didn't match: expected=%v actual=%v", igwId, c.InternetGateway.ID)
}
},
},
},
{
context: "WithLegacyVpcAndIGWIdSpecified",
configYaml: minimalValidConfigYaml + `
vpcId: vpc-1a2b3c4d
internetGatewayId: igw-1a2b3c4d
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
vpcId := "vpc-1a2b3c4d"
if c.VPC.ID != vpcId {
t.Errorf("vpc id didn't match: expected=%v actual=%v", vpcId, c.VPC.ID)
}
igwId := "igw-1a2b3c4d"
if c.InternetGateway.ID != igwId {
t.Errorf("internet gateway id didn't match: expected=%v actual=%v", igwId, c.InternetGateway.ID)
}
},
},
},
{
context: "WithVpcIdAndRouteTableIdSpecified",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
subnets:
- name: Subnet0
availabilityZone: ` + firstAz + `
instanceCIDR: "10.0.0.0/24"
routeTable:
id: rtb-1a2b3c4d
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
subnet1 := api.NewPublicSubnetWithPreconfiguredRouteTable(firstAz, "10.0.0.0/24", "rtb-1a2b3c4d")
subnet1.Name = "Subnet0"
subnets := api.Subnets{
subnet1,
}
expected := api.EtcdSettings{
Etcd: api.Etcd{
Cluster: api.EtcdCluster{
Version: "v3.3.17",
},
EC2Instance: api.EC2Instance{
Count: 1,
InstanceType: "t2.medium",
RootVolume: api.RootVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
},
Tenancy: "default",
},
DataVolume: api.DataVolume{
Size: 30,
Type: "gp2",
IOPS: 0,
Ephemeral: false,
},
Subnets: subnets,
UserSuppliedArgs: api.UserSuppliedArgs{
QuotaBackendBytes: api.DefaultQuotaBackendBytes,
},
},
}
actual := c.EtcdSettings
if !reflect.DeepEqual(expected, actual) {
t.Errorf(
"EtcdSettings didn't match: expected=%v actual=%v",
expected,
actual,
)
}
},
},
},
{
context: "WithWorkerManagedIamRoleName",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
iam:
role:
name: "myManagedRole"
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if c.NodePools[0].IAMConfig.Role.Name != "myManagedRole" {
t.Errorf("iam.role.name: expected=myManagedRole actual=%s", c.NodePools[0].IAMConfig.Role.Name)
}
},
},
},
{
context: "WithWorkerManagedPolicies",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
iam:
role:
managedPolicies:
- arn: "arn:aws:iam::aws:policy/AdministratorAccess"
- arn: "arn:aws:iam::000000000000:policy/myManagedPolicy"
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if len(c.NodePools[0].IAMConfig.Role.ManagedPolicies) < 2 {
t.Errorf("iam.role.managedPolicies: incorrect number of policies expected=2 actual=%d", len(c.NodePools[0].IAMConfig.Role.ManagedPolicies))
}
if c.NodePools[0].IAMConfig.Role.ManagedPolicies[0].Arn != "arn:aws:iam::aws:policy/AdministratorAccess" {
t.Errorf("iam.role.managedPolicies: expected=arn:aws:iam::aws:policy/AdministratorAccess actual=%s", c.NodePools[0].IAMConfig.Role.ManagedPolicies[0].Arn)
}
if c.NodePools[0].IAMConfig.Role.ManagedPolicies[1].Arn != "arn:aws:iam::000000000000:policy/myManagedPolicy" {
t.Errorf("iam.role.managedPolicies: expected=arn:aws:iam::000000000000:policy/myManagedPolicy actual=%s", c.NodePools[0].IAMConfig.Role.ManagedPolicies[1].Arn)
}
},
},
},
{
context: "WithWorkerExistingInstanceProfile",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
iam:
instanceProfile:
arn: "arn:aws:iam::000000000000:instance-profile/myInstanceProfile"
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if c.NodePools[0].IAMConfig.InstanceProfile.Arn != "arn:aws:iam::000000000000:instance-profile/myInstanceProfile" {
t.Errorf("existingInstanceProfile: expected=arn:aws:iam::000000000000:instance-profile/myInstanceProfile actual=%s", c.NodePools[0].IAMConfig.InstanceProfile.Arn)
}
},
},
},
{
context: "WithWorkerAndControllerExistingInstanceProfile",
configYaml: minimalValidConfigYaml + `
controller:
iam:
instanceProfile:
arn: "arn:aws:iam::000000000000:instance-profile/myControllerInstanceProfile"
worker:
nodePools:
- name: pool1
iam:
instanceProfile:
arn: "arn:aws:iam::000000000000:instance-profile/myInstanceProfile"
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
if c.Controller.IAMConfig.InstanceProfile.Arn != "arn:aws:iam::000000000000:instance-profile/myControllerInstanceProfile" {
t.Errorf("existingInstanceProfile: expected=arn:aws:iam::000000000000:instance-profile/myControllerInstanceProfile actual=%s", c.Controller.IAMConfig.InstanceProfile.Arn)
}
if c.NodePools[0].IAMConfig.InstanceProfile.Arn != "arn:aws:iam::000000000000:instance-profile/myInstanceProfile" {
t.Errorf("existingInstanceProfile: expected=arn:aws:iam::000000000000:instance-profile/myInstanceProfile actual=%s", c.NodePools[0].IAMConfig.InstanceProfile.Arn)
}
},
},
},
{
context: "WithWorkerSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
- sg-23456789
- sg-bcdefabc
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
expectedWorkerSecurityGroupIds := []string{
`sg-12345678`, `sg-abcdefab`, `sg-23456789`, `sg-bcdefabc`,
}
if !reflect.DeepEqual(p.SecurityGroupIds, expectedWorkerSecurityGroupIds) {
t.Errorf("WorkerSecurityGroupIds didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupIds, p.SecurityGroupIds)
}
expectedWorkerSecurityGroupRefs := []string{
`"sg-12345678"`, `"sg-abcdefab"`, `"sg-23456789"`, `"sg-bcdefabc"`,
`{"Fn::ImportValue" : {"Fn::Sub" : "${NetworkStackName}-WorkerSecurityGroup"}}`,
}
if !reflect.DeepEqual(p.SecurityGroupRefs(), expectedWorkerSecurityGroupRefs) {
t.Errorf("SecurityGroupRefs didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupRefs, p.SecurityGroupRefs())
}
},
},
},
{
context: "WithWorkerAndLBSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
loadBalancer:
enabled: true
securityGroupIds:
- sg-23456789
- sg-bcdefabc
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
expectedWorkerSecurityGroupIds := []string{
`sg-12345678`, `sg-abcdefab`,
}
if !reflect.DeepEqual(p.SecurityGroupIds, expectedWorkerSecurityGroupIds) {
t.Errorf("WorkerSecurityGroupIds didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupIds, p.SecurityGroupIds)
}
expectedLBSecurityGroupIds := []string{
`sg-23456789`, `sg-bcdefabc`,
}
if !reflect.DeepEqual(p.LoadBalancer.SecurityGroupIds, expectedLBSecurityGroupIds) {
t.Errorf("LBSecurityGroupIds didn't match: expected=%v actual=%v", expectedLBSecurityGroupIds, p.LoadBalancer.SecurityGroupIds)
}
expectedWorkerSecurityGroupRefs := []string{
`"sg-23456789"`, `"sg-bcdefabc"`, `"sg-12345678"`, `"sg-abcdefab"`,
`{"Fn::ImportValue" : {"Fn::Sub" : "${NetworkStackName}-WorkerSecurityGroup"}}`,
}
if !reflect.DeepEqual(p.SecurityGroupRefs(), expectedWorkerSecurityGroupRefs) {
t.Errorf("SecurityGroupRefs didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupRefs, p.SecurityGroupRefs())
}
},
},
},
{
context: "WithWorkerAndALBSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
targetGroup:
enabled: true
securityGroupIds:
- sg-23456789
- sg-bcdefabc
`,
assertConfig: []ConfigTester{
hasDefaultEtcdSettings,
func(c *config.Config, t *testing.T) {
p := c.NodePools[0]
expectedWorkerSecurityGroupIds := []string{
`sg-12345678`, `sg-abcdefab`,
}
if !reflect.DeepEqual(p.SecurityGroupIds, expectedWorkerSecurityGroupIds) {
t.Errorf("WorkerSecurityGroupIds didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupIds, p.SecurityGroupIds)
}
expectedALBSecurityGroupIds := []string{
`sg-23456789`, `sg-bcdefabc`,
}
if !reflect.DeepEqual(p.TargetGroup.SecurityGroupIds, expectedALBSecurityGroupIds) {
t.Errorf("LBSecurityGroupIds didn't match: expected=%v actual=%v", expectedALBSecurityGroupIds, p.TargetGroup.SecurityGroupIds)
}
expectedWorkerSecurityGroupRefs := []string{
`"sg-23456789"`, `"sg-bcdefabc"`, `"sg-12345678"`, `"sg-abcdefab"`,
`{"Fn::ImportValue" : {"Fn::Sub" : "${NetworkStackName}-WorkerSecurityGroup"}}`,
}
if !reflect.DeepEqual(p.SecurityGroupRefs(), expectedWorkerSecurityGroupRefs) {
t.Errorf("SecurityGroupRefs didn't match: expected=%v actual=%v", expectedWorkerSecurityGroupRefs, p.SecurityGroupRefs())
}
},
},
},
{
context: "WithDedicatedInstanceTenancy",
configYaml: minimalValidConfigYaml + `
workerTenancy: dedicated
controller:
tenancy: dedicated
etcd:
tenancy: dedicated
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
if c.Etcd.Tenancy != "dedicated" {
t.Errorf("Etcd.Tenancy didn't match: expected=dedicated actual=%s", c.Etcd.Tenancy)
}
if c.WorkerTenancy != "dedicated" {
t.Errorf("WorkerTenancy didn't match: expected=dedicated actual=%s", c.WorkerTenancy)
}
if c.Controller.Tenancy != "dedicated" {
t.Errorf("Controller.Tenancy didn't match: expected=dedicated actual=%s", c.Controller.Tenancy)
}
},
},
},
{
context: "WithControllerNodeLabels",
configYaml: minimalValidConfigYaml + `
controller:
nodeLabels:
kube-aws.coreos.com/role: controller
`,
assertConfig: []ConfigTester{
hasDefaultExperimentalFeatures,
func(c *config.Config, t *testing.T) {
expected := api.NodeLabels{"kube-aws.coreos.com/role": "controller"}
actual := c.NodeLabels()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("unexpected controller node labels: expected=%v, actual=%v", expected, actual)
}
},
},
},
{
context: "WithSSHAccessAllowedSourceCIDRsSpecified",
configYaml: minimalValidConfigYaml + `
sshAccessAllowedSourceCIDRs:
- 1.2.3.255/32
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
l := len(c.SSHAccessAllowedSourceCIDRs)
if l != 1 {
t.Errorf("unexpected size of sshAccessAllowedSouceCIDRs: %d", l)
t.FailNow()
}
actual := c.SSHAccessAllowedSourceCIDRs[0].String()
expected := "1.2.3.255/32"
if actual != expected {
t.Errorf("unexpected cidr in sshAccessAllowedSourecCIDRs[0]. expected = %s, actual = %s", expected, actual)
}
},
},
},
{
context: "WithSSHAccessAllowedSourceCIDRsOmitted",
configYaml: minimalValidConfigYaml,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
l := len(c.SSHAccessAllowedSourceCIDRs)
if l != 1 {
t.Errorf("unexpected size of sshAccessAllowedSouceCIDRs: %d", l)
t.FailNow()
}
actual := c.SSHAccessAllowedSourceCIDRs[0].String()
expected := "0.0.0.0/0"
if actual != expected {
t.Errorf("unexpected cidr in sshAccessAllowedSourecCIDRs[0]. expected = %s, actual = %s", expected, actual)
}
},
},
},
{
context: "WithSSHAccessAllowedSourceCIDRsEmptied",
configYaml: minimalValidConfigYaml + `
sshAccessAllowedSourceCIDRs:
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
l := len(c.SSHAccessAllowedSourceCIDRs)
if l != 0 {
t.Errorf("unexpected size of sshAccessAllowedSouceCIDRs: %d", l)
t.FailNow()
}
},
},
},
{
context: "WithWorkerWithoutGPUSettings",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
enabled := c.NodePools[0].Gpu.Nvidia.Enabled
if enabled {
t.Errorf("unexpected enabled of gpu.nvidia: %v. its default value should be false", enabled)
t.FailNow()
}
},
},
},
{
context: "WithGPUEnabledWorker",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
instanceType: p2.xlarge
gpu:
nvidia:
enabled: true
version: "123.45"
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
enabled := c.NodePools[0].Gpu.Nvidia.Enabled
version := c.NodePools[0].Gpu.Nvidia.Version
if !enabled {
t.Errorf("unexpected enabled value of gpu.nvidia: %v.", enabled)
t.FailNow()
}
if version != "123.45" {
t.Errorf("unexpected version value of gpu.nvidia: %v.", version)
t.FailNow()
}
},
},
},
{
context: "WithGPUDisabledWorker",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
gpu:
nvidia:
enabled: false
version: "123.45"
`,
assertConfig: []ConfigTester{
func(c *config.Config, t *testing.T) {
enabled := c.NodePools[0].Gpu.Nvidia.Enabled
version := c.NodePools[0].Gpu.Nvidia.Version
if enabled {
t.Errorf("unexpected enabled value of gpu.nvidia: %v.", enabled)
t.FailNow()
}
if version != "123.45" {
t.Errorf("unexpected version value of gpu.nvidia: %v.", version)
t.FailNow()
}
},
},
},
}
for _, validCase := range validCases {
t.Run(validCase.context, func(t *testing.T) {
configBytes := validCase.configYaml
// TODO Allow including plugins in test data?
plugins := []*api.Plugin{}
providedConfig, err := config.ConfigFromBytes([]byte(configBytes), plugins)
if err != nil {
t.Errorf("failed to parse config %s: %+v", configBytes, err)
t.FailNow()
}
t.Run("AssertConfig", func(t *testing.T) {
for _, assertion := range validCase.assertConfig {
assertion(providedConfig, t)
}
})
helper.WithDummyCredentials(func(dummyAssetsDir string) {
var stackTemplateOptions = root.NewOptions(false, false)
stackTemplateOptions.AssetsDir = dummyAssetsDir
stackTemplateOptions.ControllerTmplFile = "../../builtin/files/userdata/cloud-config-controller"
stackTemplateOptions.WorkerTmplFile = "../../builtin/files/userdata/cloud-config-worker"
stackTemplateOptions.EtcdTmplFile = "../../builtin/files/userdata/cloud-config-etcd"
stackTemplateOptions.RootStackTemplateTmplFile = "../../builtin/files/stack-templates/root.json.tmpl"
stackTemplateOptions.NodePoolStackTemplateTmplFile = "../../builtin/files/stack-templates/node-pool.json.tmpl"
stackTemplateOptions.ControlPlaneStackTemplateTmplFile = "../../builtin/files/stack-templates/control-plane.json.tmpl"
stackTemplateOptions.NetworkStackTemplateTmplFile = "../../builtin/files/stack-templates/network.json.tmpl"
stackTemplateOptions.EtcdStackTemplateTmplFile = "../../builtin/files/stack-templates/etcd.json.tmpl"
cl, err := root.CompileClusterFromConfig(providedConfig, stackTemplateOptions, false)
if err != nil {
t.Errorf("failed to create cluster driver : %v", err)
t.FailNow()
}
cl.Context = &model.Context{
ProvidedEncryptService: helper.DummyEncryptService{},
ProvidedCFInterrogator: helper.DummyCFInterrogator{},
ProvidedEC2Interrogator: helper.DummyEC2Interrogator{},
StackTemplateGetter: helper.DummyStackTemplateGetter{},
}
_, err = cl.EnsureAllAssetsGenerated()
if err != nil {
t.Errorf("%v", err)
t.FailNow()
}
t.Run("AssertCluster", func(t *testing.T) {
for _, assertion := range validCase.assertCluster {
assertion(cl, t)
}
})
t.Run("ValidateTemplates", func(t *testing.T) {
if err := cl.ValidateTemplates(); err != nil {
t.Errorf("failed to render stack template: %v", err)
}
})
if os.Getenv("KUBE_AWS_INTEGRATION_TEST") == "" {
t.Skipf("`export KUBE_AWS_INTEGRATION_TEST=1` is required to run integration tests. Skipping.")
t.SkipNow()
} else {
t.Run("ValidateStack", func(t *testing.T) {
if !s3URIExists {
t.Errorf("failed to obtain value for KUBE_AWS_S3_DIR_URI")
t.FailNow()
}
report, err := cl.ValidateStack()
if err != nil {
t.Errorf("failed to validate stack: %s %v", report, err)
}
})
}
})
})
}
parseErrorCases := []struct {
context string
configYaml string
expectedErrorMessage string
}{
{
context: "WithAPIEndpointLBAPIAccessAllowedSourceCIDRsEmptied",
configYaml: configYamlWithoutExernalDNSName + `
apiEndpoints:
- name: default
dnsName: k8s.example.com
loadBalancer:
apiAccessAllowedSourceCIDRs:
hostedZone:
id: a1b2c4
`,
expectedErrorMessage: `invalid cluster: invalid apiEndpoint "default" at index 0: invalid loadBalancer: either apiAccessAllowedSourceCIDRs or securityGroupIds must be present. Try not to explicitly empty apiAccessAllowedSourceCIDRs or set one or more securityGroupIDs`,
},
{
// See https://github.com/kubernetes-incubator/kube-aws/issues/365
context: "WithClusterNameContainsDots",
configYaml: kubeAwsSettings.withClusterName("my.cluster").minimumValidClusterYaml(),
expectedErrorMessage: "clusterName(=my.cluster) is malformed. It must consist only of alphanumeric characters, colons, or hyphens",
},
{
context: "WithControllerTaint",
configYaml: minimalValidConfigYaml + `
controller:
taints:
- key: foo
value: bar
effect: NoSchedule
`,
expectedErrorMessage: "`controller.taints` must not be specified because tainting controller nodes breaks the cluster",
},
{
context: "WithElasticFileSystemIdInSpecificNodePoolWithManagedSubnets",
configYaml: mainClusterYaml + `
subnets:
- name: managed1
availabilityZone: us-west-1a
instanceCIDR: 10.0.1.0/24
worker:
nodePools:
- name: pool1
subnets:
- name: managed1
elasticFileSystemId: efs-12345
- name: pool2
`,
expectedErrorMessage: "invalid node pool at index 0: elasticFileSystemId cannot be specified for a node pool in managed subnet(s), but was: efs-12345",
},
{
context: "WithEtcdAutomatedDisasterRecoveryRequiresAutomatedSnapshot",
configYaml: minimalValidConfigYaml + `
etcd:
version: 3
snapshot:
automated: false
disasterRecovery:
automated: true
`,
expectedErrorMessage: "`etcd.disasterRecovery.automated` is set to true but `etcd.snapshot.automated` is not - automated disaster recovery requires snapshot to be also automated",
},
{
context: "WithInvalidNodeDrainTimeout",
configYaml: minimalValidConfigYaml + `
experimental:
nodeDrainer:
enabled: true
drainTimeout: 100
`,
expectedErrorMessage: "Drain timeout must be an integer between 1 and 60, but was 100",
},
{
context: "WithInvalidTaint",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
taints:
- key: foo
value: bar
effect: UnknownEffect
`,
expectedErrorMessage: "invalid taint effect: UnknownEffect",
},
{
context: "WithLegacyControllerSettingKeys",
configYaml: minimalValidConfigYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
routeTableId: rtb-1a2b3c4d
controllerCount: 2
controllerCreateTimeout: PT10M
controllerInstanceType: t2.large
controllerRootVolumeSize: 101
controllerRootVolumeType: io1
controllerRootVolumeIOPS: 102
controllerTenancy: dedicated
`,
expectedErrorMessage: "unknown keys found: controllerCount, controllerCreateTimeout, controllerInstanceType, controllerRootVolumeIOPS, controllerRootVolumeSize, controllerRootVolumeType, controllerTenancy",
},
{
context: "WithLegacyEtcdSettingKeys",
configYaml: minimalValidConfigYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
routeTableId: rtb-1a2b3c4d
etcdCount: 2
etcdTenancy: dedicated
etcdInstanceType: t2.large
etcdRootVolumeSize: 101
etcdRootVolumeType: io1
etcdRootVolumeIOPS: 102
etcdDataVolumeSize: 103
etcdDataVolumeType: io1
etcdDataVolumeIOPS: 104
etcdDataVolumeEncrypted: true
`,
expectedErrorMessage: "unknown keys found: etcdCount, etcdDataVolumeEncrypted, etcdDataVolumeIOPS, etcdDataVolumeSize, etcdDataVolumeType, etcdInstanceType, etcdRootVolumeIOPS, etcdRootVolumeSize, etcdRootVolumeType, etcdTenancy",
},
{
context: "WithAwsNodeLabelEnabledForTooLongClusterNameAndPoolName",
configYaml: minimalValidConfigYaml + `
# clusterName + nodePools[].name should be less than or equal to 25 characters or the launch configuration name
# "mykubeawsclustername-mynestedstackname-1N2C4K3LLBEDZ-WorkersLC-BC2S9P3JG2QD" exceeds the limit of 63 characters
# See https://kubernetes.io/docs/user-guide/labels/#syntax-and-character-set
clusterName: my-cluster1 # 11 characters
worker:
nodePools:
- name: workernodepool1 # 15 characters
awsNodeLabels:
enabled: true
`,
expectedErrorMessage: "awsNodeLabels can't be enabled for node pool because the total number of characters in clusterName(=\"my-cluster1\") + node pool's name(=\"workernodepool1\") exceeds the limit of 25",
},
{
context: "WithAwsNodeLabelEnabledForTooLongClusterName",
configYaml: minimalValidConfigYaml + `
# clusterName should be less than or equal to 21 characters or the launch configuration name
# "mykubeawsclustername-mynestedstackname-1N2C4K3LLBEDZ-ControllersLC-BC2S9P3JG2QD" exceeds the limit of 63 characters
# See https://kubernetes.io/docs/user-guide/labels/#syntax-and-character-set
clusterName: mycluster # 9
experimental:
awsNodeLabels:
enabled: true
`,
expectedErrorMessage: "awsNodeLabels can't be enabled for controllers because the total number of characters in clusterName(=\"mycluster\") exceeds the limit of 8",
},
{
context: "WithMultiAPIEndpointsInvalidLB",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
apiEndpointName: unversionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
id: elb-internet-facing
private: true
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
`,
expectedErrorMessage: "invalid apiEndpoint \"unversionedPublic\" at index 0: invalid loadBalancer: type, private, subnets, hostedZone must be omitted when id is specified to reuse an existing ELB",
},
{
context: "WithMultiAPIEndpointsInvalidWorkerAPIEndpointName",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
# no api endpoint named like that exists!
apiEndpointName: unknownEndpoint
adminAPIEndpointName: versionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
- name: versionedPublic
dnsName: apiv1.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
`,
expectedErrorMessage: "invalid value for worker.apiEndpointName: no API endpoint named \"unknownEndpoint\" found",
},
{
context: "WithMultiAPIEndpointsInvalidWorkerNodePoolAPIEndpointName",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
# this one is ok but...
apiEndpointName: versionedPublic
nodePools:
- name: pool1
# this one is ng; no api endpoint named this exists!
apiEndpointName: unknownEndpoint
adminAPIEndpointName: versionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
- name: versionedPublic
dnsName: apiv1.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
`,
expectedErrorMessage: "invalid node pool at index 0: failed to find an API endpoint named \"unknownEndpoint\": no API endpoint named \"unknownEndpoint\" defined under the `apiEndpoints[]`",
},
{
context: "WithMultiAPIEndpointsMissingDNSName",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
apiEndpoints:
- name: unversionedPublic
dnsName:
loadBalancer:
hostedZone:
id: hostedzone-public
`,
expectedErrorMessage: "invalid apiEndpoint \"unversionedPublic\" at index 0: dnsName must be set",
},
{
context: "WithMultiAPIEndpointsMissingGlobalAPIEndpointName",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
nodePools:
- name: pool1
# this one is ng; no api endpoint named this exists!
apiEndpointName: unknownEndpoint
- name: pool1
# this one is ng; missing apiEndpointName
adminAPIEndpointName: versionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
- name: versionedPublic
dnsName: apiv1.example.com
loadBalancer:
subnets:
- name: publicSubnet1
hostedZone:
id: hostedzone-public
`,
expectedErrorMessage: "worker.apiEndpointName must not be empty when there're 2 or more API endpoints under the key `apiEndpoints` and one of worker.nodePools[] are missing apiEndpointName",
},
{
context: "WithMultiAPIEndpointsRecordSetImpliedBySubnetsMissingHostedZoneID",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
apiEndpointName: unversionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
# an internet-facing(which is the default) lb in the public subnet is going to be created with a corresponding record set
# however no hosted zone for the record set is provided!
subnets:
- name: publicSubnet1
# missing hosted zone id here!
`,
expectedErrorMessage: "invalid apiEndpoint \"unversionedPublic\" at index 0: invalid loadBalancer: missing hostedZone.id",
},
{
context: "WithMultiAPIEndpointsRecordSetImpliedByExplicitPublicMissingHostedZoneID",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
worker:
apiEndpointName: unversionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
# an internet-facing lb is going to be created with a corresponding record set
# however no hosted zone for the record set is provided!
private: false
# missing hosted zone id here!
`,
expectedErrorMessage: "invalid apiEndpoint \"unversionedPublic\" at index 0: invalid loadBalancer: missing hostedZone.id",
},
{
context: "WithMultiAPIEndpointsRecordSetImpliedByExplicitPrivateMissingHostedZoneID",
configYaml: kubeAwsSettings.mainClusterYamlWithoutAPIEndpoint() + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: publicSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
- name: privateSubnet1
availabilityZone: us-west-1a
instanceCIDR: "10.0.2.0/24"
worker:
apiEndpointName: unversionedPublic
apiEndpoints:
- name: unversionedPublic
dnsName: api.example.com
loadBalancer:
# an internal lb is going to be created with a corresponding record set
# however no hosted zone for the record set is provided!
private: true
# missing hosted zone id here!
`,
expectedErrorMessage: "invalid apiEndpoint \"unversionedPublic\" at index 0: invalid loadBalancer: missing hostedZone.id",
},
{
context: "WithNetworkTopologyAllExistingPrivateSubnetsRejectingExistingIGW",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: private1
availabilityZone: us-west-1a
id: subnet-1
private: true
controller:
loadBalancer:
private: true
etcd:
subnets:
- name: private1
worker:
nodePools:
- name: pool1
subnets:
- name: private1
`,
expectedErrorMessage: `internet gateway id can't be specified when all the subnets are existing private subnets`,
},
{
context: "WithNetworkTopologyAllExistingPublicSubnetsRejectingExistingIGW",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: public1
availabilityZone: us-west-1a
id: subnet-1
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: public1
worker:
nodePools:
- name: pool1
subnets:
- name: public1
`,
expectedErrorMessage: `internet gateway id can't be specified when all the public subnets have existing route tables associated. kube-aws doesn't try to modify an exisinting route table to include a route to the internet gateway`,
},
{
context: "WithNetworkTopologyAllManagedPublicSubnetsWithExistingRouteTableRejectingExistingIGW",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
subnets:
- name: public1
availabilityZone: us-west-1a
instanceCIDR: 10.0.1.0/24
routeTable:
id: subnet-1
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: public1
worker:
nodePools:
- name: pool1
subnets:
- name: public1
`,
expectedErrorMessage: `internet gateway id can't be specified when all the public subnets have existing route tables associated. kube-aws doesn't try to modify an exisinting route table to include a route to the internet gateway`,
},
{
context: "WithNetworkTopologyAllManagedPublicSubnetsMissingExistingIGW",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
#misses this
#internetGateway:
# id: igw-1a2b3c4d
subnets:
- name: public1
availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
controller:
loadBalancer:
private: false
etcd:
subnets:
- name: public1
worker:
nodePools:
- name: pool1
subnets:
- name: public1
`,
expectedErrorMessage: `internet gateway id can't be omitted when there're one or more managed public subnets in an existing VPC`,
},
{
context: "WithNetworkTopologyAllPreconfiguredPrivateDeprecatedAndThenRemoved",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
# This, in combination with mapPublicIPs=false, had been implying that the route table contains a route to a preconfigured NAT gateway
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-276008202
routeTableId: rtb-1a2b3c4d
# This had been implied that all the subnets created by kube-aws should be private
mapPublicIPs: false
subnets:
- availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
# implies
# private: true
# routeTable
# id: rtb-1a2b3c4d
- availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
# implies
# private: true
# routeTable
# id: rtb-1a2b3c4d
`,
expectedErrorMessage: "internet gateway id can't be omitted when there're one or more managed public subnets in an existing VPC",
},
{
context: "WithNetworkTopologyAllPreconfiguredPublicDeprecatedAndThenRemoved",
configYaml: mainClusterYaml + `
vpc:
id: vpc-1a2b3c4d
# This, in combination with mapPublicIPs=true, had been implying that the route table contains a route to a preconfigured internet gateway
# See https://github.com/kubernetes-incubator/kube-aws/pull/284#issuecomment-276008202
routeTableId: rtb-1a2b3c4d
# This had been implied that all the subnets created by kube-aws should be public
mapPublicIPs: true
# internetGateway.id should be omitted as we assume that the route table specified by routeTableId already contain a route to one
#internetGateway:
# id:
subnets:
- availabilityZone: us-west-1a
instanceCIDR: "10.0.1.0/24"
# #implies
# private: false
# routeTable
# id: rtb-1a2b3c4d
- availabilityZone: us-west-1b
instanceCIDR: "10.0.2.0/24"
# #implies
# private: false
# routeTable
# id: rtb-1a2b3c4d
`,
expectedErrorMessage: "internet gateway id can't be omitted when there're one or more managed public subnets in an existing VPC",
},
{
context: "WithVpcIdAndVPCCIDRSpecified",
configYaml: minimalValidConfigYaml + `
vpc:
id: vpc-1a2b3c4d
internetGateway:
id: igw-1a2b3c4d
# vpcCIDR (10.1.0.0/16) does not contain instanceCIDR (10.0.1.0/24)
vpcCIDR: "10.1.0.0/16"
`,
},
{
context: "WithRouteTableIdSpecified",
configYaml: minimalValidConfigYaml + `
# vpc.id must be specified if routeTableId is specified
routeTableId: rtb-1a2b3c4d
`,
},
{
context: "WithWorkerSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
- sg-23456789
- sg-bcdefabc
- sg-34567890
`,
expectedErrorMessage: "number of user provided security groups must be less than or equal to 4 but was 5",
},
{
context: "WithWorkerAndLBSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
- sg-23456789
loadBalancer:
enabled: true
securityGroupIds:
- sg-bcdefabc
- sg-34567890
`,
expectedErrorMessage: "number of user provided security groups must be less than or equal to 4 but was 5",
},
{
context: "WithWorkerAndALBSecurityGroupIds",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
securityGroupIds:
- sg-12345678
- sg-abcdefab
- sg-23456789
targetGroup:
enabled: true
securityGroupIds:
- sg-bcdefabc
- sg-34567890
`,
expectedErrorMessage: "number of user provided security groups must be less than or equal to 4 but was 5",
},
{
context: "WithUnknownKeyInRoot",
configYaml: minimalValidConfigYaml + `
foo: bar
`,
expectedErrorMessage: "unknown keys found: foo",
},
{
context: "WithUnknownKeyInController",
configYaml: minimalValidConfigYaml + `
controller:
foo: 1
`,
expectedErrorMessage: "unknown keys found in controller: foo",
},
{
context: "WithUnknownKeyInControllerASG",
configYaml: minimalValidConfigYaml + `
controller:
autoScalingGroup:
foo: 1
`,
expectedErrorMessage: "unknown keys found in controller.autoScalingGroup: foo",
},
{
context: "WithUnknownKeyInEtcd",
configYaml: minimalValidConfigYaml + `
etcd:
foo: 1
`,
expectedErrorMessage: "unknown keys found in etcd: foo",
},
{
context: "WithUnknownKeyInWorkerNodePool",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
clusterAutoscaler:
enabled: true
`,
expectedErrorMessage: "unknown keys found in worker.nodePools[0]: clusterAutoscaler",
},
{
context: "WithUnknownKeyInWorkerNodePoolASG",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
autoScalingGroup:
foo: 1
`,
expectedErrorMessage: "unknown keys found in worker.nodePools[0].autoScalingGroup: foo",
},
{
context: "WithUnknownKeyInWorkerNodePoolSpotFleet",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
spotFleet:
bar: 1
`,
expectedErrorMessage: "unknown keys found in worker.nodePools[0].spotFleet: bar",
},
{
context: "WithUnknownKeyInAddons",
configYaml: minimalValidConfigYaml + `
addons:
blah: 5
`,
expectedErrorMessage: "unknown keys found in addons: blah",
},
{
context: "WithUnknownKeyInReschedulerAddon",
configYaml: minimalValidConfigYaml + `
addons:
rescheduler:
foo: yeah
`,
expectedErrorMessage: "unknown keys found in addons.rescheduler: foo",
},
{
context: "WithTooLongControllerIAMRoleName",
configYaml: kubeAwsSettings.withClusterName("kubeaws-it-main").withRegion("ap-northeast-1").minimumValidClusterYaml() + `
controller:
iam:
role:
name: foobarba-foobarba-foobarba-foobarba-foobarba-foobarba
`,
expectedErrorMessage: "IAM role name(=kubeaws-it-main-ap-northeast-1-foobarba-foobarba-foobarba-foobarba-foobarba-foobarba) will be 84 characters long. It exceeds the AWS limit of 64 characters: clusterName(=kubeaws-it-main) + region name(=ap-northeast-1) + managed iam role name(=foobarba-foobarba-foobarba-foobarba-foobarba-foobarba) should be less than or equal to 33",
},
{
context: "WithTooLongWorkerIAMRoleName",
configYaml: kubeAwsSettings.withClusterName("kubeaws-it-main").withRegion("ap-northeast-1").minimumValidClusterYaml() + `
worker:
nodePools:
- name: pool1
iam:
role:
name: foobarba-foobarba-foobarba-foobarba-foobarba-foobarbazzz
`,
expectedErrorMessage: "IAM role name(=kubeaws-it-main-ap-northeast-1-foobarba-foobarba-foobarba-foobarba-foobarba-foobarbazzz) will be 87 characters long. It exceeds the AWS limit of 64 characters: clusterName(=kubeaws-it-main) + region name(=ap-northeast-1) + managed iam role name(=foobarba-foobarba-foobarba-foobarba-foobarba-foobarbazzz) should be less than or equal to 33",
},
{
context: "WithInvalidEtcdInstanceProfileArn",
configYaml: minimalValidConfigYaml + `
etcd:
iam:
instanceProfile:
arn: "badArn"
`,
expectedErrorMessage: "invalid etcd settings: invalid instance profile, your instance profile must match (=arn:aws:iam::YOURACCOUNTID:instance-profile/INSTANCEPROFILENAME), provided (badArn)",
},
{
context: "WithInvalidEtcdManagedPolicyArn",
configYaml: minimalValidConfigYaml + `
etcd:
iam:
role:
managedPolicies:
- arn: "badArn"
`,
expectedErrorMessage: "invalid etcd settings: invalid managed policy arn, your managed policy must match this (=arn:aws:iam::(YOURACCOUNTID|aws):policy/POLICYNAME), provided this (badArn)",
},
{
context: "WithInvalidWorkerInstanceProfileArn",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
iam:
instanceProfile:
arn: "badArn"
`,
expectedErrorMessage: "invalid instance profile, your instance profile must match (=arn:aws:iam::YOURACCOUNTID:instance-profile/INSTANCEPROFILENAME), provided (badArn)",
},
{
context: "WithInvalidWorkerManagedPolicyArn",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
iam:
role:
managedPolicies:
- arn: "badArn"
`,
expectedErrorMessage: "invalid managed policy arn, your managed policy must match this (=arn:aws:iam::(YOURACCOUNTID|aws):policy/POLICYNAME), provided this (badArn)",
},
{
context: "WithGPUEnabledWorkerButEmptyVersion",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
instanceType: p2.xlarge
gpu:
nvidia:
enabled: true
version: ""
`,
expectedErrorMessage: `gpu.nvidia.version must not be empty when gpu.nvidia is enabled.`,
},
{
context: "WithGPUDisabledWorkerButIntallationSupportEnabled",
configYaml: minimalValidConfigYaml + `
worker:
nodePools:
- name: pool1
instanceType: t2.medium
gpu:
nvidia:
enabled: true
version: ""
`,
expectedErrorMessage: `instance type t2.medium doesn't support GPU. You can enable Nvidia driver intallation support only when use [p2 p3 g2 g3] instance family.`,
},
}
for _, invalidCase := range parseErrorCases {
t.Run(invalidCase.context, func(t *testing.T) {
configBytes := invalidCase.configYaml
// TODO Allow including plugins in test data?
plugins := []*api.Plugin{}
providedConfig, err := config.ConfigFromBytes([]byte(configBytes), plugins)
if err == nil {
t.Errorf("expected to fail parsing config %s: %+v: %+v", configBytes, *providedConfig, err)
t.FailNow()
}
errorMsg := fmt.Sprintf("%v", err)
if !strings.Contains(errorMsg, invalidCase.expectedErrorMessage) {
t.Errorf(`expected "%s" to be contained in the error message : %s`, invalidCase.expectedErrorMessage, errorMsg)
}
})
}
}
|
[
"\"KUBE_AWS_INTEGRATION_TEST\""
] |
[] |
[
"KUBE_AWS_INTEGRATION_TEST"
] |
[]
|
["KUBE_AWS_INTEGRATION_TEST"]
|
go
| 1 | 0 | |
modules/msp/menu/menu.service.go
|
// Copyright (c) 2021 Terminus, 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 menu
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/ahmetb/go-linq/v3"
"github.com/erda-project/erda-proto-go/msp/menu/pb"
tenantpb "github.com/erda-project/erda-proto-go/msp/tenant/pb"
"github.com/erda-project/erda/bundle"
instancedb "github.com/erda-project/erda/modules/msp/instance/db"
"github.com/erda-project/erda/modules/msp/menu/db"
"github.com/erda-project/erda/pkg/common/errors"
)
type menuService struct {
p *provider
db *db.MenuConfigDB
instanceTenantDB *instancedb.InstanceTenantDB
instanceDB *instancedb.InstanceDB
bdl *bundle.Bundle
version string
}
var NotExist = map[string]bool{
//"LogAnalyze": true,
//"APIGateway": true,
//"RegisterCenter": true,
//"ConfigCenter": true,
//"AlarmManagement": true,
"AlertCenter": true,
"ServiceManage": true,
}
var DopMenu = map[string]bool{
"MonitorCenter": true,
"ServiceManage": true,
"EnvironmentSet": true,
}
type componentInfo struct {
cnName string
enName string
}
var ComponentInfo = map[string]*componentInfo{
"MonitorCenter": {
enName: "MonitorCenter",
cnName: "应用监控",
},
"LogAnalyze": {
enName: "LogAnalyze",
cnName: "日志分析",
},
"APIGateway": {
enName: "APIGateway",
cnName: "API网关",
},
"RegisterCenter": {
enName: "RegisterCenter",
cnName: "注册中心",
},
"ConfigCenter": {
enName: "ConfigCenter",
cnName: "配置中心",
},
}
var splitEDAS = strings.ToLower(os.Getenv("SPLIT_EDAS_CLUSTER_TYPE")) == "true"
//GetMenu api
func (s *menuService) GetMenu(ctx context.Context, req *pb.GetMenuRequest) (*pb.GetMenuResponse, error) {
//监控中心保留服务监控,诊断分析保留链路追踪、错误分析
// get menu items
items, err := s.getMenuItems()
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if req.Type == tenantpb.Type_MSP.String() {
var mspItems []*pb.MenuItem
for _, item := range items {
if NotExist[item.Key] {
continue
}
params := s.composeMSPMenuParams(req)
item.Params = params
for _, child := range item.Children {
child.Params = params
}
mspItems = append(mspItems, item)
}
items = mspItems
}
// get cluster info
if req.Type != tenantpb.Type_MSP.String() {
clusterName, err := s.instanceTenantDB.GetClusterNameByTenantGroup(req.TenantId)
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if len(clusterName) <= 0 {
return nil, errors.NewNotFoundError("TenantGroup.ClusterName")
}
clusterInfo, err := s.bdl.QueryClusterInfo(clusterName)
if err != nil {
return nil, errors.NewServiceInvokingError("QueryClusterInfo", err)
}
clusterType := clusterInfo.Get("DICE_CLUSTER_TYPE")
menuMap := make(map[string]*pb.MenuItem)
for _, item := range items {
isK8s := clusterInfo.IsK8S() || (!splitEDAS && clusterInfo.IsEDAS())
if DopMenu[item.Key] {
for _, child := range item.Children {
child.Params = item.Params
// 反转exists字段,隐藏引导页,显示功能子菜单
child.Exists = !child.Exists
if child.OnlyK8S && !isK8s {
child.Exists = false
}
if child.OnlyNotK8S && isK8s {
child.Exists = false
}
if child.MustExists {
child.Exists = true
}
}
}
item.ClusterName = clusterName
item.ClusterType = clusterType
for _, child := range item.Children {
if len(child.Href) > 0 {
child.Href = s.version + child.Href
}
menuMap[child.Key] = child
}
menuMap[item.Key] = item
}
configs, err := s.getEngineConfigs(req.TenantId, req.TenantId)
if err != nil {
return nil, err
}
for engine, config := range configs {
menuKey, err := s.db.GetMicroServiceEngineKey(engine)
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if len(menuKey) <= 0 {
continue
}
item := menuMap[menuKey]
if item == nil {
return nil, errors.NewDatabaseError(fmt.Errorf("not found menu by key %q", menuKey))
}
// setup params
item.Params = make(map[string]string)
paramsStr := config["PUBLIC_HOST"]
if len(paramsStr) > 0 {
params := make(map[string]interface{})
err := json.Unmarshal([]byte(paramsStr), ¶ms)
if err != nil {
return nil, errors.NewDatabaseError(fmt.Errorf("PUBLIC_HOST format error"))
}
for k, v := range params {
item.Params[k] = fmt.Sprint(v)
}
}
if engine != "monitor" {
item.Params["_enabled"] = "true"
}
// setup exists
isK8s := clusterInfo.IsK8S() || (!splitEDAS && clusterInfo.IsEDAS())
for _, child := range item.Children {
child.Params = item.Params
// 反转exists字段,隐藏引导页,显示功能子菜单
child.Exists = !child.Exists
if child.OnlyK8S && !isK8s {
child.Exists = false
}
if child.OnlyNotK8S && isK8s {
child.Exists = false
}
if child.MustExists {
child.Exists = true
}
}
}
}
if items == nil {
items = make([]*pb.MenuItem, 0)
}
return &pb.GetMenuResponse{Data: s.adjustMenuParams(items)}, nil
}
func (s *menuService) composeMSPMenuParams(req *pb.GetMenuRequest) map[string]string {
params := map[string]string{}
params["key"] = "Overview"
params["tenantGroup"] = req.TenantId
params["tenantId"] = req.TenantId
params["terminusKey"] = req.TenantId
return params
}
// GetSetting api
func (s *menuService) GetSetting(ctx context.Context, req *pb.GetSettingRequest) (*pb.GetSettingResponse, error) {
configs, err := s.getEngineConfigs(req.TenantGroup, req.TenantId)
if err != nil {
return nil, err
}
settings := make([]*pb.EngineSetting, 0)
for engine, config := range configs {
menuKey, err := s.db.GetMicroServiceEngineKey(engine)
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if len(menuKey) <= 0 {
continue
}
item := ComponentInfo[menuKey]
if item == nil {
return nil, errors.NewDatabaseError(fmt.Errorf("not found menu by key %q", menuKey))
}
if _, ok := config["PUBLIC_HOST"]; ok {
delete(config, "PUBLIC_HOST")
}
settings = append(settings, &pb.EngineSetting{
AddonName: engine,
Config: config,
CnName: item.cnName,
EnName: item.enName,
})
}
return &pb.GetSettingResponse{Data: settings}, nil
}
func (s *menuService) getMenuItems() ([]*pb.MenuItem, error) {
menuIni, err := s.db.GetMicroServiceMenu()
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if menuIni == nil {
return nil, nil
}
var list []*pb.MenuItem
err = json.Unmarshal([]byte(menuIni.IniValue), &list)
if err != nil {
return nil, fmt.Errorf("microservice menu config format error")
}
return list, nil
}
func (s *menuService) getEngineConfigs(group, tenantID string) (map[string]map[string]string, error) {
tenants, err := s.instanceTenantDB.GetByTenantGroup(group)
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if len(tenants) <= 0 {
return nil, nil
}
configs := make(map[string]map[string]string)
for _, tenant := range tenants {
// 针对配置中心一个tenantGroup下有多个tenantId的情况,tenantId与请求一致时,允许覆盖
if configs[tenant.Engine] == nil || tenant.ID == tenantID {
instance, err := s.instanceDB.GetByID(tenant.InstanceID)
if err != nil {
return nil, errors.NewDatabaseError(err)
}
if instance == nil {
return nil, errors.NewDatabaseError(fmt.Errorf("fail to find instance by id=%s", tenant.InstanceID))
}
config := make(map[string]string)
if len(instance.Config) > 0 {
instanceConfig := make(map[string]interface{})
err = json.Unmarshal([]byte(instance.Config), &instanceConfig)
if err != nil {
return nil, errors.NewDatabaseError(fmt.Errorf("fail to unmarshal instance config: %w", err))
}
for k, v := range instanceConfig {
config[k] = fmt.Sprint(v)
}
}
if len(tenant.Config) > 0 {
tenantConfig := make(map[string]interface{})
err = json.Unmarshal([]byte(tenant.Config), &tenantConfig)
if err != nil {
return nil, errors.NewDatabaseError(fmt.Errorf("fail to unmarshal tenant config: %w", err))
}
for k, v := range tenantConfig {
config[k] = fmt.Sprint(v)
}
}
// 兼容已经创建的日志分析租户,新创建的日志分析会有 PUBLIC_HOST
if tenant.Engine == "log-analytics" {
byts, _ := json.Marshal(map[string]interface{}{
"tenantId": tenant.ID,
"tenantGroup": tenant.TenantGroup,
"logKey": tenant.ID,
"key": "LogQuery",
})
config["PUBLIC_HOST"] = string(byts)
}
configs[tenant.Engine] = config
}
}
// if both log-analytics and log-service addon exists, use log-service config only
if _, ok := configs["log-service"]; ok {
delete(configs, "log-analytics")
}
return configs, nil
}
func (s *menuService) adjustMenuParams(items []*pb.MenuItem) []*pb.MenuItem {
//var overview, monitor, loghub *pb.MenuItem
var monitor, loghub *pb.MenuItem
setParams := make([]*pb.MenuItem, 0)
for _, item := range items {
if item.Params == nil {
setParams = append(setParams, item)
}
switch item.Key {
case "MonitorCenter":
monitor = item
case "DiagnoseAnalyzer":
loghub, _ = linq.From(item.Children).
FirstWith(func(i interface{}) bool { return i.(*pb.MenuItem).Key == "LogAnalyze" }).(*pb.MenuItem)
}
}
if monitor != nil {
for _, item := range setParams {
item.Params = monitor.Params
for _, child := range item.Children {
if child.Params != nil {
continue
}
child.Params = monitor.Params
}
}
if loghub != nil {
if loghub.Params == nil {
loghub.Params = make(map[string]string)
}
loghub.Params["terminusKey"] = monitor.Params["terminusKey"]
}
}
return items
}
|
[
"\"SPLIT_EDAS_CLUSTER_TYPE\""
] |
[] |
[
"SPLIT_EDAS_CLUSTER_TYPE"
] |
[]
|
["SPLIT_EDAS_CLUSTER_TYPE"]
|
go
| 1 | 0 | |
tool/gravity/cli/utils.go
|
/*
Copyright 2018 Gravitational, 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 cli
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/gravitational/gravity/lib/defaults"
"github.com/gravitational/gravity/lib/httplib"
"github.com/gravitational/gravity/lib/install"
"github.com/gravitational/gravity/lib/localenv"
"github.com/gravitational/gravity/lib/ops"
"github.com/gravitational/gravity/lib/pack/webpack"
"github.com/gravitational/gravity/lib/processconfig"
rpcserver "github.com/gravitational/gravity/lib/rpc/server"
"github.com/gravitational/gravity/lib/state"
"github.com/gravitational/gravity/lib/storage"
"github.com/gravitational/gravity/lib/systeminfo"
"github.com/gravitational/gravity/lib/utils"
"github.com/gravitational/gravity/tool/common"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
// LocalEnvironmentFactory defines an interface for creating operation-specific environments
type LocalEnvironmentFactory interface {
// NewLocalEnv creates a new default environment.
// It will use the location pointer file to find the location of the custom state
// directory if available and will fall back to defaults.GravityDir otherwise.
// All other environments are located under this common root directory
NewLocalEnv() (*localenv.LocalEnvironment, error)
// TODO(dmitri): generalize operation environment under a single
// NewOperationEnv API
// NewUpdateEnv creates a new environment for update operations
NewUpdateEnv() (*localenv.LocalEnvironment, error)
// NewJoinEnv creates a new environment for join operations
NewJoinEnv() (*localenv.LocalEnvironment, error)
}
// NewLocalEnv returns an instance of the local environment.
func (g *Application) NewLocalEnv() (env *localenv.LocalEnvironment, err error) {
localStateDir, err := getLocalStateDir(*g.StateDir)
if err != nil {
return nil, trace.Wrap(err)
}
return g.getEnv(localStateDir)
}
// NewInstallEnv returns an instance of the local environment for commands that
// initialize cluster environment (i.e. install or join).
func (g *Application) NewInstallEnv() (env *localenv.LocalEnvironment, err error) {
stateDir := *g.StateDir
if stateDir == "" {
stateDir = defaults.LocalGravityDir
} else {
stateDir = filepath.Join(stateDir, defaults.LocalDir)
}
return g.getEnv(stateDir)
}
// NewUpdateEnv returns an instance of the local environment that is used
// only for updates
func (g *Application) NewUpdateEnv() (*localenv.LocalEnvironment, error) {
dir, err := state.GetStateDir()
if err != nil {
return nil, trace.Wrap(err)
}
return g.getEnv(state.GravityUpdateDir(dir))
}
// NewJoinEnv returns an instance of local environment where join-specific data is stored
func (g *Application) NewJoinEnv() (*localenv.LocalEnvironment, error) {
const failImmediatelyIfLocked = -1
stateDir, err := state.GravityInstallDir()
if err != nil {
return nil, trace.Wrap(err)
}
err = os.MkdirAll(stateDir, defaults.SharedDirMask)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
return g.getEnvWithArgs(localenv.LocalEnvironmentArgs{
StateDir: stateDir,
Insecure: *g.Insecure,
Silent: localenv.Silent(*g.Silent),
Debug: *g.Debug,
EtcdRetryTimeout: *g.EtcdRetryTimeout,
BoltOpenTimeout: failImmediatelyIfLocked,
Reporter: common.ProgressReporter(*g.Silent),
})
}
func (g *Application) getEnv(stateDir string) (*localenv.LocalEnvironment, error) {
return g.getEnvWithArgs(localenv.LocalEnvironmentArgs{
StateDir: stateDir,
Insecure: *g.Insecure,
Silent: localenv.Silent(*g.Silent),
Debug: *g.Debug,
EtcdRetryTimeout: *g.EtcdRetryTimeout,
Reporter: common.ProgressReporter(*g.Silent),
})
}
func (g *Application) getEnvWithArgs(args localenv.LocalEnvironmentArgs) (*localenv.LocalEnvironment, error) {
if *g.StateDir != defaults.LocalGravityDir {
args.LocalKeyStoreDir = *g.StateDir
}
// set insecure in devmode so we won't need to use
// --insecure flag all the time
cfg, _, err := processconfig.ReadConfig("")
if err == nil && cfg.Devmode {
args.Insecure = true
}
return localenv.NewLocalEnvironment(args)
}
// isUpdateCommand returns true if the specified command is
// an upgrade related command
func (g *Application) isUpdateCommand(cmd string) bool {
switch cmd {
case g.PlanCmd.FullCommand(),
g.PlanDisplayCmd.FullCommand(),
g.PlanExecuteCmd.FullCommand(),
g.PlanRollbackCmd.FullCommand(),
g.PlanResumeCmd.FullCommand(),
g.PlanCompleteCmd.FullCommand(),
g.UpdatePlanInitCmd.FullCommand(),
g.UpdateTriggerCmd.FullCommand(),
g.UpgradeCmd.FullCommand():
return true
case g.RPCAgentRunCmd.FullCommand():
return len(*g.RPCAgentRunCmd.Args) > 0
case g.RPCAgentDeployCmd.FullCommand():
return len(*g.RPCAgentDeployCmd.LeaderArgs) > 0 ||
len(*g.RPCAgentDeployCmd.NodeArgs) > 0
}
return false
}
// isExpandCommand returns true if the specified command is
// expand-related command
func (g *Application) isExpandCommand(cmd string) bool {
switch cmd {
case g.AutoJoinCmd.FullCommand(),
g.PlanCmd.FullCommand(),
g.PlanDisplayCmd.FullCommand(),
g.PlanExecuteCmd.FullCommand(),
g.PlanRollbackCmd.FullCommand(),
g.PlanCompleteCmd.FullCommand(),
g.PlanResumeCmd.FullCommand():
return true
}
return false
}
// ConfigureNoProxy configures the current process to not use any configured HTTP proxy when connecting to any
// destination by IP address, or a domain with a suffix of .local. Gravity internally connects to nodes by IP address,
// and by queries to kubernetes using the .local suffix. The side effect is, connections towards the internet by IP
// address and not a configured domain name will not be able to invoke a proxy. This should be a reasonable tradeoff,
// because with a cluster that changes over time, it's difficult for us to accuratly detect what IP addresses need to
// have no_proxy set.
func ConfigureNoProxy() {
// The golang HTTP proxy env variable detection only uses the first detected http proxy env variable
// so we need to grab both to make sure we edit the correct one.
// https://github.com/golang/net/blob/c21de06aaf072cea07f3a65d6970e5c7d8b6cd6d/http/httpproxy/proxy.go#L91-L107
proxy := map[string]string{
"NO_PROXY": os.Getenv("NO_PROXY"),
"no_proxy": os.Getenv("no_proxy"),
}
for k, v := range proxy {
if len(v) != 0 {
os.Setenv(k, strings.Join([]string{v, "0.0.0.0/0", ".local"}, ","))
return
}
}
os.Setenv("NO_PROXY", strings.Join([]string{"0.0.0.0/0", ".local"}, ","))
}
func getLocalStateDir(stateDir string) (localStateDir string, err error) {
if stateDir != "" {
// If state directory has been explicitly specified on command line,
// use it
return stateDir, nil
}
stateDir, err = state.GetStateDir()
if err != nil {
return "", trace.Wrap(err)
}
return filepath.Join(stateDir, defaults.LocalDir), nil
}
// findServer searches the provided cluster's state for a server that matches one of the provided
// tokens, where a token can be the server's advertise IP, hostname or AWS internal DNS name
func findServer(site ops.Site, tokens []string) (*storage.Server, error) {
for _, server := range site.ClusterState.Servers {
for _, token := range tokens {
if token == "" {
continue
}
switch token {
case server.AdvertiseIP, server.Hostname, server.Nodename:
return &server, nil
}
}
}
return nil, trace.NotFound("could not find server matching %v among registered cluster nodes",
tokens)
}
// findLocalServer searches the provided cluster's state for the server that matches the one
// the current command is being executed from
func findLocalServer(site ops.Site) (*storage.Server, error) {
// collect the machines's IP addresses and search by them
ifaces, err := systeminfo.NetworkInterfaces()
if err != nil {
return nil, trace.Wrap(err)
}
if len(ifaces) == 0 {
return nil, trace.NotFound("no network interfaces found")
}
var ips []string
for _, iface := range ifaces {
ips = append(ips, iface.IPv4)
}
server, err := findServer(site, ips)
if err != nil {
return nil, trace.Wrap(err)
}
return server, nil
}
func isCancelledError(err error) bool {
if err == nil {
return false
}
return trace.IsCompareFailed(err) && strings.Contains(err.Error(), "cancelled")
}
func watchReconnects(ctx context.Context, cancel context.CancelFunc, watchCh <-chan rpcserver.WatchEvent) {
go func() {
for event := range watchCh {
if event.Error == nil {
continue
}
log.Warnf("Failed to reconnect to %v: %v.", event.Peer, event.Error)
cancel()
return
}
}()
}
func loadRPCCredentials(ctx context.Context, addr, token string) (*rpcserver.Credentials, error) {
// Assume addr to be a complete address if it's prefixed with `http`
if !strings.Contains(addr, "http") {
host, port := utils.SplitHostPort(addr, strconv.Itoa(defaults.GravitySiteNodePort))
addr = fmt.Sprintf("https://%v:%v", host, port)
}
httpClient := roundtrip.HTTPClient(httplib.GetClient(true))
packages, err := webpack.NewBearerClient(addr, token, httpClient)
if err != nil {
return nil, trace.Wrap(err)
}
creds, err := install.LoadRPCCredentials(ctx, packages)
if err != nil {
return nil, trace.Wrap(err)
}
return creds, nil
}
func parseArgs(args []string) (*kingpin.ParseContext, error) {
app := kingpin.New("gravity", "")
return RegisterCommands(app).ParseContext(args)
}
|
[
"\"NO_PROXY\"",
"\"no_proxy\""
] |
[] |
[
"NO_PROXY",
"no_proxy"
] |
[]
|
["NO_PROXY", "no_proxy"]
|
go
| 2 | 0 | |
imagenet/.ipynb_checkpoints/main-checkpoint.py
|
import argparse
import os
import random
import shutil
import time
import warnings
from enum import Enum
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('data', metavar='DIR',
help='path to dataset')
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',
choices=model_names,
help='model architecture: ' +
' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N',
help='mini-batch size (default: 256), this is the total '
'batch size of all GPUs on the current node when '
'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)',
dest='weight_decay')
parser.add_argument('-p', '--print-freq', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--world-size', default=-1, type=int,
help='number of nodes for distributed training')
parser.add_argument('--rank', default=-1, type=int,
help='node rank for distributed training')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='nccl', type=str,
help='distributed backend')
parser.add_argument('--seed', default=None, type=int,
help='seed for initializing training. ')
parser.add_argument('--gpu', default=None, type=int,
help='GPU id to use.')
parser.add_argument('--multiprocessing-distributed', action='store_true',
help='Use multi-processing distributed training to launch '
'N processes per node, which has N GPUs. This is the '
'fastest way to use PyTorch for either single node or '
'multi node data parallel training')
best_acc1 = 0
def main():
args = parser.parse_args()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
warnings.warn('You have chosen to seed training. '
'This will turn on the CUDNN deterministic setting, '
'which can slow down your training considerably! '
'You may see unexpected behavior when restarting '
'from checkpoints.')
if args.gpu is not None:
warnings.warn('You have chosen a specific GPU. This will completely '
'disable data parallelism.')
if args.dist_url == "env://" and args.world_size == -1:
args.world_size = int(os.environ["WORLD_SIZE"])
args.distributed = args.world_size > 1 or args.multiprocessing_distributed
ngpus_per_node = torch.cuda.device_count()
if args.multiprocessing_distributed:
# Since we have ngpus_per_node processes per node, the total world_size
# needs to be adjusted accordingly
args.world_size = ngpus_per_node * args.world_size
# Use torch.multiprocessing.spawn to launch distributed processes: the
# main_worker process function
mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
else:
# Simply call main_worker function
main_worker(args.gpu, ngpus_per_node, args)
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
if args.distributed:
if args.dist_url == "env://" and args.rank == -1:
args.rank = int(os.environ["RANK"])
if args.multiprocessing_distributed:
# For multiprocessing distributed training, rank needs to be the
# global rank among all the processes
args.rank = args.rank * ngpus_per_node + gpu
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size, rank=args.rank)
# create model
if args.pretrained:
print("=> using pre-trained model '{}'".format(args.arch))
model = models.__dict__[args.arch](pretrained=True)
else:
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
if not torch.cuda.is_available():
print('using CPU, this will be slow')
elif args.distributed:
# For multiprocessing distributed, DistributedDataParallel constructor
# should always set the single device scope, otherwise,
# DistributedDataParallel will use all available devices.
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model.cuda(args.gpu)
# When using a single GPU per process and per
# DistributedDataParallel, we need to divide the batch size
# ourselves based on the total number of GPUs we have
args.batch_size = int(args.batch_size / ngpus_per_node)
args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
else:
model.cuda()
# DistributedDataParallel will divide and allocate batch_size to all
# available GPUs if device_ids are not set
model = torch.nn.parallel.DistributedDataParallel(model)
elif args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
else:
# DataParallel will divide and allocate batch_size to all available GPUs
if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
model.features = torch.nn.DataParallel(model.features)
model.cuda()
else:
model = torch.nn.DataParallel(model).cuda()
# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().cuda(args.gpu)
optimizer = torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# optionally resume from a checkpoint
if args.resume:
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
if args.gpu is None:
checkpoint = torch.load(args.resume)
else:
# Map model to be loaded to specified single gpu.
loc = 'cuda:{}'.format(args.gpu)
checkpoint = torch.load(args.resume, map_location=loc)
args.start_epoch = checkpoint['epoch']
best_acc1 = checkpoint['best_acc1']
if args.gpu is not None:
# best_acc1 may be from a checkpoint from a different GPU
best_acc1 = best_acc1.to(args.gpu)
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
print("=> loaded checkpoint '{}' (epoch {})"
.format(args.resume, checkpoint['epoch']))
else:
print("=> no checkpoint found at '{}'".format(args.resume))
cudnn.benchmark = True
# Data loading code
# traindir = os.path.join(args.data, 'train')
valdir = os.path.join(args.data, 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# train_dataset = datasets.ImageFolder(
# traindir,
# transforms.Compose([
# transforms.RandomResizedCrop(224),
# transforms.RandomHorizontalFlip(),
# transforms.ToTensor(),
# normalize,
# ]))
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
else:
train_sampler = None
# train_loader = torch.utils.data.DataLoader(
# train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
# num_workers=args.workers, pin_memory=True, sampler=train_sampler)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
if args.evaluate:
validate(val_loader, model, criterion, args)
return
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
train_sampler.set_epoch(epoch)
adjust_learning_rate(optimizer, epoch, args)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch, args)
# evaluate on validation set
acc1 = validate(val_loader, model, criterion, args)
# remember best acc@1 and save checkpoint
is_best = acc1 > best_acc1
best_acc1 = max(acc1, best_acc1)
if not args.multiprocessing_distributed or (args.multiprocessing_distributed
and args.rank % ngpus_per_node == 0):
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_acc1': best_acc1,
'optimizer' : optimizer.state_dict(),
}, is_best)
def train(train_loader, model, criterion, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch))
# switch to train mode
model.train()
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if torch.cuda.is_available():
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter('Time', ':6.3f', Summary.NONE)
losses = AverageMeter('Loss', ':.4e', Summary.NONE)
top1 = AverageMeter('Acc@1', ':6.2f', Summary.AVERAGE)
top5 = AverageMeter('Acc@5', ':6.2f', Summary.AVERAGE)
progress = ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5],
prefix='Test: ')
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if torch.cuda.is_available():
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
progress.display_summary()
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
class Summary(Enum):
NONE = 0
AVERAGE = 1
SUM = 2
COUNT = 3
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE):
self.name = name
self.fmt = fmt
self.summary_type = summary_type
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def __str__(self):
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
return fmtstr.format(**self.__dict__)
def summary(self):
fmtstr = ''
if self.summary_type is Summary.NONE:
fmtstr = ''
elif self.summary_type is Summary.AVERAGE:
fmtstr = '{name} {avg:.3f}'
elif self.summary_type is Summary.SUM:
fmtstr = '{name} {sum:.3f}'
elif self.summary_type is Summary.COUNT:
fmtstr = '{name} {count:.3f}'
else:
raise ValueError('invalid summary type %r' % self.summary_type)
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print('\t'.join(entries))
def display_summary(self):
entries = [" *"]
entries += [meter.summary() for meter in self.meters]
print(' '.join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = '{:' + str(num_digits) + 'd}'
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
|
[] |
[] |
[
"RANK",
"WORLD_SIZE"
] |
[]
|
["RANK", "WORLD_SIZE"]
|
python
| 2 | 0 | |
selfdrive/car/interfaces.py
|
import os
import time
from typing import Dict
from cereal import car
from common.kalman.simple_kalman import KF1D
from common.realtime import DT_CTRL
from selfdrive.car import gen_empty_fingerprint
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX
from selfdrive.controls.lib.events import Events
from selfdrive.controls.lib.vehicle_model import VehicleModel
GearShifter = car.CarState.GearShifter
EventName = car.CarEvent.EventName
# WARNING: this value was determined based on the model's training distribution,
# model predictions above this speed can be unpredictable
MAX_CTRL_SPEED = (V_CRUISE_MAX + 4) * CV.KPH_TO_MS # 135 + 4 = 86 mph
# generic car and radar interfaces
class CarInterfaceBase():
def __init__(self, CP, CarController, CarState):
self.CP = CP
self.VM = VehicleModel(CP)
self.hzCounter = 0
self.frame = 0
self.low_speed_alert = False
if CarState is not None:
self.CS = CarState(CP)
self.cp = self.CS.get_can_parser(CP)
self.cp_cam = self.CS.get_cam_can_parser(CP)
self.cp_body = self.CS.get_body_can_parser(CP)
self.CC = None
if CarController is not None:
self.CC = CarController(self.cp.dbc_name, CP, self.VM)
@staticmethod
def calc_accel_override(a_ego, a_target, v_ego, v_target):
return 1.
@staticmethod
def compute_gb(accel, speed):
raise NotImplementedError
@staticmethod
def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None):
raise NotImplementedError
# returns a set of default params to avoid repetition in car specific params
@staticmethod
def get_std_params(candidate, fingerprint):
ret = car.CarParams.new_message()
ret.carFingerprint = candidate
# standard ALC params
ret.steerControlType = car.CarParams.SteerControlType.torque
ret.steerMaxBP = [0.]
ret.steerMaxV = [1.]
ret.minSteerSpeed = 0.
# stock ACC by default
ret.enableCruise = True
ret.minEnableSpeed = -1. # enable is done by stock ACC, so ignore this
ret.steerRatioRear = 0. # no rear steering, at least on the listed cars aboveA
ret.gasMaxBP = [0.]
ret.gasMaxV = [.5] # half max brake
ret.brakeMaxBP = [0.]
ret.brakeMaxV = [1.]
ret.openpilotLongitudinalControl = False
ret.startAccel = 0.0
ret.minSpeedCan = 0.3
ret.stoppingBrakeRate = 0.023 # brake_travel/s while trying to stop
ret.startingBrakeRate = 2.5 # brake_travel/s while releasing on restart
ret.stoppingControl = False
ret.longitudinalTuning.deadzoneBP = [0.]
ret.longitudinalTuning.deadzoneV = [0.]
ret.longitudinalTuning.kpBP = [0.]
ret.longitudinalTuning.kpV = [1.]
ret.longitudinalTuning.kiBP = [0.]
ret.longitudinalTuning.kiV = [1.]
return ret
# returns a car.CarState, pass in car.CarControl
def update(self, c, can_strings):
raise NotImplementedError
# return sendcan, pass in a car.CarControl
def apply(self, c):
raise NotImplementedError
def create_common_events(self, cs_out, extra_gears=[], gas_resume_speed=-1, pcm_enable=True): # pylint: disable=dangerous-default-value
events = Events()
if cs_out.doorOpen:
events.add(EventName.doorOpen)
if cs_out.seatbeltUnlatched:
events.add(EventName.seatbeltNotLatched)
if cs_out.gearShifter != GearShifter.drive and cs_out.gearShifter not in extra_gears:
events.add(EventName.wrongGear)
if cs_out.gearShifter == GearShifter.reverse:
events.add(EventName.reverseGear)
if not cs_out.cruiseState.available:
events.add(EventName.wrongCarMode)
if cs_out.espDisabled:
events.add(EventName.espDisabled)
if cs_out.gasPressed:
events.add(EventName.gasPressed)
if cs_out.stockFcw:
events.add(EventName.stockFcw)
if cs_out.stockAeb:
events.add(EventName.stockAeb)
if cs_out.vEgo > MAX_CTRL_SPEED:
events.add(EventName.speedTooHigh)
if cs_out.cruiseState.nonAdaptive:
events.add(EventName.wrongCruiseMode)
if not cs_out.lkMode:
events.add(EventName.manualSteeringRequired)
elif cs_out.steerError and cs_out.lkMode:
self.hzCounter += 1
if self.hzCounter > 300: #This will allow for LKAS Fault for 3 seconds before throwing error. -wirelessnet2
events.add(EventName.steerUnavailable)
self.hzCounter = 301 #Clamp the value of hzCounter -wirelessnet2
elif cs_out.steerWarning and cs_out.lkMode:
if cs_out.steeringPressed:
events.add(EventName.steerTempUnavailableUserOverride)
else:
events.add(EventName.steerTempUnavailable)
if not getattr(self.CS, "steer_error", False):
self.hzCounter = 0
# Disable on rising edge of gas or brake. Also disable on brake when speed > 0.
# Optionally allow to press gas at zero speed to resume.
# e.g. Chrysler does not spam the resume button yet, so resuming with gas is handy. FIXME!
if (cs_out.brakePressed and (not self.CS.out.brakePressed or not cs_out.standstill)):
events.add(EventName.pedalPressed)
if cs_out.cruiseState.enabled and (cs_out.gasPressed and (not self.CS.out.gasPressed) and cs_out.vEgo > gas_resume_speed):
events.add(EventName.pedalPressed)
# we engage when pcm is active (rising edge)
if pcm_enable:
if cs_out.cruiseState.enabled and not self.CS.out.cruiseState.enabled:
events.add(EventName.pcmEnable)
return events
class RadarInterfaceBase():
def __init__(self, CP):
self.pts = {}
self.delay = 0
self.radar_ts = CP.radarTimeStep
self.no_radar_sleep = 'NO_RADAR_SLEEP' in os.environ
def update(self, can_strings):
ret = car.RadarData.new_message()
if not self.no_radar_sleep:
time.sleep(self.radar_ts) # radard runs on RI updates
return ret
class CarStateBase:
def __init__(self, CP):
self.CP = CP
self.car_fingerprint = CP.carFingerprint
self.out = car.CarState.new_message()
self.cruise_buttons = 0
self.left_blinker_cnt = 0
self.right_blinker_cnt = 0
# Q = np.matrix([[10.0, 0.0], [0.0, 100.0]])
# R = 1e3
self.v_ego_kf = KF1D(x0=[[0.0], [0.0]],
A=[[1.0, DT_CTRL], [0.0, 1.0]],
C=[1.0, 0.0],
K=[[0.12287673], [0.29666309]])
def update_speed_kf(self, v_ego_raw):
if abs(v_ego_raw - self.v_ego_kf.x[0][0]) > 2.0: # Prevent large accelerations when car starts at non zero speed
self.v_ego_kf.x = [[v_ego_raw], [0.0]]
v_ego_x = self.v_ego_kf.update(v_ego_raw)
return float(v_ego_x[0]), float(v_ego_x[1])
def update_blinker(self, blinker_time: int, left_blinker_lamp: bool, right_blinker_lamp: bool):
self.left_blinker_cnt = blinker_time if left_blinker_lamp else max(self.left_blinker_cnt - 1, 0)
self.right_blinker_cnt = blinker_time if right_blinker_lamp else max(self.right_blinker_cnt - 1, 0)
return self.left_blinker_cnt > 0, self.right_blinker_cnt > 0
@staticmethod
def parse_gear_shifter(gear: str) -> car.CarState.GearShifter:
d: Dict[str, car.CarState.GearShifter] = {
'P': GearShifter.park, 'R': GearShifter.reverse, 'N': GearShifter.neutral,
'E': GearShifter.eco, 'T': GearShifter.manumatic, 'D': GearShifter.drive,
'S': GearShifter.sport, 'L': GearShifter.low, 'B': GearShifter.brake
}
return d.get(gear, GearShifter.unknown)
@staticmethod
def get_cam_can_parser(CP):
return None
@staticmethod
def get_body_can_parser(CP):
return None
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
airflow/providers/google/cloud/example_dags/example_compute_igm.py
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Example Airflow DAG that uses IGM-type compute operations:
* copy of Instance Template
* update template in Instance Group Manager
This DAG relies on the following OS environment variables
* GCP_PROJECT_ID - the Google Cloud project where the Compute Engine instance exists
* GCE_ZONE - the zone where the Compute Engine instance exists
Variables for copy template operator:
* GCE_TEMPLATE_NAME - name of the template to copy
* GCE_NEW_TEMPLATE_NAME - name of the new template
* GCE_NEW_DESCRIPTION - description added to the template
Variables for update template in Group Manager:
* GCE_INSTANCE_GROUP_MANAGER_NAME - name of the Instance Group Manager
* SOURCE_TEMPLATE_URL - url of the template to replace in the Instance Group Manager
* DESTINATION_TEMPLATE_URL - url of the new template to set in the Instance Group Manager
"""
import os
from airflow import models
from airflow.providers.google.cloud.operators.compute import (
ComputeEngineCopyInstanceTemplateOperator,
ComputeEngineInstanceGroupUpdateManagerTemplateOperator,
)
from airflow.utils.dates import days_ago
GCP_PROJECT_ID = os.environ.get('GCP_PROJECT_ID', 'example-project')
GCE_ZONE = os.environ.get('GCE_ZONE', 'europe-west1-b')
# [START howto_operator_compute_template_copy_args]
GCE_TEMPLATE_NAME = os.environ.get('GCE_TEMPLATE_NAME', 'instance-template-test')
GCE_NEW_TEMPLATE_NAME = os.environ.get('GCE_NEW_TEMPLATE_NAME', 'instance-template-test-new')
GCE_NEW_DESCRIPTION = os.environ.get('GCE_NEW_DESCRIPTION', 'Test new description')
GCE_INSTANCE_TEMPLATE_BODY_UPDATE = {
"name": GCE_NEW_TEMPLATE_NAME,
"description": GCE_NEW_DESCRIPTION,
"properties": {"machineType": "n1-standard-2"},
}
# [END howto_operator_compute_template_copy_args]
# [START howto_operator_compute_igm_update_template_args]
GCE_INSTANCE_GROUP_MANAGER_NAME = os.environ.get('GCE_INSTANCE_GROUP_MANAGER_NAME', 'instance-group-test')
SOURCE_TEMPLATE_URL = os.environ.get(
'SOURCE_TEMPLATE_URL',
"https://www.googleapis.com/compute/beta/projects/"
+ GCP_PROJECT_ID
+ "/global/instanceTemplates/instance-template-test",
)
DESTINATION_TEMPLATE_URL = os.environ.get(
'DESTINATION_TEMPLATE_URL',
"https://www.googleapis.com/compute/beta/projects/"
+ GCP_PROJECT_ID
+ "/global/instanceTemplates/"
+ GCE_NEW_TEMPLATE_NAME,
)
UPDATE_POLICY = {
"type": "OPPORTUNISTIC",
"minimalAction": "RESTART",
"maxSurge": {"fixed": 1},
"minReadySec": 1800,
}
# [END howto_operator_compute_igm_update_template_args]
with models.DAG(
'example_gcp_compute_igm',
schedule_interval=None, # Override to match your needs
start_date=days_ago(1),
) as dag:
# [START howto_operator_gce_igm_copy_template]
gce_instance_template_copy = ComputeEngineCopyInstanceTemplateOperator(
project_id=GCP_PROJECT_ID,
resource_id=GCE_TEMPLATE_NAME,
body_patch=GCE_INSTANCE_TEMPLATE_BODY_UPDATE,
task_id='gcp_compute_igm_copy_template_task',
)
# [END howto_operator_gce_igm_copy_template]
# Added to check for idempotence
# [START howto_operator_gce_igm_copy_template_no_project_id]
gce_instance_template_copy2 = ComputeEngineCopyInstanceTemplateOperator(
resource_id=GCE_TEMPLATE_NAME,
body_patch=GCE_INSTANCE_TEMPLATE_BODY_UPDATE,
task_id='gcp_compute_igm_copy_template_task_2',
)
# [END howto_operator_gce_igm_copy_template_no_project_id]
# [START howto_operator_gce_igm_update_template]
gce_instance_group_manager_update_template = ComputeEngineInstanceGroupUpdateManagerTemplateOperator(
project_id=GCP_PROJECT_ID,
resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME,
zone=GCE_ZONE,
source_template=SOURCE_TEMPLATE_URL,
destination_template=DESTINATION_TEMPLATE_URL,
update_policy=UPDATE_POLICY,
task_id='gcp_compute_igm_group_manager_update_template',
)
# [END howto_operator_gce_igm_update_template]
# Added to check for idempotence (and without UPDATE_POLICY)
# [START howto_operator_gce_igm_update_template_no_project_id]
gce_instance_group_manager_update_template2 = ComputeEngineInstanceGroupUpdateManagerTemplateOperator(
resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME,
zone=GCE_ZONE,
source_template=SOURCE_TEMPLATE_URL,
destination_template=DESTINATION_TEMPLATE_URL,
task_id='gcp_compute_igm_group_manager_update_template_2',
)
# [END howto_operator_gce_igm_update_template_no_project_id]
gce_instance_template_copy >> gce_instance_template_copy2 >> gce_instance_group_manager_update_template
gce_instance_group_manager_update_template >> gce_instance_group_manager_update_template2
|
[] |
[] |
[
"GCE_INSTANCE_GROUP_MANAGER_NAME",
"GCE_ZONE",
"GCE_NEW_DESCRIPTION",
"SOURCE_TEMPLATE_URL",
"GCE_TEMPLATE_NAME",
"GCP_PROJECT_ID",
"GCE_NEW_TEMPLATE_NAME",
"DESTINATION_TEMPLATE_URL"
] |
[]
|
["GCE_INSTANCE_GROUP_MANAGER_NAME", "GCE_ZONE", "GCE_NEW_DESCRIPTION", "SOURCE_TEMPLATE_URL", "GCE_TEMPLATE_NAME", "GCP_PROJECT_ID", "GCE_NEW_TEMPLATE_NAME", "DESTINATION_TEMPLATE_URL"]
|
python
| 8 | 0 | |
bitbots_motion/bitbots_dynamic_kick/scripts/dummy_client.py
|
#!/usr/bin/env python3
import actionlib
import argparse
import math
import os
import random
import rospy
import sys
from time import sleep
from actionlib_msgs.msg import GoalStatus
from geometry_msgs.msg import Vector3, Quaternion
from bitbots_msgs.msg import KickGoal, KickAction, KickFeedback
from visualization_msgs.msg import Marker
from tf.transformations import quaternion_from_euler
showing_feedback = False
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('ball_y', type=float, help='y position of the ball [m]', default=0)
parser.add_argument('kick_direction', type=float, help='kick direction [°]', default=0)
args = parser.parse_args()
print("Beware: this script may only work when calling it directly on the robot "
"and will maybe result in tf errors otherwise")
print("[..] Initializing node", end='')
rospy.init_node('dynamic_kick_dummy_client', anonymous=True)
marker_pub = rospy.Publisher("debug/dynamic_kick_ball_marker", Marker, queue_size=1)
print("\r[OK] Initializing node")
def done_cb(state, result):
print('Action completed: ', end='')
if state == GoalStatus.PENDING:
print('Pending')
elif state == GoalStatus.ACTIVE:
print('Active')
elif state == GoalStatus.PREEMPTED:
print('Preempted')
elif state == GoalStatus.SUCCEEDED:
print('Succeeded')
elif state == GoalStatus.ABORTED:
print('Aborted')
elif state == GoalStatus.REJECTED:
print('Rejected')
elif state == GoalStatus.PREEMPTING:
print('Preempting')
elif state == GoalStatus.RECALLING:
print('Recalling')
elif state == GoalStatus.RECALLED:
print('Recalled')
elif state == GoalStatus.LOST:
print('Lost')
else:
print('Unknown state', state)
print(str(result))
def active_cb():
print("Server accepted action")
def feedback_cb(feedback):
if len(sys.argv) > 1 and sys.argv[1] == '--feedback':
print('Feedback')
print(feedback)
print()
print('[..] Connecting to action server \'dynamic_kick\'', end='')
sys.stdout.flush()
client = actionlib.SimpleActionClient('dynamic_kick', KickAction)
if not client.wait_for_server():
exit(1)
print('\r[OK] Connecting to action server \'dynamic_kick\'')
print()
goal = KickGoal()
goal.header.stamp = rospy.Time.now()
frame_prefix = "" if os.environ.get("ROS_NAMESPACE") is None else os.environ.get("ROS_NAMESPACE") + "/"
goal.header.frame_id = frame_prefix + "base_footprint"
goal.ball_position.x = 0.2
goal.ball_position.y = args.ball_y
goal.ball_position.z = 0
goal.kick_direction = Quaternion(*quaternion_from_euler(0, 0, math.radians(args.kick_direction)))
goal.kick_speed = 1
"""marker = Marker()
marker.header.stamp = goal.ball_position.header.stamp
marker.header.frame_id = goal.ball_position.header.frame_id
marker.pose.position = goal.ball_position.vector
marker.pose.orientation.w = 1
marker.scale = Vector3(0.05, 0.05, 0.05)
marker.type = Marker.SPHERE
marker.action = Marker.ADD
marker.lifetime = rospy.Duration(8)
marker.color.a = 1
marker.color.r = 1
marker.color.g = 1
marker.color.b = 1
marker.id = 1
marker.frame_locked = True
marker_pub.publish(marker)
"""
client.send_goal(goal)
client.done_cb = done_cb
client.feedback_cb = feedback_cb
client.active_cb = active_cb
print("Sent new goal. Waiting for result")
client.wait_for_result()
|
[] |
[] |
[
"ROS_NAMESPACE"
] |
[]
|
["ROS_NAMESPACE"]
|
python
| 1 | 0 | |
controllers/configuration_controller.go
|
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"reflect"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
batchv1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/oam-dev/terraform-controller/api/types"
crossplane "github.com/oam-dev/terraform-controller/api/types/crossplane-runtime"
"github.com/oam-dev/terraform-controller/api/v1beta1"
"github.com/oam-dev/terraform-controller/api/v1beta2"
tfcfg "github.com/oam-dev/terraform-controller/controllers/configuration"
"github.com/oam-dev/terraform-controller/controllers/provider"
"github.com/oam-dev/terraform-controller/controllers/terraform"
"github.com/oam-dev/terraform-controller/controllers/util"
)
const (
terraformWorkspace = "default"
// WorkingVolumeMountPath is the mount path for working volume
WorkingVolumeMountPath = "/data"
// InputTFConfigurationVolumeName is the volume name for input Terraform Configuration
InputTFConfigurationVolumeName = "tf-input-configuration"
// BackendVolumeName is the volume name for Terraform backend
BackendVolumeName = "tf-backend"
// InputTFConfigurationVolumeMountPath is the volume mount path for input Terraform Configuration
InputTFConfigurationVolumeMountPath = "/opt/tf-configuration"
// BackendVolumeMountPath is the volume mount path for Terraform backend
BackendVolumeMountPath = "/opt/tf-backend"
// terraformContainerName is the name of the container that executes the terraform in the pod
terraformContainerName = "terraform-executor"
)
const (
// TerraformStateNameInSecret is the key name to store Terraform state
TerraformStateNameInSecret = "tfstate"
// TFInputConfigMapName is the CM name for Terraform Input Configuration
TFInputConfigMapName = "tf-%s"
// TFVariableSecret is the Secret name for variables, including credentials from Provider
TFVariableSecret = "variable-%s"
// TFBackendSecret is the Secret name for Kubernetes backend
TFBackendSecret = "tfstate-%s-%s"
)
// TerraformExecutionType is the type for Terraform execution
type TerraformExecutionType string
const (
// TerraformApply is the name to mark `terraform apply`
TerraformApply TerraformExecutionType = "apply"
// TerraformDestroy is the name to mark `terraform destroy`
TerraformDestroy TerraformExecutionType = "destroy"
)
const (
configurationFinalizer = "configuration.finalizers.terraform-controller"
// ClusterRoleName is the name of the ClusterRole for Terraform Job
ClusterRoleName = "tf-executor-clusterrole"
// ServiceAccountName is the name of the ServiceAccount for Terraform Job
ServiceAccountName = "tf-executor-service-account"
)
// ConfigurationReconciler reconciles a Configuration object.
type ConfigurationReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
ProviderName string
}
// +kubebuilder:rbac:groups=terraform.core.oam.dev,resources=configurations,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=terraform.core.oam.dev,resources=configurations/status,verbs=get;update;patch
// Reconcile will reconcile periodically
func (r *ConfigurationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
klog.InfoS("reconciling Terraform Configuration...", "NamespacedName", req.NamespacedName)
configuration, err := tfcfg.Get(ctx, r.Client, req.NamespacedName)
if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
meta := initTFConfigurationMeta(req, configuration)
// add finalizer
var isDeleting = !configuration.ObjectMeta.DeletionTimestamp.IsZero()
if !isDeleting {
if !controllerutil.ContainsFinalizer(&configuration, configurationFinalizer) {
controllerutil.AddFinalizer(&configuration, configurationFinalizer)
if err := r.Update(ctx, &configuration); err != nil {
return ctrl.Result{RequeueAfter: 3 * time.Second}, errors.Wrap(err, "failed to add finalizer")
}
}
}
// pre-check Configuration
if err := r.preCheck(ctx, &configuration, meta); err != nil && !isDeleting {
return ctrl.Result{}, err
}
var tfExecutionJob = &batchv1.Job{}
if err := r.Client.Get(ctx, client.ObjectKey{Name: meta.ApplyJobName, Namespace: meta.Namespace}, tfExecutionJob); err == nil {
if !meta.EnvChanged && tfExecutionJob.Status.Succeeded == int32(1) {
if err := meta.updateApplyStatus(ctx, r.Client, types.Available, types.MessageCloudResourceDeployed); err != nil {
return ctrl.Result{}, err
}
}
}
if isDeleting {
// terraform destroy
klog.InfoS("performing Configuration Destroy", "Namespace", req.Namespace, "Name", req.Name, "JobName", meta.DestroyJobName)
_, err := terraform.GetTerraformStatus(ctx, meta.Namespace, meta.DestroyJobName, terraformContainerName)
if err != nil {
klog.ErrorS(err, "Terraform destroy failed")
if updateErr := meta.updateDestroyStatus(ctx, r.Client, types.ConfigurationDestroyFailed, err.Error()); updateErr != nil {
return ctrl.Result{}, updateErr
}
}
if err := r.terraformDestroy(ctx, req.Namespace, configuration, meta); err != nil {
if err.Error() == types.MessageDestroyJobNotCompleted {
return ctrl.Result{RequeueAfter: 3 * time.Second}, nil
}
return ctrl.Result{RequeueAfter: 3 * time.Second}, errors.Wrap(err, "continue reconciling to destroy cloud resource")
}
configuration, err := tfcfg.Get(ctx, r.Client, req.NamespacedName)
if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if controllerutil.ContainsFinalizer(&configuration, configurationFinalizer) {
controllerutil.RemoveFinalizer(&configuration, configurationFinalizer)
if err := r.Update(ctx, &configuration); err != nil {
return ctrl.Result{RequeueAfter: 3 * time.Second}, errors.Wrap(err, "failed to remove finalizer")
}
}
return ctrl.Result{}, nil
}
// Terraform apply (create or update)
klog.InfoS("performing Terraform Apply (cloud resource create/update)", "Namespace", req.Namespace, "Name", req.Name)
if err := r.terraformApply(ctx, req.Namespace, configuration, meta); err != nil {
if err.Error() == types.MessageApplyJobNotCompleted {
return ctrl.Result{RequeueAfter: 3 * time.Second}, nil
}
return ctrl.Result{RequeueAfter: 3 * time.Second}, errors.Wrap(err, "failed to create/update cloud resource")
}
state, err := terraform.GetTerraformStatus(ctx, meta.Namespace, meta.ApplyJobName, terraformContainerName)
if err != nil {
klog.ErrorS(err, "Terraform apply failed")
if updateErr := meta.updateApplyStatus(ctx, r.Client, state, err.Error()); updateErr != nil {
return ctrl.Result{}, updateErr
}
}
return ctrl.Result{}, nil
}
// TFConfigurationMeta is all the metadata of a Configuration
type TFConfigurationMeta struct {
Name string
Namespace string
ConfigurationType types.ConfigurationType
CompleteConfiguration string
RemoteGit string
RemoteGitPath string
ConfigurationChanged bool
EnvChanged bool
ConfigurationCMName string
BackendSecretName string
ApplyJobName string
DestroyJobName string
Envs []v1.EnvVar
ProviderReference *crossplane.Reference
VariableSecretName string
VariableSecretData map[string][]byte
DeleteResource bool
Credentials map[string]string
// TerraformImage is the Terraform image which can run `terraform init/plan/apply`
TerraformImage string
TerraformBackendNamespace string
BusyboxImage string
GitImage string
}
func initTFConfigurationMeta(req ctrl.Request, configuration v1beta2.Configuration) *TFConfigurationMeta {
var meta = &TFConfigurationMeta{
Namespace: req.Namespace,
Name: req.Name,
ConfigurationCMName: fmt.Sprintf(TFInputConfigMapName, req.Name),
VariableSecretName: fmt.Sprintf(TFVariableSecret, req.Name),
ApplyJobName: req.Name + "-" + string(TerraformApply),
DestroyJobName: req.Name + "-" + string(TerraformDestroy),
}
// githubBlocked mark whether GitHub is blocked in the cluster
githubBlockedStr := os.Getenv("GITHUB_BLOCKED")
if githubBlockedStr == "" {
githubBlockedStr = "false"
}
meta.RemoteGit = tfcfg.ReplaceTerraformSource(configuration.Spec.Remote, githubBlockedStr)
meta.DeleteResource = configuration.Spec.DeleteResource
if configuration.Spec.Path == "" {
meta.RemoteGitPath = "."
} else {
meta.RemoteGitPath = configuration.Spec.Path
}
meta.ProviderReference = tfcfg.GetProviderNamespacedName(configuration)
// Check the existence of Terraform state secret which is used to store TF state file. For detailed information,
// please refer to https://www.terraform.io/docs/language/settings/backends/kubernetes.html#configuration-variables
var backendSecretSuffix string
if configuration.Spec.Backend != nil && configuration.Spec.Backend.SecretSuffix != "" {
backendSecretSuffix = configuration.Spec.Backend.SecretSuffix
} else {
backendSecretSuffix = configuration.Name
}
// Secrets will be named in the format: tfstate-{workspace}-{secret_suffix}
meta.BackendSecretName = fmt.Sprintf(TFBackendSecret, terraformWorkspace, backendSecretSuffix)
return meta
}
func (r *ConfigurationReconciler) terraformApply(ctx context.Context, namespace string, configuration v1beta2.Configuration, meta *TFConfigurationMeta) error {
klog.InfoS("terraform apply job", "Namespace", namespace, "Name", meta.ApplyJobName)
var (
k8sClient = r.Client
tfExecutionJob batchv1.Job
)
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.ApplyJobName, Namespace: namespace}, &tfExecutionJob); err != nil {
if kerrors.IsNotFound(err) {
return meta.assembleAndTriggerJob(ctx, k8sClient, TerraformApply)
}
}
if err := meta.updateTerraformJobIfNeeded(ctx, k8sClient, tfExecutionJob); err != nil {
klog.ErrorS(err, types.ErrUpdateTerraformApplyJob, "Name", meta.ApplyJobName)
return errors.Wrap(err, types.ErrUpdateTerraformApplyJob)
}
if !meta.EnvChanged && tfExecutionJob.Status.Succeeded == int32(1) {
if err := meta.updateApplyStatus(ctx, k8sClient, types.Available, types.MessageCloudResourceDeployed); err != nil {
return err
}
} else {
// start provisioning and check the status of the provision
// If the state is types.InvalidRegion, no need to continue checking
if configuration.Status.Apply.State != types.ConfigurationProvisioningAndChecking &&
configuration.Status.Apply.State != types.InvalidRegion {
if err := meta.updateApplyStatus(ctx, r.Client, types.ConfigurationProvisioningAndChecking, types.MessageCloudResourceProvisioningAndChecking); err != nil {
return err
}
}
}
return nil
}
func (r *ConfigurationReconciler) terraformDestroy(ctx context.Context, namespace string, configuration v1beta2.Configuration, meta *TFConfigurationMeta) error {
var (
destroyJob batchv1.Job
k8sClient = r.Client
)
deletable, err := tfcfg.IsDeletable(ctx, k8sClient, &configuration)
if err != nil {
return err
}
deleteConfigurationDirectly := deletable || !meta.DeleteResource
if !deleteConfigurationDirectly {
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.DestroyJobName, Namespace: meta.Namespace}, &destroyJob); err != nil {
if kerrors.IsNotFound(err) {
if err := r.Client.Get(ctx, client.ObjectKey{Name: configuration.Name, Namespace: configuration.Namespace}, &v1beta2.Configuration{}); err == nil {
if err = meta.assembleAndTriggerJob(ctx, k8sClient, TerraformDestroy); err != nil {
return err
}
}
}
}
if err := meta.updateTerraformJobIfNeeded(ctx, k8sClient, destroyJob); err != nil {
klog.ErrorS(err, types.ErrUpdateTerraformApplyJob, "Name", meta.ApplyJobName)
return errors.Wrap(err, types.ErrUpdateTerraformApplyJob)
}
}
// destroying
if err := meta.updateDestroyStatus(ctx, k8sClient, types.ConfigurationDestroying, types.MessageCloudResourceDestroying); err != nil {
return err
}
// When the deletion Job process succeeded, clean up work is starting.
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.DestroyJobName, Namespace: meta.Namespace}, &destroyJob); err != nil {
return err
}
if destroyJob.Status.Succeeded == int32(1) || deleteConfigurationDirectly {
// 1. delete Terraform input Configuration ConfigMap
if err := meta.deleteConfigMap(ctx, k8sClient); err != nil {
return err
}
// 2. delete connectionSecret
if configuration.Spec.WriteConnectionSecretToReference != nil {
secretName := configuration.Spec.WriteConnectionSecretToReference.Name
secretNameSpace := configuration.Spec.WriteConnectionSecretToReference.Namespace
if err := deleteConnectionSecret(ctx, k8sClient, secretName, secretNameSpace); err != nil {
return err
}
}
// 3. delete apply job
var applyJob batchv1.Job
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.ApplyJobName, Namespace: namespace}, &applyJob); err == nil {
if err := k8sClient.Delete(ctx, &applyJob, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil {
return err
}
}
// 4. delete destroy job
var j batchv1.Job
if err := r.Client.Get(ctx, client.ObjectKey{Name: destroyJob.Name, Namespace: destroyJob.Namespace}, &j); err == nil {
if err := r.Client.Delete(ctx, &j, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil {
return err
}
}
// 5. delete secret which stores variables
klog.InfoS("Deleting the secret which stores variables", "Name", meta.VariableSecretName)
var variableSecret v1.Secret
if err := r.Client.Get(ctx, client.ObjectKey{Name: meta.VariableSecretName, Namespace: meta.Namespace}, &variableSecret); err == nil {
if err := r.Client.Delete(ctx, &variableSecret); err != nil {
return err
}
}
// 6. delete Kubernetes backend secret
klog.InfoS("Deleting the secret which stores Kubernetes backend", "Name", meta.BackendSecretName)
var kubernetesBackendSecret v1.Secret
if err := r.Client.Get(ctx, client.ObjectKey{Name: meta.BackendSecretName, Namespace: meta.TerraformBackendNamespace}, &kubernetesBackendSecret); err == nil {
if err := r.Client.Delete(ctx, &kubernetesBackendSecret); err != nil {
return err
}
}
return nil
}
return errors.New(types.MessageDestroyJobNotCompleted)
}
func (r *ConfigurationReconciler) preCheck(ctx context.Context, configuration *v1beta2.Configuration, meta *TFConfigurationMeta) error {
var k8sClient = r.Client
meta.TerraformImage = os.Getenv("TERRAFORM_IMAGE")
if meta.TerraformImage == "" {
meta.TerraformImage = "oamdev/docker-terraform:1.1.2"
}
meta.TerraformBackendNamespace = os.Getenv("TERRAFORM_BACKEND_NAMESPACE")
if meta.TerraformBackendNamespace == "" {
meta.TerraformBackendNamespace = "vela-system"
}
meta.BusyboxImage = os.Getenv("BUSYBOX_IMAGE")
if meta.BusyboxImage == "" {
meta.BusyboxImage = "busybox:latest"
}
meta.GitImage = os.Getenv("GIT_IMAGE")
if meta.GitImage == "" {
meta.GitImage = "alpine/git:latest"
}
// Validation: 1) validate Configuration itself
configurationType, err := tfcfg.ValidConfigurationObject(configuration)
if err != nil {
if updateErr := meta.updateApplyStatus(ctx, k8sClient, types.ConfigurationStaticCheckFailed, err.Error()); updateErr != nil {
return updateErr
}
return err
}
meta.ConfigurationType = configurationType
// TODO(zzxwill) Need to find an alternative to check whether there is an state backend in the Configuration
// Render configuration with backend
completeConfiguration, err := tfcfg.RenderConfiguration(configuration, meta.TerraformBackendNamespace, configurationType)
if err != nil {
return err
}
meta.CompleteConfiguration = completeConfiguration
if err := meta.storeTFConfiguration(ctx, k8sClient); err != nil {
return err
}
// Check whether configuration(hcl/json) is changed
if err := meta.CheckWhetherConfigurationChanges(ctx, k8sClient, configurationType); err != nil {
return err
}
if meta.ConfigurationChanged {
klog.InfoS("Configuration hanged, reloading...")
if err := meta.updateApplyStatus(ctx, k8sClient, types.ConfigurationReloading, types.ConfigurationReloadingAsHCLChanged); err != nil {
return err
}
// store configuration to ConfigMap
return meta.storeTFConfiguration(ctx, k8sClient)
}
// Check provider
p, err := provider.GetProviderFromConfiguration(ctx, k8sClient, meta.ProviderReference.Namespace, meta.ProviderReference.Name)
if p == nil {
msg := types.ErrProviderNotFound
if err != nil {
msg = err.Error()
}
if updateStatusErr := meta.updateApplyStatus(ctx, k8sClient, types.Authorizing, msg); updateStatusErr != nil {
return errors.Wrap(updateStatusErr, msg)
}
return errors.New(msg)
}
if err := meta.getCredentials(ctx, k8sClient, p); err != nil {
return err
}
// Check whether env changes
if err := meta.prepareTFVariables(configuration); err != nil {
return err
}
var variableInSecret v1.Secret
err = k8sClient.Get(ctx, client.ObjectKey{Name: meta.VariableSecretName, Namespace: meta.Namespace}, &variableInSecret)
switch {
case kerrors.IsNotFound(err):
var secret = v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: meta.VariableSecretName,
Namespace: meta.Namespace,
},
TypeMeta: metav1.TypeMeta{Kind: "Secret"},
Data: meta.VariableSecretData,
}
if err := k8sClient.Create(ctx, &secret); err != nil {
return err
}
case err == nil:
for k, v := range meta.VariableSecretData {
if val, ok := variableInSecret.Data[k]; !ok || !bytes.Equal(v, val) {
meta.EnvChanged = true
klog.Info("Job's env changed")
if err := meta.updateApplyStatus(ctx, k8sClient, types.ConfigurationReloading, types.ConfigurationReloadingAsVariableChanged); err != nil {
return err
}
break
}
}
default:
return err
}
// Apply ClusterRole
return createTerraformExecutorClusterRole(ctx, k8sClient, fmt.Sprintf("%s-%s", meta.Namespace, ClusterRoleName))
}
func (meta *TFConfigurationMeta) updateApplyStatus(ctx context.Context, k8sClient client.Client, state types.ConfigurationState, message string) error {
var configuration v1beta2.Configuration
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.Name, Namespace: meta.Namespace}, &configuration); err == nil {
configuration.Status.Apply = v1beta2.ConfigurationApplyStatus{
State: state,
Message: message,
}
configuration.Status.ObservedGeneration = configuration.Generation
if state == types.Available {
outputs, err := meta.getTFOutputs(ctx, k8sClient, configuration)
if err != nil {
configuration.Status.Apply = v1beta2.ConfigurationApplyStatus{
State: types.GeneratingOutputs,
Message: types.ErrGenerateOutputs + ": " + err.Error(),
}
} else {
configuration.Status.Apply.Outputs = outputs
}
}
return k8sClient.Status().Update(ctx, &configuration)
}
return nil
}
func (meta *TFConfigurationMeta) updateDestroyStatus(ctx context.Context, k8sClient client.Client, state types.ConfigurationState, message string) error {
var configuration v1beta2.Configuration
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.Name, Namespace: meta.Namespace}, &configuration); err == nil {
configuration.Status.Destroy = v1beta2.ConfigurationDestroyStatus{
State: state,
Message: message,
}
return k8sClient.Status().Update(ctx, &configuration)
}
return nil
}
func (meta *TFConfigurationMeta) assembleAndTriggerJob(ctx context.Context, k8sClient client.Client, executionType TerraformExecutionType) error {
// apply rbac
if err := createTerraformExecutorServiceAccount(ctx, k8sClient, meta.Namespace, ServiceAccountName); err != nil {
return err
}
if err := createTerraformExecutorClusterRoleBinding(ctx, k8sClient, meta.Namespace, fmt.Sprintf("%s-%s", meta.Namespace, ClusterRoleName), ServiceAccountName); err != nil {
return err
}
job := meta.assembleTerraformJob(executionType)
return k8sClient.Create(ctx, job)
}
// updateTerraformJob will set deletion finalizer to the Terraform job if its envs are changed, which will result in
// deleting the job. Finally, a new Terraform job will be generated
func (meta *TFConfigurationMeta) updateTerraformJobIfNeeded(ctx context.Context, k8sClient client.Client, job batchv1.Job) error {
// if either one changes, delete the job
if meta.EnvChanged || meta.ConfigurationChanged {
klog.InfoS("about to delete job", "Name", job.Name, "Namespace", job.Namespace)
var j batchv1.Job
if err := k8sClient.Get(ctx, client.ObjectKey{Name: job.Name, Namespace: job.Namespace}, &j); err == nil {
if deleteErr := k8sClient.Delete(ctx, &job, client.PropagationPolicy(metav1.DeletePropagationBackground)); deleteErr != nil {
return deleteErr
}
}
var s v1.Secret
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.VariableSecretName, Namespace: meta.Namespace}, &s); err == nil {
if deleteErr := k8sClient.Delete(ctx, &s); deleteErr != nil {
return deleteErr
}
}
}
return nil
}
func (meta *TFConfigurationMeta) assembleTerraformJob(executionType TerraformExecutionType) *batchv1.Job {
var (
initContainer v1.Container
initContainers []v1.Container
parallelism int32 = 1
completions int32 = 1
backoffLimit int32 = math.MaxInt32
)
executorVolumes := meta.assembleExecutorVolumes()
initContainerVolumeMounts := []v1.VolumeMount{
{
Name: meta.Name,
MountPath: WorkingVolumeMountPath,
},
{
Name: InputTFConfigurationVolumeName,
MountPath: InputTFConfigurationVolumeMountPath,
},
{
Name: BackendVolumeName,
MountPath: BackendVolumeMountPath,
},
}
initContainer = v1.Container{
Name: "prepare-input-terraform-configurations",
Image: meta.BusyboxImage,
ImagePullPolicy: v1.PullIfNotPresent,
Command: []string{
"sh",
"-c",
fmt.Sprintf("cp %s/* %s", InputTFConfigurationVolumeMountPath, WorkingVolumeMountPath),
},
VolumeMounts: initContainerVolumeMounts,
}
initContainers = append(initContainers, initContainer)
hclPath := filepath.Join(BackendVolumeMountPath, meta.RemoteGitPath)
if meta.RemoteGit != "" {
initContainers = append(initContainers,
v1.Container{
Name: "git-configuration",
Image: meta.GitImage,
ImagePullPolicy: v1.PullIfNotPresent,
Command: []string{
"sh",
"-c",
fmt.Sprintf("git clone %s %s && cp -r %s/* %s", meta.RemoteGit, BackendVolumeMountPath,
hclPath, WorkingVolumeMountPath),
},
VolumeMounts: initContainerVolumeMounts,
})
}
return &batchv1.Job{
TypeMeta: metav1.TypeMeta{
Kind: "Job",
APIVersion: "batch/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: meta.Name + "-" + string(executionType),
Namespace: meta.Namespace,
},
Spec: batchv1.JobSpec{
Parallelism: ¶llelism,
Completions: &completions,
BackoffLimit: &backoffLimit,
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
// This annotation will prevent istio-proxy sidecar injection in the pods
// as having the sidecar would have kept the Job in `Running` state and would
// not transition to `Completed`
"sidecar.istio.io/inject": "false",
},
},
Spec: v1.PodSpec{
// InitContainer will copy Terraform configuration files to working directory and create Terraform
// state file directory in advance
InitContainers: initContainers,
// Container terraform-executor will first copy predefined terraform.d to working directory, and
// then run terraform init/apply.
Containers: []v1.Container{{
Name: terraformContainerName,
Image: meta.TerraformImage,
ImagePullPolicy: v1.PullIfNotPresent,
Command: []string{
"bash",
"-c",
fmt.Sprintf("terraform init && terraform %s -lock=false -auto-approve", executionType),
},
VolumeMounts: []v1.VolumeMount{
{
Name: meta.Name,
MountPath: WorkingVolumeMountPath,
},
{
Name: InputTFConfigurationVolumeName,
MountPath: InputTFConfigurationVolumeMountPath,
},
},
Env: meta.Envs,
},
},
ServiceAccountName: ServiceAccountName,
Volumes: executorVolumes,
RestartPolicy: v1.RestartPolicyOnFailure,
},
},
},
}
}
func (meta *TFConfigurationMeta) assembleExecutorVolumes() []v1.Volume {
workingVolume := v1.Volume{Name: meta.Name}
workingVolume.EmptyDir = &v1.EmptyDirVolumeSource{}
inputTFConfigurationVolume := meta.createConfigurationVolume()
tfBackendVolume := meta.createTFBackendVolume()
return []v1.Volume{workingVolume, inputTFConfigurationVolume, tfBackendVolume}
}
func (meta *TFConfigurationMeta) createConfigurationVolume() v1.Volume {
inputCMVolumeSource := v1.ConfigMapVolumeSource{}
inputCMVolumeSource.Name = meta.ConfigurationCMName
inputTFConfigurationVolume := v1.Volume{Name: InputTFConfigurationVolumeName}
inputTFConfigurationVolume.ConfigMap = &inputCMVolumeSource
return inputTFConfigurationVolume
}
func (meta *TFConfigurationMeta) createTFBackendVolume() v1.Volume {
gitVolume := v1.Volume{Name: BackendVolumeName}
gitVolume.EmptyDir = &v1.EmptyDirVolumeSource{}
return gitVolume
}
// TfStateProperty is the tf state property for an output
type TfStateProperty struct {
Value interface{} `json:"value,omitempty"`
Type string `json:"type,omitempty"`
}
// ToProperty converts TfStateProperty type to Property
func (tp *TfStateProperty) ToProperty() (v1beta2.Property, error) {
var (
property v1beta2.Property
err error
)
sv, err := tfcfg.Interface2String(tp.Value)
if err != nil {
return property, errors.Wrap(err, "failed to get terraform state outputs")
}
property = v1beta2.Property{
Type: tp.Type,
Value: sv,
}
return property, err
}
// TFState is Terraform State
type TFState struct {
Outputs map[string]TfStateProperty `json:"outputs"`
}
//nolint:funlen
func (meta *TFConfigurationMeta) getTFOutputs(ctx context.Context, k8sClient client.Client, configuration v1beta2.Configuration) (map[string]v1beta2.Property, error) {
var s = v1.Secret{}
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.BackendSecretName, Namespace: meta.TerraformBackendNamespace}, &s); err != nil {
return nil, errors.Wrap(err, "terraform state file backend secret is not generated")
}
tfStateData, ok := s.Data[TerraformStateNameInSecret]
if !ok {
return nil, fmt.Errorf("failed to get %s from Terraform State secret %s", TerraformStateNameInSecret, s.Name)
}
tfStateJSON, err := util.DecompressTerraformStateSecret(string(tfStateData))
if err != nil {
return nil, errors.Wrap(err, "failed to decompress state secret data")
}
var tfState TFState
if err := json.Unmarshal(tfStateJSON, &tfState); err != nil {
return nil, err
}
outputs := make(map[string]v1beta2.Property)
for k, v := range tfState.Outputs {
property, err := v.ToProperty()
if err != nil {
return outputs, err
}
outputs[k] = property
}
writeConnectionSecretToReference := configuration.Spec.WriteConnectionSecretToReference
if writeConnectionSecretToReference == nil || writeConnectionSecretToReference.Name == "" {
return outputs, nil
}
name := writeConnectionSecretToReference.Name
ns := writeConnectionSecretToReference.Namespace
if ns == "" {
ns = "default"
}
data := make(map[string][]byte)
for k, v := range outputs {
data[k] = []byte(v.Value)
}
var gotSecret v1.Secret
if err := k8sClient.Get(ctx, client.ObjectKey{Name: name, Namespace: ns}, &gotSecret); err != nil {
if kerrors.IsNotFound(err) {
var secret = v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
Labels: map[string]string{
"created-by": "terraform-controller",
},
},
TypeMeta: metav1.TypeMeta{Kind: "Secret"},
Data: data,
}
if err := k8sClient.Create(ctx, &secret); err != nil {
return nil, err
}
}
} else {
gotSecret.Data = data
if err := k8sClient.Update(ctx, &gotSecret); err != nil {
return nil, err
}
}
return outputs, nil
}
func (meta *TFConfigurationMeta) prepareTFVariables(configuration *v1beta2.Configuration) error {
var (
envs []v1.EnvVar
data = map[string][]byte{}
)
if configuration == nil {
return errors.New("configuration is nil")
}
if meta.ProviderReference == nil {
return errors.New("The referenced provider could not be retrieved")
}
tfVariable, err := getTerraformJSONVariable(configuration.Spec.Variable)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to get Terraform JSON variables from Configuration Variables %v", configuration.Spec.Variable))
}
for k, v := range tfVariable {
envValue, err := tfcfg.Interface2String(v)
if err != nil {
return err
}
data[k] = []byte(envValue)
valueFrom := &v1.EnvVarSource{SecretKeyRef: &v1.SecretKeySelector{Key: k}}
valueFrom.SecretKeyRef.Name = meta.VariableSecretName
envs = append(envs, v1.EnvVar{Name: k, ValueFrom: valueFrom})
}
if meta.Credentials == nil {
return errors.New(provider.ErrCredentialNotRetrieved)
}
for k, v := range meta.Credentials {
data[k] = []byte(v)
valueFrom := &v1.EnvVarSource{SecretKeyRef: &v1.SecretKeySelector{Key: k}}
valueFrom.SecretKeyRef.Name = meta.VariableSecretName
envs = append(envs, v1.EnvVar{Name: k, ValueFrom: valueFrom})
}
// make sure the env of the Job is set
if envs == nil {
return errors.New(provider.ErrCredentialNotRetrieved)
}
meta.Envs = envs
meta.VariableSecretData = data
return nil
}
// SetupWithManager setups with a manager
func (r *ConfigurationReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1beta2.Configuration{}).
Complete(r)
}
func getTerraformJSONVariable(tfVariables *runtime.RawExtension) (map[string]interface{}, error) {
variables, err := tfcfg.RawExtension2Map(tfVariables)
if err != nil {
return nil, err
}
var environments = make(map[string]interface{})
for k, v := range variables {
environments[fmt.Sprintf("TF_VAR_%s", k)] = v
}
return environments, nil
}
func (meta *TFConfigurationMeta) deleteConfigMap(ctx context.Context, k8sClient client.Client) error {
var cm v1.ConfigMap
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.ConfigurationCMName, Namespace: meta.Namespace}, &cm); err == nil {
if err := k8sClient.Delete(ctx, &cm); err != nil {
return err
}
}
return nil
}
func deleteConnectionSecret(ctx context.Context, k8sClient client.Client, name, ns string) error {
if len(name) == 0 {
return nil
}
var connectionSecret v1.Secret
if len(ns) == 0 {
ns = "default"
}
if err := k8sClient.Get(ctx, client.ObjectKey{Name: name, Namespace: ns}, &connectionSecret); err == nil {
return k8sClient.Delete(ctx, &connectionSecret)
}
return nil
}
func (meta *TFConfigurationMeta) createOrUpdateConfigMap(ctx context.Context, k8sClient client.Client, data map[string]string) error {
var gotCM v1.ConfigMap
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.ConfigurationCMName, Namespace: meta.Namespace}, &gotCM); err != nil {
if kerrors.IsNotFound(err) {
cm := v1.ConfigMap{
TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ConfigMap"},
ObjectMeta: metav1.ObjectMeta{
Name: meta.ConfigurationCMName,
Namespace: meta.Namespace,
},
Data: data,
}
err := k8sClient.Create(ctx, &cm)
return errors.Wrap(err, "failed to create TF configuration ConfigMap")
}
return err
}
if !reflect.DeepEqual(gotCM.Data, data) {
gotCM.Data = data
return errors.Wrap(k8sClient.Update(ctx, &gotCM), "failed to update TF configuration ConfigMap")
}
return nil
}
func (meta *TFConfigurationMeta) prepareTFInputConfigurationData() map[string]string {
var dataName string
switch meta.ConfigurationType {
case types.ConfigurationJSON:
dataName = types.TerraformJSONConfigurationName
case types.ConfigurationHCL:
dataName = types.TerraformHCLConfigurationName
case types.ConfigurationRemote:
dataName = "terraform-backend.tf"
}
data := map[string]string{dataName: meta.CompleteConfiguration, "kubeconfig": ""}
return data
}
// storeTFConfiguration will store Terraform configuration to ConfigMap
func (meta *TFConfigurationMeta) storeTFConfiguration(ctx context.Context, k8sClient client.Client) error {
data := meta.prepareTFInputConfigurationData()
return meta.createOrUpdateConfigMap(ctx, k8sClient, data)
}
// CheckWhetherConfigurationChanges will check whether configuration is changed
func (meta *TFConfigurationMeta) CheckWhetherConfigurationChanges(ctx context.Context, k8sClient client.Client, configurationType types.ConfigurationType) error {
var cm v1.ConfigMap
if err := k8sClient.Get(ctx, client.ObjectKey{Name: meta.ConfigurationCMName, Namespace: meta.Namespace}, &cm); err != nil {
return err
}
var configurationChanged bool
switch configurationType {
case types.ConfigurationJSON:
meta.ConfigurationChanged = true
return nil
case types.ConfigurationHCL:
configurationChanged = cm.Data[types.TerraformHCLConfigurationName] != meta.CompleteConfiguration
meta.ConfigurationChanged = configurationChanged
if configurationChanged {
klog.InfoS("Configuration HCL changed", "ConfigMap", cm.Data[types.TerraformHCLConfigurationName],
"RenderedCompletedConfiguration", meta.CompleteConfiguration)
}
return nil
case types.ConfigurationRemote:
meta.ConfigurationChanged = false
return nil
}
return errors.New("unknown issue")
}
// getCredentials will get credentials from secret of the Provider
func (meta *TFConfigurationMeta) getCredentials(ctx context.Context, k8sClient client.Client, providerObj *v1beta1.Provider) error {
region, err := tfcfg.SetRegion(ctx, k8sClient, meta.Namespace, meta.Name, providerObj)
if err != nil {
return err
}
credentials, err := provider.GetProviderCredentials(ctx, k8sClient, providerObj, region)
if err != nil {
return err
}
if credentials == nil {
return errors.New(provider.ErrCredentialNotRetrieved)
}
meta.Credentials = credentials
return nil
}
|
[
"\"GITHUB_BLOCKED\"",
"\"TERRAFORM_IMAGE\"",
"\"TERRAFORM_BACKEND_NAMESPACE\"",
"\"BUSYBOX_IMAGE\"",
"\"GIT_IMAGE\""
] |
[] |
[
"GITHUB_BLOCKED",
"BUSYBOX_IMAGE",
"GIT_IMAGE",
"TERRAFORM_BACKEND_NAMESPACE",
"TERRAFORM_IMAGE"
] |
[]
|
["GITHUB_BLOCKED", "BUSYBOX_IMAGE", "GIT_IMAGE", "TERRAFORM_BACKEND_NAMESPACE", "TERRAFORM_IMAGE"]
|
go
| 5 | 0 | |
BacAlign/config.py
|
"""
BacAlign: config module
Configuration settings
"""
#
# MIT License
#
# Copyright (c) 2021 Huanan Shi
#
# 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.
import os
import sys
import configparser
import logging
logger = logging.getLogger(__name__)
def log_settings():
lines = []
lines.append("DATABASE SETTINGS")
lines.append("QIASeq Spike-in miRNA folder = " + ref_QIASeq)
lines.append("miRbase reference miRNA database folder = " + ref_miRbase)
lines.append("MirGeneDB reference pre-mature miRNA database folder = " + ref_MirGeneDB)
lines.append("Reference tRNA database folder = " + ref_GtRNAdb)
lines.append("Reference piRNA database folder = " + ref_piRbase)
lines.append("Non coding RNA reference database folder = " + ref_NONCODE)
lines.append("Reference host genome database folder = " + ref_UCSC)
lines.append("Reference rRNA database folder = " + ref_SILVA)
lines.append("Reference bacterial genomic assemblies folder = " + ref_bacteria)
lines.append("")
lines.append("RUN MODE")
lines.append("resume = " + str(resume))
lines.append("verbose = " + str(verbose))
lines.append("threads = " + str(threads))
lines.append("")
lines.append("ALIGNMENT SETTINGS")
lines.append("cutadapt options = " + str(" ".join(map(str, cutadapt_opts))))
lines.append("bowtie2 options = " + str(" ".join(map(str, bowtie2_align_opts))))
lines.append("")
lines.append("INPUT AND OUTPUT FORMATS")
lines.append("input file format = " + input_format)
lines.append("output file format = " + output_format)
lines.append("log level = " + log_level)
logger.info("\nRun config settings: \n\n" + "\n".join(lines))
user_edit_config_file = "BacAlign.config"
full_path_user_edit_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), user_edit_config_file)
def update_user_edit_config_file_single_item(section, name, value):
new_config_items = {section: { name : value}}
update_user_edit_config_file(new_config_items)
print("BacAlign configuration file updated: " + section + " : " + name + " = " + str(value))
def update_user_edit_config_file(new_config_items):
config = configparser.RawConfigParser()
config_items = read_user_edit_config_file()
for section in new_config_items:
for name, value in new_config_items[section].items():
if section in config_items:
if name in config_items[section]:
config_items[section][name] = value
else:
sys.exit("ERROR: Unable to add new name ( " + name +
" ) to existing section ( " + section + " ) to " +
" config file: " + full_path_user_edit_config_file)
else:
sys.exit("ERROR: Unable to add new section ( " + section +
" ) to config file: " + full_path_user_edit_config_file)
for section in config_items:
config.add_section(section)
for name, value in config_items[section].items():
value = str(value)
if "file" in section or "folder" in section:
# convert to absolute path if needed
if not os.path.isabs(value):
value=os.path.abspath(value)
config.set(section,name,value)
try:
file_handle = open(full_path_user_edit_config_file, "wt")
config.write(file_handle)
file_handle.close()
except EnvironmentError:
sys.exit("Unable to write to the BacAlign config file.")
def read_user_edit_config_file():
config = configparser.ConfigParser()
try:
config.read(full_path_user_edit_config_file)
except EnvironmentError:
sys.exit("Unable to read from the config file: " + full_path_user_edit_config_file)
config_items = {}
for section in config.sections():
config_list = config.items(section)
config_items[section] = {}
for name, value in config_list:
if "file" in section or "folder" in section:
if not os.path.isabs(value):
value = os.path.abspath(os.path.join(os.path.dirname(full_path_user_edit_config_file), value))
config_items[section][name] = value
return config_items
def get_item(config_items, section, name, type=None):
try:
value = config_items[section][name]
except KeyError:
sys.exit("CRITICAL ERROR: Unable to load value from " + full_path_user_edit_config_file +
" . \nItem not found. \nItem should be in section (" + section + ") with name (" + name + ").")
if type:
try:
if type == "string":
value = str(value)
elif type == "int":
value = int(value)
elif type == "float":
value = float(value)
elif type == "bool":
if value in ["False", "false", "F", "f"]:
value = False
elif value in ["True", "true", "T", "t"]:
value = True
else:
raise ValueError
except ValueError:
sys.exit("CRITICAL ERROR: Unable to load value from " + full_path_user_edit_config_file +
" . \nItem found in section (" + section + ") with name (" + name + "). " +
"\nItem is not of type (" + type + ").")
return value
config_items=read_user_edit_config_file()
ref_QIASeq = get_item(config_items, "database_folders", "ref_QIASeq", "string")
ref_miRbase = get_item(config_items, "database_folders", "ref_miRbase", "string")
ref_MirGeneDB = get_item(config_items, "database_folders", "ref_MirGeneDB", "string")
ref_GtRNAdb = get_item(config_items, "database_folders", "ref_GtRNAdb", "string")
ref_NONCODE = get_item(config_items, "database_folders", "ref_NONCODE", "string")
ref_piRbase = get_item(config_items, "database_folders", "ref_piRbase", "string")
ref_UCSC = get_item(config_items, "database_folders", "ref_UCSC", "string")
ref_SILVA = get_item(config_items, "database_folders", "ref_SILVA", "string")
ref_bacteria = get_item(config_items, "database_folders", "ref_bacteria", "string")
resume = get_item(config_items, "run_modes", "resume", "bool")
verbose = get_item(config_items, "run_modes", "verbose", "bool")
threads = get_item(config_items, "run_modes", "threads", "int")
log_level_choices =["DEBUG","INFO","WARNING","ERROR","CRITICAL"]
log_level = log_level_choices[0]
output_format_choices = ["tsv", "biom"]
output_format = output_format_choices[0]
input_format_choices = ["fastq","fastq.gz","fasta","fasta.gz","sam","bam","blastm8","genetable","biom"]
input_format = input_format_choices[1]
temp_dir = ""
unnamed_temp_dir = ""
file_basename = ""
fasta_extension = ".fa"
bowtie2_index_name = "_bowtie2_index"
nucleotide_alignment_name = "_bowtie2_aligned.sam"
nucleotide_unalignment_name = "_bowtie2_unaligned.fastq.gz"
nucleotide_algined_reads_name_tsv = "_bowtie2_aligned.tsv"
db_prefix_name = {
"ref_QIAseq": "spikein",
"ref_miRbase": ["mature_rno", "hairpin_rno", "mature_other", "hairpin_other"],
"ref_MirGeneDB": "pre_rno",
"ref_GtRNAdb": ["tRNA_rno", "tRNA_bacteria"],
"ref_piRbase": "piRNA_rno",
"ref_NONCODE": "noncode_rno",
"ref_UCSC": "genome_rno",
"ref_SILVA": ["rRNA_rno", "rRNA_138"],
"ref_bacteria": ["cds_bacteria", "genomes_bacteria"]
}
bowtie2_align_opts=["--very-sensitive"]
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
qa/rpc-tests/test_framework/util.py
|
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Copyright (c) 2014-2017 The CephCoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing
#
# Add python-bitcoinrpc to module search path:
import os
import sys
from binascii import hexlify, unhexlify
from base64 import b64encode
from decimal import Decimal, ROUND_DOWN
import json
import random
import shutil
import subprocess
import time
import re
import errno
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
COVERAGE_DIR = None
#Set Mocktime default to OFF.
#MOCKTIME is only needed for scripts that use the
#cached version of the blockchain. If the cached
#version of the blockchain is used without MOCKTIME
#then the mempools will not sync due to IBD.
MOCKTIME = 0
def enable_mocktime():
#For backwared compatibility of the python scripts
#with previous versions of the cache, set MOCKTIME
#to regtest genesis time + (201 * 156)
global MOCKTIME
MOCKTIME = 1417713337 + (201 * 156)
def disable_mocktime():
global MOCKTIME
MOCKTIME = 0
def get_mocktime():
return MOCKTIME
def enable_coverage(dirname):
"""Maintain a log of which RPC calls are made during testing."""
global COVERAGE_DIR
COVERAGE_DIR = dirname
def get_rpc_proxy(url, node_number, timeout=None):
"""
Args:
url (str): URL of the RPC server to call
node_number (int): the node number (or id) that this calls to
Kwargs:
timeout (int): HTTP timeout in seconds
Returns:
AuthServiceProxy. convenience object for making RPC calls.
"""
proxy_kwargs = {}
if timeout is not None:
proxy_kwargs['timeout'] = timeout
proxy = AuthServiceProxy(url, **proxy_kwargs)
proxy.url = url # store URL on proxy for info
coverage_logfile = coverage.get_filename(
COVERAGE_DIR, node_number) if COVERAGE_DIR else None
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def get_mnsync_status(node):
result = node.mnsync("status")
return result['IsSynced']
def wait_to_sync(node):
synced = False
while not synced:
synced = get_mnsync_status(node)
time.sleep(0.5)
def p2p_port(n):
return 11000 + n + os.getpid()%999
def rpc_port(n):
return 12000 + n + os.getpid()%999
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def count_bytes(hex_string):
return len(bytearray.fromhex(hex_string))
def bytes_to_hex_str(byte_str):
return hexlify(byte_str).decode('ascii')
def hex_str_to_bytes(hex_str):
return unhexlify(hex_str.encode('ascii'))
def str_to_b64str(string):
return b64encode(string.encode('utf-8')).decode('ascii')
def sync_blocks(rpc_connections, wait=1):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc_connections ]
if counts == [ counts[0] ]*len(counts):
break
time.sleep(wait)
def sync_mempools(rpc_connections, wait=1):
"""
Wait until everybody has the same transactions in their memory
pools
"""
while True:
pool = set(rpc_connections[0].getrawmempool())
num_match = 1
for i in range(1, len(rpc_connections)):
if set(rpc_connections[i].getrawmempool()) == pool:
num_match = num_match+1
if num_match == len(rpc_connections):
break
time.sleep(wait)
def sync_masternodes(rpc_connections):
for node in rpc_connections:
wait_to_sync(node)
bitcoind_processes = {}
def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n))
if not os.path.isdir(datadir):
os.makedirs(datadir)
with open(os.path.join(datadir, "cephcoin.conf"), 'w') as f:
f.write("regtest=1\n")
f.write("rpcuser=rt\n")
f.write("rpcpassword=rt\n")
f.write("port="+str(p2p_port(n))+"\n")
f.write("rpcport="+str(rpc_port(n))+"\n")
f.write("listenonion=0\n")
return datadir
def rpc_url(i, rpchost=None):
return "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
def wait_for_bitcoind_start(process, url, i):
'''
Wait for cephcoind to start. This means that RPC is accessible and fully initialized.
Raise an exception if cephcoind exits during initialization.
'''
while True:
if process.poll() is not None:
raise Exception('cephcoind exited with status %i during initialization' % process.returncode)
try:
rpc = get_rpc_proxy(url, i)
blocks = rpc.getblockcount()
break # break out of loop on success
except IOError as e:
if e.errno != errno.ECONNREFUSED: # Port not yet open?
raise # unknown IO error
except JSONRPCException as e: # Initialization phase
if e.error['code'] != -28: # RPC in warmup?
raise # unkown JSON RPC exception
time.sleep(0.25)
def initialize_chain(test_dir):
"""
Create (or copy from cache) a 200-block-long chain and
4 wallets.
"""
if (not os.path.isdir(os.path.join("cache","node0"))
or not os.path.isdir(os.path.join("cache","node1"))
or not os.path.isdir(os.path.join("cache","node2"))
or not os.path.isdir(os.path.join("cache","node3"))):
#find and delete old cache directories if any exist
for i in range(4):
if os.path.isdir(os.path.join("cache","node"+str(i))):
shutil.rmtree(os.path.join("cache","node"+str(i)))
# Create cache directories, run cephcoinds:
for i in range(4):
datadir=initialize_datadir("cache", i)
args = [ os.getenv("CEPHD", "cephcoind"), "-server", "-keypool=1", "-datadir="+datadir, "-discover=0" ]
if i > 0:
args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
bitcoind_processes[i] = subprocess.Popen(args)
if os.getenv("PYTHON_DEBUG", ""):
print "initialize_chain: cephcoind started, waiting for RPC to come up"
wait_for_bitcoind_start(bitcoind_processes[i], rpc_url(i), i)
if os.getenv("PYTHON_DEBUG", ""):
print "initialize_chain: RPC succesfully started"
rpcs = []
for i in range(4):
try:
rpcs.append(get_rpc_proxy(rpc_url(i), i))
except:
sys.stderr.write("Error connecting to "+url+"\n")
sys.exit(1)
# Create a 200-block-long chain; each of the 4 nodes
# gets 25 mature blocks and 25 immature.
# blocks are created with timestamps 156 seconds apart
# starting from 31356 seconds in the past
enable_mocktime()
block_time = get_mocktime() - (201 * 156)
for i in range(2):
for peer in range(4):
for j in range(25):
set_node_times(rpcs, block_time)
rpcs[peer].generate(1)
block_time += 156
# Must sync before next peer starts generating blocks
sync_blocks(rpcs)
# Shut them down, and clean up cache directories:
stop_nodes(rpcs)
wait_bitcoinds()
disable_mocktime()
for i in range(4):
os.remove(log_filename("cache", i, "debug.log"))
os.remove(log_filename("cache", i, "db.log"))
os.remove(log_filename("cache", i, "peers.dat"))
os.remove(log_filename("cache", i, "fee_estimates.dat"))
for i in range(4):
from_dir = os.path.join("cache", "node"+str(i))
to_dir = os.path.join(test_dir, "node"+str(i))
shutil.copytree(from_dir, to_dir)
initialize_datadir(test_dir, i) # Overwrite port/rpcport in cephcoin.conf
def initialize_chain_clean(test_dir, num_nodes):
"""
Create an empty blockchain and num_nodes wallets.
Useful if a test case wants complete control over initialization.
"""
for i in range(num_nodes):
datadir=initialize_datadir(test_dir, i)
def _rpchost_to_args(rpchost):
'''Convert optional IP:port spec to rpcconnect/rpcport args'''
if rpchost is None:
return []
match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
if not match:
raise ValueError('Invalid RPC host spec ' + rpchost)
rpcconnect = match.group(1)
rpcport = match.group(2)
if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
rpcconnect = rpcconnect[1:-1]
rv = ['-rpcconnect=' + rpcconnect]
if rpcport:
rv += ['-rpcport=' + rpcport]
return rv
def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None):
"""
Start a cephcoind and return RPC connection to it
"""
datadir = os.path.join(dirname, "node"+str(i))
if binary is None:
binary = os.getenv("CEPHD", "cephcoind")
# RPC tests still depend on free transactions
args = [ binary, "-datadir="+datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-blockprioritysize=50000", "-mocktime="+str(get_mocktime()) ]
if extra_args is not None: args.extend(extra_args)
bitcoind_processes[i] = subprocess.Popen(args)
if os.getenv("PYTHON_DEBUG", ""):
print "start_node: cephcoind started, waiting for RPC to come up"
url = rpc_url(i, rpchost)
wait_for_bitcoind_start(bitcoind_processes[i], url, i)
if os.getenv("PYTHON_DEBUG", ""):
print "start_node: RPC succesfully started"
proxy = get_rpc_proxy(url, i, timeout=timewait)
if COVERAGE_DIR:
coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)
return proxy
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None, binary=None):
"""
Start multiple cephcoinds, return RPC connections to them
"""
if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
if binary is None: binary = [ None for i in range(num_nodes) ]
rpcs = []
try:
for i in range(num_nodes):
rpcs.append(start_node(i, dirname, extra_args[i], rpchost, binary=binary[i]))
except: # If one node failed to start, stop the others
stop_nodes(rpcs)
raise
return rpcs
def log_filename(dirname, n_node, logname):
return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
def stop_node(node, i):
node.stop()
bitcoind_processes[i].wait()
del bitcoind_processes[i]
def stop_nodes(nodes):
for node in nodes:
node.stop()
del nodes[:] # Emptying array closes connections as a side effect
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def wait_bitcoinds():
# Wait for all bitcoinds to cleanly exit
for bitcoind in bitcoind_processes.values():
bitcoind.wait()
bitcoind_processes.clear()
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:"+str(p2p_port(node_num))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
time.sleep(0.1)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def find_output(node, txid, amount):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >=0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > 0:
t = utxo.pop()
total_in += t["amount"]
inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
if total_in < amount_needed:
raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
return (total_in, inputs)
def make_change(from_node, amount_in, amount_out, fee):
"""
Create change output(s), return them
"""
outputs = {}
amount = amount_out+fee
change = amount_in - amount
if change > amount*2:
# Create an extra change output to break up big inputs
change_address = from_node.getnewaddress()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return outputs
def send_zeropri_transaction(from_node, to_node, amount, fee):
"""
Create&broadcast a zero-priority transaction.
Returns (txid, hex-encoded-txdata)
Ensures transaction is zero-priority by first creating a send-to-self,
then using its output
"""
# Create a send-to-self with confirmed inputs:
self_address = from_node.getnewaddress()
(total_in, inputs) = gather_inputs(from_node, amount+fee*2)
outputs = make_change(from_node, total_in, amount+fee, fee)
outputs[self_address] = float(amount+fee)
self_rawtx = from_node.createrawtransaction(inputs, outputs)
self_signresult = from_node.signrawtransaction(self_rawtx)
self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)
vout = find_output(from_node, self_txid, amount+fee)
# Now immediately spend the output to create a 1-input, 1-output
# zero-priority transaction:
inputs = [ { "txid" : self_txid, "vout" : vout } ]
outputs = { to_node.getnewaddress() : float(amount) }
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"])
def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random zero-priority transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
return (txid, txhex, fee)
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount+fee)
outputs = make_change(from_node, total_in, amount, fee)
outputs[to_node.getnewaddress()] = float(amount)
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"], fee)
def assert_equal(thing1, thing2):
if thing1 != thing2:
raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
try:
fun(*args, **kwds)
except exc:
pass
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionError(
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
def assert_is_hash_string(string, length=64):
if not isinstance(string, basestring):
raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string)))
elif not re.match('[abcdef0-9]+$', string):
raise AssertionError(
"String %r contains invalid characters for a hash." % string)
def assert_array_result(object_array, to_match, expected, should_not_find = False):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
If the should_not_find flag is true, to_match should not be found
in object_array
"""
if should_not_find == True:
assert_equal(expected, { })
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
elif should_not_find == True:
num_matched = num_matched+1
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0 and should_not_find != True:
raise AssertionError("No objects matched %s"%(str(to_match)))
if num_matched > 0 and should_not_find == True:
raise AssertionError("Objects were found %s"%(str(to_match)))
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
# Helper to create at least "count" utxos
# Pass in a fee that is sufficient for relay and mining new transactions.
def create_confirmed_utxos(fee, node, count):
node.generate(int(0.5*count)+101)
utxos = node.listunspent()
iterations = count - len(utxos)
addr1 = node.getnewaddress()
addr2 = node.getnewaddress()
if iterations <= 0:
return utxos
for i in xrange(iterations):
t = utxos.pop()
inputs = []
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr1] = satoshi_round(send_value/2)
outputs[addr2] = satoshi_round(send_value/2)
raw_tx = node.createrawtransaction(inputs, outputs)
signed_tx = node.signrawtransaction(raw_tx)["hex"]
txid = node.sendrawtransaction(signed_tx)
while (node.getmempoolinfo()['size'] > 0):
node.generate(1)
utxos = node.listunspent()
assert(len(utxos) >= count)
return utxos
# Create large OP_RETURN txouts that can be appended to a transaction
# to make it large (helper for constructing large transactions).
def gen_return_txouts():
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
# So we have big transactions (and therefore can't fit very many into each block)
# create one script_pubkey
script_pubkey = "6a4d0200" #OP_RETURN OP_PUSH2 512 bytes
for i in xrange (512):
script_pubkey = script_pubkey + "01"
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
txouts = "81"
for k in xrange(128):
# add txout value
txouts = txouts + "0000000000000000"
# add length of script_pubkey
txouts = txouts + "fd0402"
# add script_pubkey
txouts = txouts + script_pubkey
return txouts
def create_tx(node, coinbase, to_address, amount):
inputs = [{ "txid" : coinbase, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
assert_equal(signresult["complete"], True)
return signresult["hex"]
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
# transaction to make it large. See gen_return_txouts() above.
def create_lots_of_big_transactions(node, txouts, utxos, fee):
addr = node.getnewaddress()
txids = []
for i in xrange(len(utxos)):
t = utxos.pop()
inputs = []
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr] = satoshi_round(send_value)
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + txouts
newtx = newtx + rawtx[94:]
signresult = node.signrawtransaction(newtx, None, None, "NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
txids.append(txid)
return txids
def get_bip9_status(node, key):
info = node.getblockchaininfo()
for row in info['bip9_softforks']:
if row['id'] == key:
return row
raise IndexError ('key:"%s" not found' % key)
|
[] |
[] |
[
"PYTHON_DEBUG",
"CEPHD"
] |
[]
|
["PYTHON_DEBUG", "CEPHD"]
|
python
| 2 | 0 | |
sd/eureka/integration_test.go
|
// +build integration
package eureka
import (
"os"
"testing"
"time"
"github.com/hudl/fargo"
"github.com/go-kit/kit/log"
)
// Package sd/eureka provides a wrapper around the Netflix Eureka service
// registry by way of the Fargo library. This test assumes the user has an
// instance of Eureka available at the address in the environment variable.
// Example `${EUREKA_ADDR}` format: http://localhost:8761/eureka
//
// NOTE: when starting a Eureka server for integration testing, ensure
// the response cache interval is reduced to one second. This can be
// achieved with the following Java argument:
// `-Deureka.server.responseCacheUpdateIntervalMs=1000`
func TestIntegration(t *testing.T) {
eurekaAddr := os.Getenv("EUREKA_ADDR")
if eurekaAddr == "" {
t.Skip("EUREKA_ADDR is not set")
}
logger := log.NewLogfmtLogger(os.Stderr)
logger = log.With(logger, "ts", log.DefaultTimestamp)
var fargoConfig fargo.Config
// Target Eureka server(s).
fargoConfig.Eureka.ServiceUrls = []string{eurekaAddr}
// How often the subscriber should poll for updates.
fargoConfig.Eureka.PollIntervalSeconds = 1
// Create a Fargo connection and a Eureka registrar.
fargoConnection := fargo.NewConnFromConfig(fargoConfig)
registrar1 := NewRegistrar(&fargoConnection, instanceTest1, log.With(logger, "component", "registrar1"))
// Register one instance.
registrar1.Register()
defer registrar1.Deregister()
// Build a Eureka instancer.
instancer := NewInstancer(
&fargoConnection,
appNameTest,
log.With(logger, "component", "instancer"),
)
defer instancer.Stop()
// checks every 100ms (fr up to 10s) for the expected number of instances to be reported
waitForInstances := func(count int) {
for t := 0; t < 100; t++ {
state := instancer.state()
if len(state.Instances) == count {
return
}
time.Sleep(100 * time.Millisecond)
}
state := instancer.state()
if state.Err != nil {
t.Error(state.Err)
}
if want, have := 1, len(state.Instances); want != have {
t.Errorf("want %d, have %d", want, have)
}
}
// We should have one instance immediately after subscriber instantiation.
waitForInstances(1)
// Register a second instance
registrar2 := NewRegistrar(&fargoConnection, instanceTest2, log.With(logger, "component", "registrar2"))
registrar2.Register()
defer registrar2.Deregister() // In case of exceptional circumstances.
// This should be enough time for a scheduled update assuming Eureka is
// configured with the properties mentioned in the function comments.
waitForInstances(2)
// Deregister the second instance.
registrar2.Deregister()
// Wait for another scheduled update.
// And then there was one.
waitForInstances(1)
}
|
[
"\"EUREKA_ADDR\""
] |
[] |
[
"EUREKA_ADDR"
] |
[]
|
["EUREKA_ADDR"]
|
go
| 1 | 0 | |
pruning/MNIST_PruneDBM_AntiFI.py
|
import warnings
warnings.filterwarnings("ignore")
import os
import sys
import env
import tensorflow as tf
import numpy as np
import pickle
from bm.dbm import DBM
from bm.rbm.rbm import BernoulliRBM, logit_mean
from bm.init_BMs import * # helper functions to initialize, fit and load RBMs and 2 layer DBM
from bm.utils.dataset import *
from bm.utils import *
from rbm_utils.stutils import *
from rbm_utils.fimdiag import * # functions to compute the diagonal of the FIM for RBMs
from copy import deepcopy
import argparse
import random
from shutil import copy
import pathlib
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
from pruning.MNIST_Baselines import *
random.seed(42)
np.random.seed(42)
# if machine has multiple GPUs only use first one
#os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
#os.environ["CUDA_VISIBLE_DEVICES"]="0"
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def main(perc=10, n_sessions=10):
# check that we have access to a GPU and that we only use one!
if tf.test.gpu_device_name():
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
print("Workspace initialized")
else:
print("Consider installing GPU version of TF and running sampling from DBMs on GPU.")
if 'session' in locals() and tf.compat.v1.Session() is not None:
print('Close interactive session')
tf.compat.v1.Session().session.close()
logreg_digits = get_classifier_trained_on_raw_digits()
# Load MNIST
print("\nPreparing data ...\n\n")
train, test = preprocess_MNIST()
bin_X_train = train[0]
y_train = train[1]
bin_X_test = test[0]
y_test = test[1]
n_train = len(bin_X_train)
# path to where models shall be saved
model_path = os.path.join('..', 'models', 'MNIST', f'antiFI_{perc}perc_{n_sessions}sessions')
res_path = os.path.join(model_path,'res')
assert not os.path.exists(model_path), "model path already exists - abort"
os.makedirs(res_path)
path = pathlib.Path(__file__).absolute() # save the script
copy(path, res_path+'/script.py')
# LOAD MODEL
args = get_initial_args()
dbm = get_initial_DBM()
rbm1 = load_rbm1(Struct(**args))
rbm2 = load_rbm2(Struct(**args))
weights = dbm.get_tf_params(scope='weights')
W1 = weights['W']
hb1 = weights['hb']
W2 = weights['W_1']
hb2 = weights['hb_1']
vb = weights['vb']
# adjust parameters of rbm2 to the current ones:
rbm2.set_params(initialized_=False)
rbm2.set_params(vb_init=hb1)
rbm2.set_params(hb_init=hb2)
rbm2.set_params(W_init=W2)
rbm2.init()
masks = dbm.get_tf_params(scope='masks')
rf_mask1 = masks['rf_mask']
prune_mask1 = masks['prune_mask']
rf_mask2 = masks['rf_mask_1']
prune_mask2 = masks['prune_mask_1']
# Variance (true) or heuristic estimate (false)?
USE_VAR = True
# Delete all with an FI of zero (false) or constantly x percent of weights (true)?
CONSTANTLY = False
# Anti-Fi pruning?
ANTI_FI = True
if USE_VAR:
print("Pruning based on variance estimate of FIM diagonal.")
else:
print("Pruning based on heuristic estimate")
THR = perc/100 #threshold for percentile
if ANTI_FI:
THR = round(1-THR,1)
# PREPARE PRUNING
n_iter = n_sessions
n_check = 2
pruning_session = 0
nv = args['n_vis']
nh1 = args['n_hidden'][0]
nh2 = args['n_hidden'][1]
# compute FI before first pruning
SAMPLE_EVERY = 200
samples = dbm.sample_gibbs(n_gibbs_steps=SAMPLE_EVERY, save_model=False, n_runs=n_train)
s_v = samples[:,:nv]
s_h1 = samples[:,nv:nv+nh1]
s_h2 = samples[:,nv+nh1:]
temp_mask1 = rf_mask1 * prune_mask1
samples = np.hstack((s_v, s_h1))
var_est1, heu_est1 = FI_weights_var_heur_estimates(samples, nv, nh1, W1) # call without mask
if USE_VAR:
fi_weights_after_joint_RBM1 = var_est1.reshape((nh1,nv)).T * temp_mask1
else:
fi_weights_after_joint_RBM1 = heu_est1.reshape((nh1,nv)).T * temp_mask1
temp_mask2 = rf_mask2 * prune_mask2
samples = np.hstack((s_h1, s_h2))
var_est2, heu_est2 = FI_weights_var_heur_estimates(samples, nh1, nh2, W2) # call without mask
if USE_VAR:
fi_weights_after_joint_RBM2 = var_est2.reshape((nh2,nh1)).T * temp_mask2
else:
fi_weights_after_joint_RBM2 = heu_est2.reshape((nh2,nh1)).T * temp_mask2
fi_weights2=fi_weights_after_joint_RBM2
if CONSTANTLY:
left = int(len(W1[np.where(rf_mask1!=0)].flatten()) + len(hb1)*len(hb2)) # number of units left
list_n_to_remove = []
for i in range(n_iter):
list_n_to_remove.append(int(THR*left))
left = int(left - list_n_to_remove[i])
np.save(os.path.join(res_path, 'n_to_remove.npy'), np.array(list_n_to_remove))
# create result arrays
res_acc_logreg = np.zeros((n_iter, n_check)) # accuracy of log reg
res_act_weights_L2 = np.zeros((n_iter, n_check)) # active weights layer 2
res_act_weights_L1 = np.zeros((n_iter, n_check)) # active weights layer 1
res_n_hid_L2 = np.zeros((n_iter, n_check)) # number hidden units layer 2
res_n_hid_L1 = np.zeros((n_iter, n_check))
def save_results():
np.save(os.path.join(res_path, 'AccLogReg.npy'), res_acc_logreg)
np.save(os.path.join(res_path, 'n_active_weights_L2.npy'), res_act_weights_L2)
np.save(os.path.join(res_path, 'n_active_weights_L1.npy'), res_act_weights_L1)
np.save(os.path.join(res_path, 'n_hid_units_L2.npy'), res_n_hid_L2)
np.save(os.path.join(res_path, 'n_hid_units_L1.npy'), res_n_hid_L1)
save_results()
# retrain the DBMs for just 10 epochs instead of 20
args['epochs'] = (20, 20, 10)
args['max_epoch'] = 10
active_nh1 = nh1
for it in range(n_iter):
pruning_session += 1
print("\n################## Pruning session", pruning_session, "##################")
print("################## Start pruning both layers based on the same samples ##################")
print("################## Start pruning first layer ##################")
fi_weights1 = fi_weights_after_joint_RBM1.reshape((nv,nh1)) # already computed FI above
new_weights = deepcopy(W1)
temp_mask = rf_mask1 * prune_mask1
perc = np.percentile(fi_weights1[np.where(temp_mask!=0)],THR*100)
if not CONSTANTLY:
print("Prune",round(1-THR,1), " percentile of weights with highest FI")
n_pruned = sum(fi_weights1[np.where(temp_mask!=0)].flatten()>perc)
print(n_pruned, "weights of a total of",
len(W1[np.where(temp_mask!=0)].flatten()), "are pruned: ",
n_pruned/len(W1[np.where(temp_mask!=0)].flatten()), "of all weights.")
print("Weights with FI higher than", perc, "pruned")
keep = np.reshape(fi_weights1, (nv, nh1)) <= perc
if CONSTANTLY:
n_pruned = sum(fi_weights1[np.where(temp_mask!=0)].flatten()>perc)
if (n_pruned/len(W1[np.where(temp_mask!=0)].flatten())) < round(1-THR,1):
print(THR, "th percentile = 0, randomly select some more in order to prune ", round(1-THR,1), "of weights.")
# make a copy of the array
copy_fi = deepcopy(fi_weights1)
# indicate indices that are pruned
copy_fi[temp_mask.astype(bool)==0]=-100
copy_fi = copy_fi.flatten()
indices_of_all_remaining = np.where(copy_fi!= -100)
indices_of_all_remaining = np.squeeze(np.asarray(indices_of_all_remaining))
indices_of_all_remaining = set(indices_of_all_remaining)
indices_of_important_ones = np.where(copy_fi > perc)
indices_of_important_ones = np.squeeze(np.asarray(indices_of_important_ones))
indices_of_important_ones = set(indices_of_important_ones)
# that many we have to remove in order to delete 10%:
#n_10_percent = int(round(1-THR,1)*sum(temp_mask.flatten()!=0).flatten())
n_10_percent = list_n_to_remove[it]
# subtract the ones we prune because they have an FI > 0
n_to_remove = n_10_percent - len(indices_of_important_ones)
# get subset of indices where we have to select from
indices_of_all_remaining = indices_of_all_remaining - indices_of_important_ones
# randomly select 10% of all indices where FI is 0
randomly_selected_ones = random.sample(indices_of_all_remaining, n_to_remove)
keep = temp_mask.flatten()
keep[(list(indices_of_important_ones))] = False
keep[(list(randomly_selected_ones))] = False # set them to false
keep = keep.reshape(nv, nh1)
else:
print("Prune",round(1-THR,1), " percentile of weights with highest FI")
perc = np.percentile(fi_weights1[np.where(temp_mask!=0)],THR*100)
print("Weights with FI higher than", perc, "pruned")
print(n_pruned, "weights of a total of",
len(W1[np.where(temp_mask!=0)].flatten()), "are pruned: ",
n_pruned/len(W1[np.where(temp_mask!=0)].flatten()), "of all weights.")
keep = np.reshape(fi_weights1, (nv, nh1)) <= perc
keep[rf_mask1==0]=0 # these weights don't exist anyways
keep[prune_mask1==0]=0
# check how many hidden units in last layer are still connected
no_left_hidden = 0 # number of hidden units left
indices_of_left_hiddens = [] # indices of the ones we keep
for i in range(nh1):
if sum(keep[:,i]!=0):
no_left_hidden+=1
indices_of_left_hiddens.append(i)
print(no_left_hidden, "hidden units in first layer are still connected by weights to visibles.",nh1-no_left_hidden, "unconnected hidden units are removed.")
no_left_visible = 0
indices_of_left_visibles = []
indices_of_lost_visibles = []
for i in range(nv):
if sum(keep[i]!=0):
no_left_visible+=1
indices_of_left_visibles.append(i)
else:
indices_of_lost_visibles.append(i)
print(no_left_visible, "visible units are still connected by weights.", nv-no_left_visible, "unconnected visible units.")
print("Indices of lost visibles:", indices_of_lost_visibles)
keep1 = keep # save mask
new_weights1 = new_weights # save weights
# cannot initialise RBM1 yet because perhaps hidden units of first layer will be removed as a consequence of weight pruning in second layer
# (we remove all unconnected hiddens, even if connected from just one side)
# set number of hidden units in second layer!
# for next layer the hiddens are the visibles
indices_of_left_intermediates = indices_of_left_hiddens
no_left_intermediates = no_left_hidden
############## PRUNE 1 #######################
# prune second layer
print("\nStart pruning second layer")
new_weights = deepcopy(W2)
fi_weights2 = fi_weights2.reshape((nh1,nh2))
temp_mask = rf_mask2 * prune_mask2
perc = np.percentile(fi_weights2[np.where(temp_mask!=0)],THR*100)
if not CONSTANTLY:
print("Prune",round(1-THR,1), " percentile of weights with highest FI")
n_pruned = sum(fi_weights2[np.where(temp_mask!=0)].flatten()>perc)
print(n_pruned, "weights of a total of",
len(W2[np.where(temp_mask!=0)].flatten()), "are pruned: ",
n_pruned/len(W2[np.where(temp_mask!=0)].flatten()), "of all weights.")
print("Weights with FI higher than", perc, "pruned")
keep = np.reshape(fi_weights2, (nh1, nh2)) <= perc
if CONSTANTLY:
n_pruned = sum(fi_weights2[np.where(temp_mask!=0)].flatten()>perc)
if (n_pruned/len(W2[np.where(temp_mask!=0)].flatten())) < round(1-THR,1):
print(perc, "th percentile = 0, randomly select some more in order to prune ", round(1-THR,1), "of weights.")
# make a copy of the array
copy_fi = deepcopy(fi_weights2)
# indicate indices that are pruned
copy_fi[temp_mask.astype(bool)==0]=-100
copy_fi = copy_fi.flatten()
indices_of_all_remaining = np.where(copy_fi!= -100)
indices_of_all_remaining = np.squeeze(np.asarray(indices_of_all_remaining))
indices_of_all_remaining = set(indices_of_all_remaining)
indices_of_important_ones = np.where(copy_fi > perc)
indices_of_important_ones = np.squeeze(np.asarray(indices_of_important_ones))
indices_of_important_ones = set(indices_of_important_ones)
# that many we have to remove in order to delete 10%:
n_10_percent = int(round(1-THR,1)*sum(temp_mask.flatten()!=0).flatten())
# subtract the ones we prune because they have an FI > 0
n_to_remove = n_10_percent - len(indices_of_important_ones)
# get subset of indices where we have to select from
indices_of_all_remaining = indices_of_all_remaining - indices_of_important_ones
# randomly select 10% of all indices where FI is 0
randomly_selected_ones = random.sample(indices_of_all_remaining, n_to_remove)
keep = temp_mask.flatten()
keep[(list(indices_of_important_ones))] = False
keep[(list(randomly_selected_ones))] = False # set them to false
keep = keep.reshape(nh1, nh2)
else:
print("Prune",round(1-THR,1), " percentile of weights with highest FI")
print("Weights with FI higher than", perc, "pruned")
print(n_pruned, "weights of a total of",
len(W2[np.where(temp_mask!=0)].flatten()), "are pruned: ",
n_pruned/len(W2[np.where(temp_mask!=0)].flatten()), "of all weights.")
keep = np.reshape(fi_weights2, (nh1, nh2)) <= perc
keep[rf_mask2==0]=0 # these weights don't exist anyways
keep[prune_mask2==0]=0
# check how many hidden units in last layer are still connected
no_left_hidden = 0 # number of hidden units left
indices_of_left_hiddens = [] # indices of the ones we keep
for i in range(nh2):
if sum(keep[:,i]!=0):
no_left_hidden+=1
indices_of_left_hiddens.append(i)
print(no_left_hidden, "hidden units in last layer are still connected by weights.", nh2-no_left_hidden, "unconnected hidden units are removed.")
no_left_visible_rbm2 = 0
indices_of_left_visibles_rbm2 = []
indices_of_lost_visibles_rbm2 = []
for i in range(nh1):
if sum(keep[i]!=0):
no_left_visible_rbm2+=1
indices_of_left_visibles_rbm2.append(i)
else:
indices_of_lost_visibles_rbm2.append(i)
# only keep the ones that still have connections to both their neighboring layers, otherwise they are lost bc they are dead ends
indices_of_left_intermediate_units=np.intersect1d(indices_of_left_visibles_rbm2, indices_of_left_intermediates)
nh1 = len(indices_of_left_intermediate_units)
print(nh1, "hidden units in intermediate layer are still connected by weights to both layers.", no_left_intermediates-nh1, "are removed.")
# store mask and weights
keep2 = keep
new_weights2 = new_weights
# INITIALISE NEW RBMs and DBM
# now we initialise the new first layer (RBM1)
# get visible and hidden biases
vb = deepcopy(vb)
hb = deepcopy(hb1)
hb = hb[indices_of_left_intermediate_units]
# adjust hidden biases -> gave bad performance
#mean_act_per_neuron = np.mean(s_h1, axis = 0)
#hb = (-1/(1+np.exp(mean_act_per_neuron)))
#hb=hb[indices_of_left_intermediate_units]
# set new weights
new_weights1[keep1==0]=0
new_weights1 = new_weights1[:, indices_of_left_intermediate_units]
keep1 = keep1[:, indices_of_left_intermediate_units]
new_weights1[keep1==0]=0
args['rbm1_dirpath'] = os.path.join(model_path,'MNIST_PrunedRBM1_both_Sess{}/'.format(pruning_session))
args['vb_init']=(vb, -1)
args['hb_init']=(hb, -2)
args['prune']=True
args['n_hidden'] = (nh1, 676)
args['freeze_weights']=keep1
args['w_init']=(new_weights1, 0.1, 0.1)
args['n_vis']=nv
args['filter_shape']=[(20,20)] # deactivate receptive fields, they are now realised over the prune_mask (keep)!!!!!!
print("Shape of new weights of RBM1", new_weights1.shape)
rbm1_pruned = init_rbm1(Struct(**args))
# initialise second layer (RBM2)
# set number of hidden units
nh2 = no_left_hidden
# get visible and hidden biases
hb = deepcopy(hb2)
hb=hb[indices_of_left_hiddens]
vb = deepcopy(hb1)
vb=vb[indices_of_left_intermediate_units]
# set new weights
new_weights2[keep2==0]=0
new_weights2 = new_weights2[:, indices_of_left_hiddens]
new_weights2 = new_weights2[indices_of_left_intermediate_units, :]
keep2 = keep2[:, indices_of_left_hiddens]
keep2 = keep2[indices_of_left_intermediate_units, :]
# set params for new RBM2
args['rbm2_dirpath'] = os.path.join(model_path,'MNIST_PrunedRBM2_both_Sess{}/'.format(pruning_session))
args['vb_init']=(-1, vb)
args['hb_init']=(-2, hb)
args['n_hidden'] = (nh1, nh2)
args['prune']=True
args['freeze_weights']=keep2
args['w_init']=(0.1, new_weights2, 0.1)
print("Shape of new weights of RBM2", new_weights2.shape)
# initialise new RBM2
rbm2_pruned = init_rbm2(Struct(**args))
print("\nInitialize hidden unit particles for DBM...")
Q_train = rbm1_pruned.transform(bin_X_train)
Q_train_bin = make_probs_binary(Q_train)
G_train = rbm2_pruned.transform(Q_train_bin)
G_train_bin = make_probs_binary(G_train)
############## INITIALIZE PRUNED DBM ###################
# initialize new DBM
args['dbm_dirpath']=os.path.join(model_path,'MNIST_PrunedDBM_both_Sess{}/'.format(pruning_session))
dbm_pruned = init_dbm(bin_X_train, None, (rbm1_pruned, rbm2_pruned), Q_train_bin, G_train_bin, Struct(**args))
#run on gpu
config = tf.ConfigProto(
device_count = {'GPU': 1})
dbm_pruned._tf_session_config = config
# do as many samples as training instances
samples = dbm_pruned.sample_gibbs(n_gibbs_steps=SAMPLE_EVERY, save_model=False, n_runs=n_train)
s_v = samples[:,:nv]
s_h1 = samples[:,nv:nv+nh1]
s_h2 = samples[:,nv+nh1:]
mean_activity_v = np.mean(s_v, axis=0)
mean_activity_h1 = np.mean(s_h1, axis=0)
mean_activity_h2 = np.mean(s_h2, axis=0)
np.save(os.path.join(res_path,'mean_activity_v_both_Sess{}_before_retrain'.format(pruning_session)), mean_activity_v)
np.save(os.path.join(res_path,'mean_activity_h1_both_Sess{}_before_retrain'.format(pruning_session)), mean_activity_h1)
np.save(os.path.join(res_path,'mean_activity_h2_both_Sess{}_before_retrain'.format(pruning_session)), mean_activity_h2)
############ EVALUATION 1 ##############
checkpoint=0
res_n_hid_L2[it, checkpoint] = nh2 # save number of left hiddens in layer 2
res_n_hid_L1[it, checkpoint] = nh1
# get masks
masks = dbm_pruned.get_tf_params(scope='masks')
rf_mask1 = masks['rf_mask']
prune_mask1 = masks['prune_mask']
rf_mask2 = masks['rf_mask_1']
prune_mask2 = masks['prune_mask_1']
print("\nPruning session", pruning_session, "checkpoint", checkpoint+1,"\n")
print("After pruning both layers, before joint retraining")
mask2 = rf_mask2 * prune_mask2
active_weights2 = len(mask2.flatten()) - len(mask2[mask2==0].flatten())
mask1 = rf_mask1 * prune_mask1
active_weights1 = len(mask1.flatten()) - len(mask1[mask1==0].flatten())
print("")
print(active_weights1, "active weights in layer 1")
print(active_weights2, "active weights in layer 2\n")
res_act_weights_L2[it, checkpoint] = active_weights2
res_act_weights_L1[it, checkpoint] = active_weights1
# get parameters
weights = dbm_pruned.get_tf_params(scope='weights')
W1 = weights['W']
hb1 = weights['hb']
W2 = weights['W_1']
hb2 = weights['hb_1']
vb = weights['vb']
# compute FI for first layer
samples = np.hstack((s_v, s_h1))
temp_mask1 = rf_mask1 * prune_mask1
print("Computing FI for weights of layer 1")
var_est1, heu_est1 = FI_weights_var_heur_estimates(samples, nv, nh1, W1) # call without mask
if USE_VAR:
fi_weights_after_joint_RBM1 = var_est1.reshape((nh1,nv)).T * temp_mask1 # VARIANCE ESTIMATE!
else:
fi_weights_after_joint_RBM1 = heu_est1.reshape((nh1,nv)).T * temp_mask1 # HEURISTIC ESTIMATE!
np.save(os.path.join(res_path, 'FI_weights_RBM1_before_retrain_sess{}'.format(pruning_session)), fi_weights_after_joint_RBM1)
samples = np.hstack((s_h1, s_h2))
# compute FI for second layer
temp_mask2 = rf_mask2 * prune_mask2
print("Computing FI for weights of layer 2")
var_est2, heu_est2 = FI_weights_var_heur_estimates(samples, nh1, nh2, W2) # call without mask
if USE_VAR:
fi_weights_after_joint_RBM2 = var_est2.reshape((nh2,nh1)).T * temp_mask2 # VARIANCE ESTIMATE
else:
fi_weights_after_joint_RBM2 = heu_est2.reshape((nh2,nh1)).T * temp_mask2 # HEURISTIC ESTIMATE
np.save(os.path.join(res_path, 'FI_weights_RBM2_before_retrain_sess{}'.format(pruning_session)), fi_weights_after_joint_RBM2)
print("\nEvaluate samples similarity to digits...")
pred_probs_samples = logreg_digits.predict_proba(s_v)
prob_winner_pred_samples = pred_probs_samples.max(axis=1)
mean_qual = np.mean(prob_winner_pred_samples)
print("Mean quality of samples", mean_qual, "Std: ", np.std(prob_winner_pred_samples))
ind_winner_pred_samples = np.argmax(pred_probs_samples, axis=1)
sample_class, sample_counts = np.unique(ind_winner_pred_samples, return_counts=True)
dic = dict(zip(sample_class, sample_counts))
print("sample counts per class",dic)
probs=pred_probs_samples.max(axis=1)
mean_qual_d = np.zeros(len(sample_class))
for i in range(0,len(sample_class)):
ind=np.where(ind_winner_pred_samples==sample_class[i])
mean_qual_d[i] = np.mean(probs[ind])
qual_d = [sample_class, mean_qual_d, sample_counts]
print("Weighted (per class frequency) mean quality of samples", np.mean(mean_qual_d))
np.save(os.path.join(res_path, 'ProbsWinDig_sess{}_checkpoint{}.npy'.format(pruning_session, checkpoint+1)), qual_d)
print("\nEvaluate hidden unit representations...")
final_train = dbm_pruned.transform(bin_X_train)
final_test = dbm_pruned.transform(bin_X_test)
print("\nTrain LogReg classifier on final hidden layer...")
logreg_hid = LogisticRegression(multi_class='multinomial', solver='sag', max_iter=800, n_jobs=2, random_state=4444)
logreg_hid.fit(final_train, y_train)
logreg_acc = logreg_hid.score(final_test, y_test)
print("classification accuracy of LogReg classifier", logreg_acc)
res_acc_logreg[it, checkpoint] = logreg_acc
save_results()
# RETRAIN
print("\nRetraining of DBM after pruning both layers...")
dbm_pruned.fit(bin_X_train)
# get parameters
weights = dbm_pruned.get_tf_params(scope='weights')
W1 = weights['W']
hb1 = weights['hb']
W2 = weights['W_1']
hb2 = weights['hb_1']
vb = weights['vb']
checkpoint =1
############ EVALUATION 2 ##############
# after retraining of DBM
print("\nPruning session", pruning_session, "checkpoint", checkpoint+1,"\n")
print("After pruning both layers, after joint retraining")
active_weights2 = len(W2.flatten())- W2[(prune_mask2==0) | (rf_mask2==0)].shape[0]
active_weights1 = len(W1.flatten())- W1[(prune_mask1==0) | (rf_mask1==0)].shape[0]
print("")
print(active_weights1, "active weights in layer 1")
print(active_weights2, "active weights in layer 2\n")
res_act_weights_L2[it, checkpoint] = active_weights2
res_act_weights_L1[it, checkpoint] = active_weights1
res_n_hid_L2[it, checkpoint] = nh2 # save number of left hiddens in layer 2
res_n_hid_L1[it, checkpoint] = nh1
print("\nSampling...")
#run on gpu
config = tf.ConfigProto(
device_count = {'GPU': 1})
dbm_pruned._tf_session_config = config
# do as many samples as training instances
samples = dbm_pruned.sample_gibbs(n_gibbs_steps=SAMPLE_EVERY, save_model=False, n_runs=n_train)
s_v = samples[:,:nv]
s_h1 = samples[:,nv:nv+nh1]
s_h2 = samples[:,nv+nh1:]
mean_activity_v = np.mean(s_v, axis=0)
mean_activity_h1 = np.mean(s_h1, axis=0)
mean_activity_h2 = np.mean(s_h2, axis=0)
np.save(os.path.join(res_path,'mean_activity_v_both_Sess{}_retrained'.format(pruning_session)), mean_activity_v)
np.save(os.path.join(res_path,'mean_activity_h1_both_Sess{}_retrained'.format(pruning_session)), mean_activity_h1)
np.save(os.path.join(res_path,'mean_activity_h2_both_Sess{}_retrained'.format(pruning_session)), mean_activity_h2)
samples = np.hstack((s_v, s_h1))
# compute FI for first layer
temp_mask1 = rf_mask1 * prune_mask1
print("Computing FI for weights of layer 1")
var_est1, heu_est1 = FI_weights_var_heur_estimates(samples, nv, nh1, W1) # call without mask
if USE_VAR:
fi_weights_after_joint_RBM1 = var_est1.reshape((nh1,nv)).T * temp_mask1 # VARIANCE ESTIMATE!
else:
fi_weights_after_joint_RBM1 = heu_est1.reshape((nh1,nv)).T * temp_mask1 # HEURISTIC ESTIMATE!
np.save(os.path.join(res_path, 'FI_weights_RBM1_after_retrain_sess{}'.format(pruning_session)), fi_weights_after_joint_RBM1)
samples = np.hstack((s_h1, s_h2))
# compute FI for second layer
temp_mask2 = rf_mask2 * prune_mask2
print("Computing FI for weights of layer 2")
var_est2, heu_est2 = FI_weights_var_heur_estimates(samples, nh1, nh2, W2)
if USE_VAR:
fi_weights_after_joint_RBM2 = var_est2.reshape((nh2,nh1)).T * temp_mask2 # VARIANCE ESTIMATE
else:
fi_weights_after_joint_RBM2 = heu_est2.reshape((nh2,nh1)).T * temp_mask2 # HEURISTIC ESTIMATE
np.save(os.path.join(res_path, 'FI_weights_RBM2_after_retrain_sess{}'.format(pruning_session)), fi_weights_after_joint_RBM2)
print("\nEvaluate samples similarity to digits...")
pred_probs_samples = logreg_digits.predict_proba(s_v)
prob_winner_pred_samples = pred_probs_samples.max(axis=1)
mean_qual = np.mean(prob_winner_pred_samples)
print("Mean quality of samples", mean_qual, "Std: ", np.std(prob_winner_pred_samples))
ind_winner_pred_samples = np.argmax(pred_probs_samples, axis=1)
sample_class, sample_counts = np.unique(ind_winner_pred_samples, return_counts=True)
dic = dict(zip(sample_class, sample_counts))
print("sample counts per class",dic)
probs=pred_probs_samples.max(axis=1)
mean_qual_d = np.zeros(len(sample_class))
for i in range(0,len(sample_class)):
ind=np.where(ind_winner_pred_samples==sample_class[i])
mean_qual_d[i] = np.mean(probs[ind])
qual_d = [sample_class, mean_qual_d, sample_counts]
print("Weighted (per class frequency) mean quality of samples", np.mean(mean_qual_d))
np.save(os.path.join(res_path, 'ProbsWinDig_sess{}_checkpoint{}.npy'.format(pruning_session, checkpoint+1)), qual_d)
print("\nEvaluate hidden unit representations...")
final_train = dbm_pruned.transform(bin_X_train)
final_test = dbm_pruned.transform(bin_X_test)
print("\nTrain LogReg classifier on final hidden layer...")
logreg_hid = LogisticRegression(multi_class='multinomial', solver='sag', max_iter=800, n_jobs=2, random_state=4444)
logreg_hid.fit(final_train, y_train)
logreg_acc = logreg_hid.score(final_test, y_test)
print("classification accuracy of LogReg classifier", logreg_acc)
res_acc_logreg[it, checkpoint] = logreg_acc
save_results()
# set these for next loop
fi_weights2 = fi_weights_after_joint_RBM2
fi_weights1 = fi_weights_after_joint_RBM1
if __name__ == '__main__':
def check_positive(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError('Not a positive integer.')
return ivalue
parser = argparse.ArgumentParser(description = 'DBM Pruning')
parser.add_argument('percentile', default=10, nargs='?', help='Percentage of weights removed in each iteration', type=int, choices=range(1, 100))
parser.add_argument('n_pruning_session', default=10, nargs='?', help='Number of pruning sessions', type=check_positive)
args = parser.parse_args()
main(args.percentile, args.n_pruning_session)
|
[] |
[] |
[
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
|
python
| 2 | 0 | |
train.py
|
import os
import json
import argparse
import math
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.multiprocessing as mp
import torch.distributed as dist
from apex.parallel import DistributedDataParallel as DDP
from apex import amp
from data_utils import TextMelLoader, TextMelCollate
import models
import commons
import utils
from text.symbols import symbols
global_step = 0
def main():
"""Assume Single Node Multi GPUs Training Only"""
assert torch.cuda.is_available(), "CPU training is not allowed."
n_gpus = torch.cuda.device_count()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '80000'
hps = utils.get_hparams()
mp.spawn(train_and_eval, nprocs=n_gpus, args=(n_gpus, hps,))
def train_and_eval(rank, n_gpus, hps):
global global_step
if rank == 0:
logger = utils.get_logger(hps.model_dir)
logger.info(hps)
utils.check_git_hash(hps.model_dir)
writer = SummaryWriter(log_dir=hps.model_dir)
writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank)
torch.manual_seed(hps.train.seed)
torch.cuda.set_device(rank)
train_dataset = TextMelLoader(hps.data.training_files, hps.data)
train_sampler = torch.utils.data.distributed.DistributedSampler(
train_dataset,
num_replicas=n_gpus,
rank=rank,
shuffle=True)
collate_fn = TextMelCollate(1)
train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False,
batch_size=hps.train.batch_size, pin_memory=True,
drop_last=True, collate_fn=collate_fn, sampler=train_sampler)
if rank == 0:
val_dataset = TextMelLoader(hps.data.validation_files, hps.data)
# FIXME: hardcoded, forcing validation batch size to be at most the number of validation files
batch_val_size = hps.train.batch_size
if len(val_dataset) < hps.train.batch_size:
batch_val_size = len(val_dataset)
val_loader = DataLoader(val_dataset, num_workers=8, shuffle=False,
batch_size=batch_val_size, pin_memory=True,
drop_last=True, collate_fn=collate_fn)
generator = models.FlowGenerator(
speaker_dim=hps.model.speaker_embedding,
n_vocab=len(symbols),
out_channels=hps.data.n_mel_channels,
**hps.model).cuda(rank)
optimizer_g = commons.Adam(generator.parameters(), scheduler=hps.train.scheduler,
dim_model=hps.model.hidden_channels, warmup_steps=hps.train.warmup_steps,
lr=hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps)
if hps.train.fp16_run:
generator, optimizer_g._optim = amp.initialize(generator, optimizer_g._optim, opt_level="O1")
generator = DDP(generator)
try:
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), generator,
optimizer_g)
epoch_str += 1
optimizer_g.step_num = (epoch_str - 1) * len(train_loader)
optimizer_g._update_learning_rate()
global_step = (epoch_str - 1) * len(train_loader)
except:
if hps.train.ddi and os.path.isfile(os.path.join(hps.model_dir, "ddi_G.pth")):
_ = utils.load_checkpoint(os.path.join(hps.model_dir, "ddi_G.pth"), generator, optimizer_g)
epoch_str = 1
global_step = 0
for epoch in range(epoch_str, hps.train.epochs + 1):
if rank == 0:
train(rank, epoch, hps, generator, optimizer_g, train_loader, logger, writer)
# for single GPU force saving every 100 epochs only
# TODO: add this to hparams?
if epoch % 100 == 0:
evaluate(rank, epoch, hps, generator, optimizer_g, val_loader, logger, writer_eval)
utils.save_checkpoint(generator, optimizer_g, hps.train.learning_rate, epoch,
os.path.join(hps.model_dir, "G_{}.pth".format(epoch)))
else:
train(rank, epoch, hps, generator, optimizer_g, train_loader, None, None)
def train(rank, epoch, hps, generator, optimizer_g, train_loader, logger, writer):
train_loader.sampler.set_epoch(epoch)
global global_step
generator.train()
for batch_idx, (x, x_lengths, y, y_lengths, speaker_embedding) in enumerate(train_loader):
x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
# Multi-tts
speaker_embedding = speaker_embedding.cuda(rank, non_blocking=True)
# Train Generator
optimizer_g.zero_grad()
(z, y_m, y_logs, logdet), attn, logw, logw_, x_m, x_logs = generator(x, x_lengths, speaker_embedding, y,
y_lengths, gen=False)
l_mle = 0.5 * math.log(2 * math.pi) + (
torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m) ** 2) - torch.sum(
logdet)) / (torch.sum(y_lengths // hps.model.n_sqz) * hps.model.n_sqz * hps.data.n_mel_channels)
l_length = torch.sum((logw - logw_) ** 2) / torch.sum(x_lengths)
loss_gs = [l_mle, l_length]
loss_g = sum(loss_gs)
if hps.train.fp16_run:
with amp.scale_loss(loss_g, optimizer_g._optim) as scaled_loss:
scaled_loss.backward()
grad_norm = commons.clip_grad_value_(amp.master_params(optimizer_g._optim), 5)
else:
loss_g.backward()
grad_norm = commons.clip_grad_value_(generator.parameters(), 5)
optimizer_g.step()
if rank == 0:
if batch_idx % hps.train.log_interval == 0:
(y_gen, *_), *_ = generator.module(x[:1], x_lengths[:1], speaker_embedding[:1], gen=True)
logger.info('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(x), len(train_loader.dataset),
100. * batch_idx / len(train_loader),
loss_g.item()))
logger.info([x.item() for x in loss_gs] + [global_step, optimizer_g.get_lr()])
scalar_dict = {"loss/g/total": loss_g, "learning_rate": optimizer_g.get_lr(), "grad_norm": grad_norm}
scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(loss_gs)})
utils.summarize(
writer=writer,
global_step=global_step,
images={"y_org": utils.plot_spectrogram_to_numpy(y[0].data.cpu().numpy()),
"y_gen": utils.plot_spectrogram_to_numpy(y_gen[0].data.cpu().numpy()),
"attn": utils.plot_alignment_to_numpy(attn[0, 0].data.cpu().numpy()),
},
scalars=scalar_dict)
global_step += 1
if rank == 0:
logger.info('====> Epoch: {}'.format(epoch))
def evaluate(rank, epoch, hps, generator, optimizer_g, val_loader, logger, writer_eval):
if rank == 0:
global global_step
generator.eval()
losses_tot = []
with torch.no_grad():
for batch_idx, (x, x_lengths, y, y_lengths, speaker_embedding) in enumerate(val_loader):
x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
# Multi-tts
speaker_embedding = speaker_embedding.cuda(rank, non_blocking=True)
(z, y_m, y_logs, logdet), attn, logw, logw_, x_m, x_logs = generator(x, x_lengths, speaker_embedding, y,
y_lengths,
gen=False)
l_mle = 0.5 * math.log(2 * math.pi) + (
torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m) ** 2) - torch.sum(
logdet)) / (torch.sum(y_lengths // hps.model.n_sqz) * hps.model.n_sqz * hps.data.n_mel_channels)
l_length = torch.sum((logw - logw_) ** 2) / torch.sum(x_lengths)
loss_gs = [l_mle, l_length]
loss_g = sum(loss_gs)
if batch_idx == 0:
losses_tot = loss_gs
else:
losses_tot = [x + y for (x, y) in zip(losses_tot, loss_gs)]
logger.info('Eval Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(x), len(val_loader.dataset),
100. * batch_idx / len(val_loader),
loss_g.item()))
logger.info([x.item() for x in loss_gs])
losses_tot = [x / len(val_loader) for x in losses_tot]
loss_tot = sum(losses_tot)
scalar_dict = {"loss/g/total": loss_tot}
scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_tot)})
utils.summarize(
writer=writer_eval,
global_step=global_step,
scalars=scalar_dict)
logger.info('====> Epoch: {}'.format(epoch))
if __name__ == "__main__":
main()
|
[] |
[] |
[
"MASTER_ADDR",
"MASTER_PORT"
] |
[]
|
["MASTER_ADDR", "MASTER_PORT"]
|
python
| 2 | 0 | |
manage.py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DS3Rings.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 (
"fmt"
"net/http"
"os"
"strings"
"github.com/chyeh/pubip"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
)
func HelloServer(w http.ResponseWriter, r *http.Request) {
hlog.FromRequest(r).Info().
Str("method", r.Method).
Stringer("url", r.URL).
Msg("")
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
if r.URL.RawQuery == "debug" {
fmt.Fprintf(w, "\n\n\n-- env:\n\n")
for _, e := range os.Environ() {
fmt.Fprintf(w, "%s\n", e)
}
fmt.Fprintf(w, "\n\n-- headers:\n\n")
for k, v := range r.Header {
fmt.Fprintf(w, "%s: %s\n", k, strings.Join(v, ","))
}
}
if r.URL.RawQuery == "ip" {
fmt.Fprintf(w, "\n\n\n-- my public ip: ")
ip, err := pubip.Get()
if err != nil {
fmt.Fprintf(w, "%s\n", err)
} else {
fmt.Fprintf(w, "%s\n", ip)
}
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Warn().Msg("PORT is undefined, assuming 80")
port = "80"
}
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/*", HelloServer)
r.Get("/db/{dbPrefix}", TestDB)
fmt.Println("Listening to port", port)
if err := http.ListenAndServe(":"+port, r); err != nil {
log.Fatal().Err(err).Msg("ListenAndServe")
}
}
|
[
"\"PORT\""
] |
[] |
[
"PORT"
] |
[]
|
["PORT"]
|
go
| 1 | 0 | |
py/py/wsgi.py
|
"""
WSGI config for py 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "py.settings")
application = get_wsgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
code/han_bias.py
|
import os
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import keras
from keras.preprocessing import text
from keras.engine.topology import Layer
import keras.layers as L
from keras.models import Model
from keras import initializers as initializers
from keras import backend as K
import pandas as pd
import numpy as np
from nltk.tokenize import sent_tokenize
from glovevectorizer import load_glove_weights, generate_weights
# BASE_DIR = '/home/kwu14/data/cs584_course_project'
BASE_DIR = '../data/'
VOCAB_SIZE = 10000
MAX_SENTS = 43
MAX_SENT_LEN = 300
AUX_COLUMNS = ['severe_toxicity', 'obscene',
'identity_attack', 'insult', 'threat']
IDENTITY_COLUMNS = [
'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',
'muslim', 'black', 'white', 'psychiatric_or_mental_illness'
]
class AttentionLayer(Layer):
"""
Hierarchial Attention Layer as described by Hierarchical
Attention Networks for Document Classification(2016)
- Yang et. al.
Source:
https://www.cs.cmu.edu/~hovy/papers/16HLT-hierarchical-attention-networks.pdf
Theano backend
"""
def __init__(self, attention_dim=100, return_coefficients=False, **kwargs):
# Initializer
self.supports_masking = True
self.return_coefficients = return_coefficients
self.init = initializers.get('glorot_uniform') # initializes values with uniform distribution
self.attention_dim = attention_dim
super(AttentionLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Builds all weights
# W = Weight matrix, b = bias vector, u = context vector
assert len(input_shape) == 3
self.W = K.variable(self.init((input_shape[-1], self.attention_dim)), name='W')
self.b = K.variable(self.init((self.attention_dim, )), name='b')
self.u = K.variable(self.init((self.attention_dim, 1)), name='u')
self.trainable_weights = [self.W, self.b, self.u]
super(AttentionLayer, self).build(input_shape)
def compute_mask(self, input, input_mask=None):
return None
def call(self, hit, mask=None):
# Here, the actual calculation is done
uit = K.bias_add(K.dot(hit, self.W),self.b)
uit = K.tanh(uit)
ait = K.dot(uit, self.u)
ait = K.squeeze(ait, -1)
ait = K.exp(ait)
if mask is not None:
ait *= K.cast(mask, K.floatx())
ait /= K.cast(K.sum(ait, axis=1, keepdims=True) + K.epsilon(), K.floatx())
ait = K.expand_dims(ait)
weighted_input = hit * ait
if self.return_coefficients:
return [K.sum(weighted_input, axis=1), ait]
else:
return K.sum(weighted_input, axis=1)
def compute_output_shape(self, input_shape):
if self.return_coefficients:
return [(input_shape[0], input_shape[-1]), (input_shape[0], input_shape[-1], 1)]
else:
return input_shape[0], input_shape[-1]
def load_data():
train_df = pd.read_csv(os.path.join(BASE_DIR, 'preprocessed_train.csv'))
# Preprocess data
for column in IDENTITY_COLUMNS + ['target']:
train_df[column] = train_df[column].apply(
lambda x: 1 if x >= 0.5 else 0)
sample_weights = np.ones(train_df.shape[0], dtype=np.float32)
sample_weights += train_df[IDENTITY_COLUMNS].sum(axis=1)
sample_weights += train_df['target'] * \
(~train_df[IDENTITY_COLUMNS]).sum(axis=1)
sample_weights += (~train_df['target']) * \
train_df[IDENTITY_COLUMNS].sum(axis=1) * 5
sample_weights /= sample_weights.mean()
text_train = train_df['comment_text'].astype(str).values
y_train = train_df['target'].values
y_aux_train = train_df[AUX_COLUMNS].values
tk = text.Tokenizer(num_words=VOCAB_SIZE)
tk.fit_on_texts(text_train)
comments = []
for t in text_train:
comments.append(sent_tokenize(t))
x_train = np.zeros((len(comments), MAX_SENTS, MAX_SENT_LEN),
dtype='int32')
for i, sents in enumerate(comments):
for j, sent in enumerate(sents):
if j >= MAX_SENTS:
continue
tokens = tk.texts_to_sequences(sent)
k = 0
for idx in tokens:
if len(idx) == 0:
continue
if k < MAX_SENT_LEN and idx[0] < VOCAB_SIZE:
x_train[i, j, k] = idx[0]
k += 1
embedding_matrix = generate_weights(
load_glove_weights(os.path.join(BASE_DIR, 'glove.6B.300d.txt')),
tk.word_index,
VOCAB_SIZE - 1,
)
# load test data
test_df = pd.read_csv(os.path.join(BASE_DIR, 'preprocessed_test.csv'))
text_test = test_df['comment_text'].astype(str).values
test_comments = []
for t in text_test:
test_comments.append(sent_tokenize(t))
x_test = np.zeros((len(test_comments), MAX_SENTS, MAX_SENT_LEN),
dtype='int32')
for i, sents in enumerate(test_comments):
for j, sent in enumerate(sents):
if j >= MAX_SENTS:
continue
tokens = tk.texts_to_sequences(sent)
k = 0
for idx in tokens:
if len(idx) == 0:
continue
if k < MAX_SENT_LEN and idx[0] < VOCAB_SIZE:
x_test[i, j, k] = idx[0]
k += 1
return x_train, y_train, y_aux_train, test_df.id, x_test, \
embedding_matrix, sample_weights
def load_model(weights, hidden_size=100):
# Words level attention model
word_input = L.Input(shape=(MAX_SENT_LEN,), dtype='int32')
word_sequences = L.Embedding(weights.shape[0], weights.shape[1], weights=[weights], input_length=MAX_SENT_LEN, trainable=False, name='word_embedding')(word_input)
word_gru = L.Bidirectional(L.GRU(hidden_size, return_sequences=True))(word_sequences)
word_dense = L.Dense(100, activation='relu', name='word_dense')(word_gru)
word_att, word_coeffs = AttentionLayer(100, True, name='word_attention')(word_dense)
wordEncoder = Model(inputs=word_input, outputs=word_att)
# Sentence level attention model
sent_input = L.Input(shape=(MAX_SENTS, MAX_SENT_LEN), dtype='int32', name='sent_input')
sent_encoder = L.TimeDistributed(wordEncoder, name='sent_linking')(sent_input)
sent_gru = L.Bidirectional(L.GRU(50, return_sequences=True))(sent_encoder)
sent_dense = L.Dense(100, activation='relu', name='sent_dense')(sent_gru)
sent_att, sent_coeffs = AttentionLayer(100, return_coefficients=True, name='sent_attention')(sent_dense)
sent_drop = L.Dropout(0.5, name='sent_dropout')(sent_att)
preds = L.Dense(1, activation='sigmoid', name='output')(sent_drop)
# Model compile
model = Model(sent_input, preds)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])
print(wordEncoder.summary())
print(model.summary())
return model
if __name__ == "__main__":
# hyper-paramters
batch_size = 1024
epochs = 50
hidden_size = 128
# load data
x_train, y_train, y_aux_train, test_id,\
x_test, weights, sample_weights = load_data()
checkpoint = keras.callbacks.ModelCheckpoint(
'han_bias_model.h5', save_best_only=True, verbose=1)
es = keras.callbacks.EarlyStopping(patience=3, verbose=1)
model = load_model(weights, hidden_size)
history = model.fit(
x_train, y_train,
batch_size=batch_size,
validation_split=0.2,
epochs=epochs,
callbacks=[es, checkpoint],
verbose=2
# sample_weight=[sample_weights.values, np.ones_like(sample_weights)]
)
# evaluation
model.load_weights('han_bias_model.h5')
test_preds = model.predict(x_test)
submission = pd.DataFrame.from_dict({
'id': test_id,
'prediction': test_preds
})
submission.to_csv('han_bias_submission.csv', index=False)
|
[] |
[] |
[
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
|
python
| 2 | 0 | |
samples/java/src/main/java/utils/EnvironmentUtils.java
|
package utils;
import org.apache.commons.io.FileUtils;
class EnvironmentUtils {
static String getTestPoolIP() {
String testPoolIp = System.getenv("TEST_POOL_IP");
return testPoolIp != null ? testPoolIp : "127.0.0.1";
}
static String getTmpPath() {
return FileUtils.getTempDirectoryPath() + "/indy/";
}
static String getTmpPath(String filename) {
return getTmpPath() + filename;
}
}
|
[
"\"TEST_POOL_IP\""
] |
[] |
[
"TEST_POOL_IP"
] |
[]
|
["TEST_POOL_IP"]
|
java
| 1 | 0 | |
platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/CaseSensitivityDetectionTest.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.openapi.vfs.local;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.io.FileSystemUtil;
import com.intellij.testFramework.rules.TempDirectory;
import com.intellij.util.io.SuperUserStatus;
import org.jetbrains.annotations.NotNull;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.intellij.openapi.util.io.IoTestUtil.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
/** Tests low-level functions for reading file case-sensitivity attributes in {@link FileSystemUtil} */
public class CaseSensitivityDetectionTest {
@Rule public TempDirectory myTempDir = new TempDirectory();
@Test
public void windowsFSRootsMustHaveDefaultSensitivity() {
assumeWindows();
String systemDrive = System.getenv("SystemDrive"); // typically "C:"
assertNotNull(systemDrive);
File root = new File(systemDrive + '\\');
FileAttributes.CaseSensitivity rootCs = FileSystemUtil.readParentCaseSensitivity(root);
assertEquals(systemDrive, FileAttributes.CaseSensitivity.INSENSITIVE, rootCs);
String systemRoot = System.getenv("SystemRoot"); // typically "C:\Windows"
assertNotNull(systemRoot);
File child = new File(systemRoot);
assertEquals(root, child.getParentFile());
assertEquals(systemRoot, rootCs, FileSystemUtil.readParentCaseSensitivity(child));
}
@Test
public void wslRootsMustBeCaseSensitive() {
assumeWindows();
List<@NotNull String> distributions = enumerateWslDistributions();
assumeTrue("No WSL distributions found", !distributions.isEmpty());
for (String name : distributions) {
String root = "\\\\wsl$\\" + name;
assertEquals(root, FileAttributes.CaseSensitivity.SENSITIVE, FileSystemUtil.readParentCaseSensitivity(new File(root)));
}
}
@Test
public void caseSensitivityChangesUnderWindowsMustBeReReadCorrectly() throws IOException {
assumeWindows();
assumeWslPresence();
assumeTrue("'fsutil.exe' needs elevated privileges to work", SuperUserStatus.isSuperUser());
File file = myTempDir.newFile("dir/child.txt"), dir = file.getParentFile();
assertEquals(FileAttributes.CaseSensitivity.INSENSITIVE, FileSystemUtil.readParentCaseSensitivity(file));
setCaseSensitivity(dir, true);
assertEquals(FileAttributes.CaseSensitivity.SENSITIVE, FileSystemUtil.readParentCaseSensitivity(file));
setCaseSensitivity(dir, false);
assertEquals(FileAttributes.CaseSensitivity.INSENSITIVE, FileSystemUtil.readParentCaseSensitivity(file));
}
@Test
public void macOsBasics() {
assumeMacOS();
File root = new File("/");
FileAttributes.CaseSensitivity rootCs = FileSystemUtil.readParentCaseSensitivity(root);
assertNotEquals(FileAttributes.CaseSensitivity.UNKNOWN, rootCs);
File child = new File("/Users");
assertEquals(root, child.getParentFile());
assertEquals(rootCs, FileSystemUtil.readParentCaseSensitivity(child));
}
@Test
public void linuxBasics() {
assumeTrue("Need Linux, can't run on " + SystemInfo.OS_NAME, SystemInfo.isLinux);
File root = new File("/");
FileAttributes.CaseSensitivity rootCs = FileSystemUtil.readParentCaseSensitivity(root);
assertEquals(FileAttributes.CaseSensitivity.SENSITIVE, rootCs);
File child = new File("/home");
assertEquals(rootCs, FileSystemUtil.readParentCaseSensitivity(child));
}
@Test
public void caseSensitivityIsReadSanely() throws IOException {
File file = myTempDir.newFile("dir/child.txt");
File dir = file.getParentFile();
FileAttributes.CaseSensitivity sensitivity = FileSystemUtil.readParentCaseSensitivity(file);
assertTrue(new File(dir, "x.txt").createNewFile());
switch (sensitivity) {
case SENSITIVE:
assertTrue(new File(dir, "X.txt").createNewFile());
break;
case INSENSITIVE:
assertFalse(new File(dir, "X.txt").createNewFile());
break;
default:
fail("invalid sensitivity: " + sensitivity);
break;
}
}
@Test
public void caseSensitivityOfNonExistingDirMustBeUnknown() {
File file = new File(myTempDir.getRoot(), "dir/child.txt");
assertFalse(file.exists());
FileAttributes.CaseSensitivity sensitivity = FileSystemUtil.readParentCaseSensitivity(file);
assertEquals(FileAttributes.CaseSensitivity.UNKNOWN, sensitivity);
}
}
|
[
"\"SystemDrive\"",
"\"SystemRoot\""
] |
[] |
[
"SystemRoot",
"SystemDrive"
] |
[]
|
["SystemRoot", "SystemDrive"]
|
java
| 2 | 0 | |
test/functional/test_framework/test_framework.py
|
#!/usr/bin/env python3
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
import configparser
from enum import Enum
import argparse
import logging
import os
import pdb
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
from typing import List
from .address import ADDRESS_BCRT1_P2WSH_OP_TRUE
from .authproxy import JSONRPCException
from . import coverage
from .p2p import NetworkThread
from .test_node import TestNode
from .util import (
MAX_NODES,
PortSeed,
assert_equal,
check_json_precision,
get_datadir_path,
initialize_datadir,
p2p_port,
wait_until_helper,
)
class TestStatus(Enum):
PASSED = 1
FAILED = 2
SKIPPED = 3
TEST_EXIT_PASSED = 0
TEST_EXIT_FAILED = 1
TEST_EXIT_SKIPPED = 77
TMPDIR_PREFIX = "umkoin_func_test_"
class SkipTest(Exception):
"""This exception is raised to skip a test"""
def __init__(self, message):
self.message = message
class UmkoinTestMetaClass(type):
"""Metaclass for UmkoinTestFramework.
Ensures that any attempt to register a subclass of `UmkoinTestFramework`
adheres to a standard whereby the subclass overrides `set_test_params` and
`run_test` but DOES NOT override either `__init__` or `main`. If any of
those standards are violated, a ``TypeError`` is raised."""
def __new__(cls, clsname, bases, dct):
if not clsname == 'UmkoinTestFramework':
if not ('run_test' in dct and 'set_test_params' in dct):
raise TypeError("UmkoinTestFramework subclasses must override "
"'run_test' and 'set_test_params'")
if '__init__' in dct or 'main' in dct:
raise TypeError("UmkoinTestFramework subclasses may not override "
"'__init__' or 'main'")
return super().__new__(cls, clsname, bases, dct)
class UmkoinTestFramework(metaclass=UmkoinTestMetaClass):
"""Base class for a umkoin test script.
Individual umkoin test scripts should subclass this class and override the set_test_params() and run_test() methods.
Individual tests can also override the following methods to customize the test setup:
- add_options()
- setup_chain()
- setup_network()
- setup_nodes()
The __init__() and main() methods should not be overridden.
This class also contains various public and private helper methods."""
def __init__(self):
"""Sets test framework defaults. Do not override this method. Instead, override the set_test_params() method"""
self.chain: str = 'regtest'
self.setup_clean_chain: bool = False
self.nodes: List[TestNode] = []
self.network_thread = None
self.rpc_timeout = 60 # Wait for up to 60 seconds for the RPC server to respond
self.supports_cli = True
self.bind_to_localhost_only = True
self.parse_args()
self.disable_syscall_sandbox = self.options.nosandbox
self.default_wallet_name = "default_wallet" if self.options.descriptors else ""
self.wallet_data_filename = "wallet.dat"
# Optional list of wallet names that can be set in set_test_params to
# create and import keys to. If unset, default is len(nodes) *
# [default_wallet_name]. If wallet names are None, wallet creation is
# skipped. If list is truncated, wallet creation is skipped and keys
# are not imported.
self.wallet_names = None
# By default the wallet is not required. Set to true by skip_if_no_wallet().
# When False, we ignore wallet_names regardless of what it is.
self.requires_wallet = False
# Disable ThreadOpenConnections by default, so that adding entries to
# addrman will not result in automatic connections to them.
self.disable_autoconnect = True
self.set_test_params()
assert self.wallet_names is None or len(self.wallet_names) <= self.num_nodes
if self.options.timeout_factor == 0 :
self.options.timeout_factor = 99999
self.rpc_timeout = int(self.rpc_timeout * self.options.timeout_factor) # optionally, increase timeout by a factor
def main(self):
"""Main function. This should not be overridden by the subclass test scripts."""
assert hasattr(self, "num_nodes"), "Test must set self.num_nodes in set_test_params()"
try:
self.setup()
self.run_test()
except JSONRPCException:
self.log.exception("JSONRPC error")
self.success = TestStatus.FAILED
except SkipTest as e:
self.log.warning("Test Skipped: %s" % e.message)
self.success = TestStatus.SKIPPED
except AssertionError:
self.log.exception("Assertion failed")
self.success = TestStatus.FAILED
except KeyError:
self.log.exception("Key error")
self.success = TestStatus.FAILED
except subprocess.CalledProcessError as e:
self.log.exception("Called Process failed with '{}'".format(e.output))
self.success = TestStatus.FAILED
except Exception:
self.log.exception("Unexpected exception caught during testing")
self.success = TestStatus.FAILED
except KeyboardInterrupt:
self.log.warning("Exiting after keyboard interrupt")
self.success = TestStatus.FAILED
finally:
exit_code = self.shutdown()
sys.exit(exit_code)
def parse_args(self):
previous_releases_path = os.getenv("PREVIOUS_RELEASES_DIR") or os.getcwd() + "/releases"
parser = argparse.ArgumentParser(usage="%(prog)s [options]")
parser.add_argument("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave umkoinds and test.* datadir on exit or error")
parser.add_argument("--nosandbox", dest="nosandbox", default=False, action="store_true",
help="Don't use the syscall sandbox")
parser.add_argument("--noshutdown", dest="noshutdown", default=False, action="store_true",
help="Don't stop umkoinds after the test execution")
parser.add_argument("--cachedir", dest="cachedir", default=os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/../../cache"),
help="Directory for caching pregenerated datadirs (default: %(default)s)")
parser.add_argument("--tmpdir", dest="tmpdir", help="Root directory for datadirs")
parser.add_argument("-l", "--loglevel", dest="loglevel", default="INFO",
help="log events at this level and higher to the console. Can be set to DEBUG, INFO, WARNING, ERROR or CRITICAL. Passing --loglevel DEBUG will output all logs to console. Note that logs at all levels are always written to the test_framework.log file in the temporary test directory.")
parser.add_argument("--tracerpc", dest="trace_rpc", default=False, action="store_true",
help="Print out all RPC calls as they are made")
parser.add_argument("--portseed", dest="port_seed", default=os.getpid(), type=int,
help="The seed to use for assigning port numbers (default: current process id)")
parser.add_argument("--previous-releases", dest="prev_releases", action="store_true",
default=os.path.isdir(previous_releases_path) and bool(os.listdir(previous_releases_path)),
help="Force test of previous releases (default: %(default)s)")
parser.add_argument("--coveragedir", dest="coveragedir",
help="Write tested RPC commands into this directory")
parser.add_argument("--configfile", dest="configfile",
default=os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/../../config.ini"),
help="Location of the test framework config file (default: %(default)s)")
parser.add_argument("--pdbonfailure", dest="pdbonfailure", default=False, action="store_true",
help="Attach a python debugger if test fails")
parser.add_argument("--usecli", dest="usecli", default=False, action="store_true",
help="use umkoin-cli instead of RPC for all commands")
parser.add_argument("--perf", dest="perf", default=False, action="store_true",
help="profile running nodes with perf for the duration of the test")
parser.add_argument("--valgrind", dest="valgrind", default=False, action="store_true",
help="run nodes under the valgrind memory error detector: expect at least a ~10x slowdown, valgrind 3.14 or later required")
parser.add_argument("--randomseed", type=int,
help="set a random seed for deterministically reproducing a previous test run")
parser.add_argument('--timeout-factor', dest="timeout_factor", type=float, default=1.0, help='adjust test timeouts by a factor. Setting it to 0 disables all timeouts')
group = parser.add_mutually_exclusive_group()
group.add_argument("--descriptors", action='store_const', const=True,
help="Run test using a descriptor wallet", dest='descriptors')
group.add_argument("--legacy-wallet", action='store_const', const=False,
help="Run test using legacy wallets", dest='descriptors')
self.add_options(parser)
# Running TestShell in a Jupyter notebook causes an additional -f argument
# To keep TestShell from failing with an "unrecognized argument" error, we add a dummy "-f" argument
# source: https://stackoverflow.com/questions/48796169/how-to-fix-ipykernel-launcher-py-error-unrecognized-arguments-in-jupyter/56349168#56349168
parser.add_argument("-f", "--fff", help="a dummy argument to fool ipython", default="1")
self.options = parser.parse_args()
self.options.previous_releases_path = previous_releases_path
config = configparser.ConfigParser()
config.read_file(open(self.options.configfile))
self.config = config
if self.options.descriptors is None:
# Prefer BDB unless it isn't available
if self.is_bdb_compiled():
self.options.descriptors = False
elif self.is_sqlite_compiled():
self.options.descriptors = True
else:
# If neither are compiled, tests requiring a wallet will be skipped and the value of self.options.descriptors won't matter
# It still needs to exist and be None in order for tests to work however.
self.options.descriptors = None
def setup(self):
"""Call this method to start up the test framework object with options set."""
PortSeed.n = self.options.port_seed
check_json_precision()
self.options.cachedir = os.path.abspath(self.options.cachedir)
config = self.config
fname_umkoind = os.path.join(
config["environment"]["BUILDDIR"],
"src",
"umkoind" + config["environment"]["EXEEXT"],
)
fname_umkoincli = os.path.join(
config["environment"]["BUILDDIR"],
"src",
"umkoin-cli" + config["environment"]["EXEEXT"],
)
self.options.umkoind = os.getenv("UMKOIND", default=fname_umkoind)
self.options.umkoincli = os.getenv("UMKOINCLI", default=fname_umkoincli)
os.environ['PATH'] = os.pathsep.join([
os.path.join(config['environment']['BUILDDIR'], 'src'),
os.path.join(config['environment']['BUILDDIR'], 'src', 'qt'), os.environ['PATH']
])
# Set up temp directory and start logging
if self.options.tmpdir:
self.options.tmpdir = os.path.abspath(self.options.tmpdir)
os.makedirs(self.options.tmpdir, exist_ok=False)
else:
self.options.tmpdir = tempfile.mkdtemp(prefix=TMPDIR_PREFIX)
self._start_logging()
# Seed the PRNG. Note that test runs are reproducible if and only if
# a single thread accesses the PRNG. For more information, see
# https://docs.python.org/3/library/random.html#notes-on-reproducibility.
# The network thread shouldn't access random. If we need to change the
# network thread to access randomness, it should instantiate its own
# random.Random object.
seed = self.options.randomseed
if seed is None:
seed = random.randrange(sys.maxsize)
else:
self.log.debug("User supplied random seed {}".format(seed))
random.seed(seed)
self.log.debug("PRNG seed is: {}".format(seed))
self.log.debug('Setting up network thread')
self.network_thread = NetworkThread()
self.network_thread.start()
if self.options.usecli:
if not self.supports_cli:
raise SkipTest("--usecli specified but test does not support using CLI")
self.skip_if_no_cli()
self.skip_test_if_missing_module()
self.setup_chain()
self.setup_network()
self.success = TestStatus.PASSED
def shutdown(self):
"""Call this method to shut down the test framework object."""
if self.success == TestStatus.FAILED and self.options.pdbonfailure:
print("Testcase failed. Attaching python debugger. Enter ? for help")
pdb.set_trace()
self.log.debug('Closing down network thread')
self.network_thread.close()
if not self.options.noshutdown:
self.log.info("Stopping nodes")
if self.nodes:
self.stop_nodes()
else:
for node in self.nodes:
node.cleanup_on_exit = False
self.log.info("Note: umkoinds were not stopped and may still be running")
should_clean_up = (
not self.options.nocleanup and
not self.options.noshutdown and
self.success != TestStatus.FAILED and
not self.options.perf
)
if should_clean_up:
self.log.info("Cleaning up {} on exit".format(self.options.tmpdir))
cleanup_tree_on_exit = True
elif self.options.perf:
self.log.warning("Not cleaning up dir {} due to perf data".format(self.options.tmpdir))
cleanup_tree_on_exit = False
else:
self.log.warning("Not cleaning up dir {}".format(self.options.tmpdir))
cleanup_tree_on_exit = False
if self.success == TestStatus.PASSED:
self.log.info("Tests successful")
exit_code = TEST_EXIT_PASSED
elif self.success == TestStatus.SKIPPED:
self.log.info("Test skipped")
exit_code = TEST_EXIT_SKIPPED
else:
self.log.error("Test failed. Test logging available at %s/test_framework.log", self.options.tmpdir)
self.log.error("")
self.log.error("Hint: Call {} '{}' to consolidate all logs".format(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../combine_logs.py"), self.options.tmpdir))
self.log.error("")
self.log.error("If this failure happened unexpectedly or intermittently, please file a bug and provide a link or upload of the combined log.")
self.log.error(self.config['environment']['PACKAGE_BUGREPORT'])
self.log.error("")
exit_code = TEST_EXIT_FAILED
# Logging.shutdown will not remove stream- and filehandlers, so we must
# do it explicitly. Handlers are removed so the next test run can apply
# different log handler settings.
# See: https://docs.python.org/3/library/logging.html#logging.shutdown
for h in list(self.log.handlers):
h.flush()
h.close()
self.log.removeHandler(h)
rpc_logger = logging.getLogger("UmkoinRPC")
for h in list(rpc_logger.handlers):
h.flush()
rpc_logger.removeHandler(h)
if cleanup_tree_on_exit:
shutil.rmtree(self.options.tmpdir)
self.nodes.clear()
return exit_code
# Methods to override in subclass test scripts.
def set_test_params(self):
"""Tests must override this method to change default values for number of nodes, topology, etc"""
raise NotImplementedError
def add_options(self, parser):
"""Override this method to add command-line options to the test"""
pass
def skip_test_if_missing_module(self):
"""Override this method to skip a test if a module is not compiled"""
pass
def setup_chain(self):
"""Override this method to customize blockchain setup"""
self.log.info("Initializing test directory " + self.options.tmpdir)
if self.setup_clean_chain:
self._initialize_chain_clean()
else:
self._initialize_chain()
def setup_network(self):
"""Override this method to customize test network topology"""
self.setup_nodes()
# Connect the nodes as a "chain". This allows us
# to split the network between nodes 1 and 2 to get
# two halves that can work on competing chains.
#
# Topology looks like this:
# node0 <-- node1 <-- node2 <-- node3
#
# If all nodes are in IBD (clean chain from genesis), node0 is assumed to be the source of blocks (miner). To
# ensure block propagation, all nodes will establish outgoing connections toward node0.
# See fPreferredDownload in net_processing.
#
# If further outbound connections are needed, they can be added at the beginning of the test with e.g.
# self.connect_nodes(1, 2)
for i in range(self.num_nodes - 1):
self.connect_nodes(i + 1, i)
self.sync_all()
def setup_nodes(self):
"""Override this method to customize test node setup"""
extra_args = [[]] * self.num_nodes
if hasattr(self, "extra_args"):
extra_args = self.extra_args
self.add_nodes(self.num_nodes, extra_args)
self.start_nodes()
if self.requires_wallet:
self.import_deterministic_coinbase_privkeys()
if not self.setup_clean_chain:
for n in self.nodes:
assert_equal(n.getblockchaininfo()["blocks"], 199)
# To ensure that all nodes are out of IBD, the most recent block
# must have a timestamp not too old (see IsInitialBlockDownload()).
self.log.debug('Generate a block with current time')
block_hash = self.generate(self.nodes[0], 1)[0]
block = self.nodes[0].getblock(blockhash=block_hash, verbosity=0)
for n in self.nodes:
n.submitblock(block)
chain_info = n.getblockchaininfo()
assert_equal(chain_info["blocks"], 200)
assert_equal(chain_info["initialblockdownload"], False)
def import_deterministic_coinbase_privkeys(self):
for i in range(self.num_nodes):
self.init_wallet(node=i)
def init_wallet(self, *, node):
wallet_name = self.default_wallet_name if self.wallet_names is None else self.wallet_names[node] if node < len(self.wallet_names) else False
if wallet_name is not False:
n = self.nodes[node]
if wallet_name is not None:
n.createwallet(wallet_name=wallet_name, descriptors=self.options.descriptors, load_on_startup=True)
n.importprivkey(privkey=n.get_deterministic_priv_key().key, label='coinbase')
def run_test(self):
"""Tests must override this method to define test logic"""
raise NotImplementedError
# Public helper methods. These can be accessed by the subclass test scripts.
def add_nodes(self, num_nodes: int, extra_args=None, *, rpchost=None, binary=None, binary_cli=None, versions=None):
"""Instantiate TestNode objects.
Should only be called once after the nodes have been specified in
set_test_params()."""
def get_bin_from_version(version, bin_name, bin_default):
if not version:
return bin_default
return os.path.join(
self.options.previous_releases_path,
re.sub(
r'\.0$',
'', # remove trailing .0 for point releases
'v{}.{}.{}.{}'.format(
(version % 100000000) // 1000000,
(version % 1000000) // 10000,
(version % 10000) // 100,
(version % 100) // 1,
),
),
'bin',
bin_name,
)
if self.bind_to_localhost_only:
extra_confs = [["bind=127.0.0.1"]] * num_nodes
else:
extra_confs = [[]] * num_nodes
if extra_args is None:
extra_args = [[]] * num_nodes
if versions is None:
versions = [None] * num_nodes
if self.is_syscall_sandbox_compiled() and not self.disable_syscall_sandbox:
for i in range(len(extra_args)):
if versions[i] is None or versions[i] >= 219900:
extra_args[i] = extra_args[i] + ["-sandbox=log-and-abort"]
if binary is None:
binary = [get_bin_from_version(v, 'umkoind', self.options.umkoind) for v in versions]
if binary_cli is None:
binary_cli = [get_bin_from_version(v, 'umkoin-cli', self.options.umkoincli) for v in versions]
assert_equal(len(extra_confs), num_nodes)
assert_equal(len(extra_args), num_nodes)
assert_equal(len(versions), num_nodes)
assert_equal(len(binary), num_nodes)
assert_equal(len(binary_cli), num_nodes)
for i in range(num_nodes):
test_node_i = TestNode(
i,
get_datadir_path(self.options.tmpdir, i),
chain=self.chain,
rpchost=rpchost,
timewait=self.rpc_timeout,
timeout_factor=self.options.timeout_factor,
umkoind=binary[i],
umkoin_cli=binary_cli[i],
version=versions[i],
coverage_dir=self.options.coveragedir,
cwd=self.options.tmpdir,
extra_conf=extra_confs[i],
extra_args=extra_args[i],
use_cli=self.options.usecli,
start_perf=self.options.perf,
use_valgrind=self.options.valgrind,
descriptors=self.options.descriptors,
)
self.nodes.append(test_node_i)
if not test_node_i.version_is_at_least(170000):
# adjust conf for pre 17
conf_file = test_node_i.umkoinconf
with open(conf_file, 'r', encoding='utf8') as conf:
conf_data = conf.read()
with open(conf_file, 'w', encoding='utf8') as conf:
conf.write(conf_data.replace('[regtest]', ''))
def start_node(self, i, *args, **kwargs):
"""Start a umkoind"""
node = self.nodes[i]
node.start(*args, **kwargs)
node.wait_for_rpc_connection()
if self.options.coveragedir is not None:
coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
def start_nodes(self, extra_args=None, *args, **kwargs):
"""Start multiple umkoinds"""
if extra_args is None:
extra_args = [None] * self.num_nodes
assert_equal(len(extra_args), self.num_nodes)
try:
for i, node in enumerate(self.nodes):
node.start(extra_args[i], *args, **kwargs)
for node in self.nodes:
node.wait_for_rpc_connection()
except:
# If one node failed to start, stop the others
self.stop_nodes()
raise
if self.options.coveragedir is not None:
for node in self.nodes:
coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
def stop_node(self, i, expected_stderr='', wait=0):
"""Stop a umkoind test node"""
self.nodes[i].stop_node(expected_stderr, wait=wait)
def stop_nodes(self, wait=0):
"""Stop multiple umkoind test nodes"""
for node in self.nodes:
# Issue RPC to stop nodes
node.stop_node(wait=wait, wait_until_stopped=False)
for node in self.nodes:
# Wait for nodes to stop
node.wait_until_stopped()
def restart_node(self, i, extra_args=None):
"""Stop and start a test node"""
self.stop_node(i)
self.start_node(i, extra_args)
def wait_for_node_exit(self, i, timeout):
self.nodes[i].process.wait(timeout)
def connect_nodes(self, a, b):
from_connection = self.nodes[a]
to_connection = self.nodes[b]
ip_port = "127.0.0.1:" + str(p2p_port(b))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
# See comments in net_processing:
# * Must have a version message before anything else
# * Must have a verack message before anything else
wait_until_helper(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
wait_until_helper(lambda: all(peer['version'] != 0 for peer in to_connection.getpeerinfo()))
wait_until_helper(lambda: all(peer['bytesrecv_per_msg'].pop('verack', 0) == 24 for peer in from_connection.getpeerinfo()))
wait_until_helper(lambda: all(peer['bytesrecv_per_msg'].pop('verack', 0) == 24 for peer in to_connection.getpeerinfo()))
def disconnect_nodes(self, a, b):
def disconnect_nodes_helper(from_connection, node_num):
def get_peer_ids():
result = []
for peer in from_connection.getpeerinfo():
if "testnode{}".format(node_num) in peer['subver']:
result.append(peer['id'])
return result
peer_ids = get_peer_ids()
if not peer_ids:
self.log.warning("disconnect_nodes: {} and {} were not connected".format(
from_connection.index,
node_num,
))
return
for peer_id in peer_ids:
try:
from_connection.disconnectnode(nodeid=peer_id)
except JSONRPCException as e:
# If this node is disconnected between calculating the peer id
# and issuing the disconnect, don't worry about it.
# This avoids a race condition if we're mass-disconnecting peers.
if e.error['code'] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
raise
# wait to disconnect
wait_until_helper(lambda: not get_peer_ids(), timeout=5)
disconnect_nodes_helper(self.nodes[a], b)
def split_network(self):
"""
Split the network of four nodes into nodes 0/1 and 2/3.
"""
self.disconnect_nodes(1, 2)
self.sync_all(self.nodes[:2])
self.sync_all(self.nodes[2:])
def join_network(self):
"""
Join the (previously split) network halves together.
"""
self.connect_nodes(1, 2)
self.sync_all()
def generate(self, generator, *args, **kwargs):
blocks = generator.generate(*args, invalid_call=False, **kwargs)
return blocks
def generateblock(self, generator, *args, **kwargs):
blocks = generator.generateblock(*args, invalid_call=False, **kwargs)
return blocks
def generatetoaddress(self, generator, *args, **kwargs):
blocks = generator.generatetoaddress(*args, invalid_call=False, **kwargs)
return blocks
def generatetodescriptor(self, generator, *args, **kwargs):
blocks = generator.generatetodescriptor(*args, invalid_call=False, **kwargs)
return blocks
def sync_blocks(self, nodes=None, wait=1, timeout=60):
"""
Wait until everybody has the same tip.
sync_blocks needs to be called with an rpc_connections set that has least
one node already synced to the latest, stable tip, otherwise there's a
chance it might return before all nodes are stably synced.
"""
rpc_connections = nodes or self.nodes
timeout = int(timeout * self.options.timeout_factor)
stop_time = time.time() + timeout
while time.time() <= stop_time:
best_hash = [x.getbestblockhash() for x in rpc_connections]
if best_hash.count(best_hash[0]) == len(rpc_connections):
return
# Check that each peer has at least one connection
assert (all([len(x.getpeerinfo()) for x in rpc_connections]))
time.sleep(wait)
raise AssertionError("Block sync timed out after {}s:{}".format(
timeout,
"".join("\n {!r}".format(b) for b in best_hash),
))
def sync_mempools(self, nodes=None, wait=1, timeout=60, flush_scheduler=True):
"""
Wait until everybody has the same transactions in their memory
pools
"""
rpc_connections = nodes or self.nodes
timeout = int(timeout * self.options.timeout_factor)
stop_time = time.time() + timeout
while time.time() <= stop_time:
pool = [set(r.getrawmempool()) for r in rpc_connections]
if pool.count(pool[0]) == len(rpc_connections):
if flush_scheduler:
for r in rpc_connections:
r.syncwithvalidationinterfacequeue()
return
# Check that each peer has at least one connection
assert (all([len(x.getpeerinfo()) for x in rpc_connections]))
time.sleep(wait)
raise AssertionError("Mempool sync timed out after {}s:{}".format(
timeout,
"".join("\n {!r}".format(m) for m in pool),
))
def sync_all(self, nodes=None):
self.sync_blocks(nodes)
self.sync_mempools(nodes)
def wait_until(self, test_function, timeout=60):
return wait_until_helper(test_function, timeout=timeout, timeout_factor=self.options.timeout_factor)
# Private helper methods. These should not be accessed by the subclass test scripts.
def _start_logging(self):
# Add logger and logging handlers
self.log = logging.getLogger('TestFramework')
self.log.setLevel(logging.DEBUG)
# Create file handler to log all messages
fh = logging.FileHandler(self.options.tmpdir + '/test_framework.log', encoding='utf-8')
fh.setLevel(logging.DEBUG)
# Create console handler to log messages to stderr. By default this logs only error messages, but can be configured with --loglevel.
ch = logging.StreamHandler(sys.stdout)
# User can provide log level as a number or string (eg DEBUG). loglevel was caught as a string, so try to convert it to an int
ll = int(self.options.loglevel) if self.options.loglevel.isdigit() else self.options.loglevel.upper()
ch.setLevel(ll)
# Format logs the same as umkoind's debug.log with microprecision (so log files can be concatenated and sorted)
formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d000Z %(name)s (%(levelname)s): %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')
formatter.converter = time.gmtime
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
self.log.addHandler(fh)
self.log.addHandler(ch)
if self.options.trace_rpc:
rpc_logger = logging.getLogger("UmkoinRPC")
rpc_logger.setLevel(logging.DEBUG)
rpc_handler = logging.StreamHandler(sys.stdout)
rpc_handler.setLevel(logging.DEBUG)
rpc_logger.addHandler(rpc_handler)
def _initialize_chain(self):
"""Initialize a pre-mined blockchain for use by the test.
Create a cache of a 199-block-long chain
Afterward, create num_nodes copies from the cache."""
CACHE_NODE_ID = 0 # Use node 0 to create the cache for all other nodes
cache_node_dir = get_datadir_path(self.options.cachedir, CACHE_NODE_ID)
assert self.num_nodes <= MAX_NODES
if not os.path.isdir(cache_node_dir):
self.log.debug("Creating cache directory {}".format(cache_node_dir))
initialize_datadir(self.options.cachedir, CACHE_NODE_ID, self.chain, self.disable_autoconnect)
self.nodes.append(
TestNode(
CACHE_NODE_ID,
cache_node_dir,
chain=self.chain,
extra_conf=["bind=127.0.0.1"],
extra_args=['-disablewallet'],
rpchost=None,
timewait=self.rpc_timeout,
timeout_factor=self.options.timeout_factor,
umkoind=self.options.umkoind,
umkoin_cli=self.options.umkoincli,
coverage_dir=None,
cwd=self.options.tmpdir,
descriptors=self.options.descriptors,
))
self.start_node(CACHE_NODE_ID)
cache_node = self.nodes[CACHE_NODE_ID]
# Wait for RPC connections to be ready
cache_node.wait_for_rpc_connection()
# Set a time in the past, so that blocks don't end up in the future
cache_node.setmocktime(cache_node.getblockheader(cache_node.getbestblockhash())['time'])
# Create a 199-block-long chain; each of the 3 first nodes
# gets 25 mature blocks and 25 immature.
# The 4th address gets 25 mature and only 24 immature blocks so that the very last
# block in the cache does not age too much (have an old tip age).
# This is needed so that we are out of IBD when the test starts,
# see the tip age check in IsInitialBlockDownload().
gen_addresses = [k.address for k in TestNode.PRIV_KEYS][:3] + [ADDRESS_BCRT1_P2WSH_OP_TRUE]
assert_equal(len(gen_addresses), 4)
for i in range(8):
self.generatetoaddress(
cache_node,
nblocks=25 if i != 7 else 24,
address=gen_addresses[i % len(gen_addresses)],
)
assert_equal(cache_node.getblockchaininfo()["blocks"], 199)
# Shut it down, and clean up cache directories:
self.stop_nodes()
self.nodes = []
def cache_path(*paths):
return os.path.join(cache_node_dir, self.chain, *paths)
os.rmdir(cache_path('wallets')) # Remove empty wallets dir
for entry in os.listdir(cache_path()):
if entry not in ['chainstate', 'blocks', 'indexes']: # Only indexes, chainstate and blocks folders
os.remove(cache_path(entry))
for i in range(self.num_nodes):
self.log.debug("Copy cache directory {} to node {}".format(cache_node_dir, i))
to_dir = get_datadir_path(self.options.tmpdir, i)
shutil.copytree(cache_node_dir, to_dir)
initialize_datadir(self.options.tmpdir, i, self.chain, self.disable_autoconnect) # Overwrite port/rpcport in umkoin.conf
def _initialize_chain_clean(self):
"""Initialize empty blockchain for use by the test.
Create an empty blockchain and num_nodes wallets.
Useful if a test case wants complete control over initialization."""
for i in range(self.num_nodes):
initialize_datadir(self.options.tmpdir, i, self.chain, self.disable_autoconnect)
def skip_if_no_py3_zmq(self):
"""Attempt to import the zmq package and skip the test if the import fails."""
try:
import zmq # noqa
except ImportError:
raise SkipTest("python3-zmq module not available.")
def skip_if_no_umkoind_zmq(self):
"""Skip the running test if umkoind has not been compiled with zmq support."""
if not self.is_zmq_compiled():
raise SkipTest("umkoind has not been built with zmq enabled.")
def skip_if_no_wallet(self):
"""Skip the running test if wallet has not been compiled."""
self.requires_wallet = True
if not self.is_wallet_compiled():
raise SkipTest("wallet has not been compiled.")
if self.options.descriptors:
self.skip_if_no_sqlite()
else:
self.skip_if_no_bdb()
def skip_if_no_sqlite(self):
"""Skip the running test if sqlite has not been compiled."""
if not self.is_sqlite_compiled():
raise SkipTest("sqlite has not been compiled.")
def skip_if_no_bdb(self):
"""Skip the running test if BDB has not been compiled."""
if not self.is_bdb_compiled():
raise SkipTest("BDB has not been compiled.")
def skip_if_no_wallet_tool(self):
"""Skip the running test if umkoin-wallet has not been compiled."""
if not self.is_wallet_tool_compiled():
raise SkipTest("umkoin-wallet has not been compiled")
def skip_if_no_cli(self):
"""Skip the running test if umkoin-cli has not been compiled."""
if not self.is_cli_compiled():
raise SkipTest("umkoin-cli has not been compiled.")
def skip_if_no_previous_releases(self):
"""Skip the running test if previous releases are not available."""
if not self.has_previous_releases():
raise SkipTest("previous releases not available or disabled")
def has_previous_releases(self):
"""Checks whether previous releases are present and enabled."""
if not os.path.isdir(self.options.previous_releases_path):
if self.options.prev_releases:
raise AssertionError("Force test of previous releases but releases missing: {}".format(
self.options.previous_releases_path))
return self.options.prev_releases
def skip_if_no_external_signer(self):
"""Skip the running test if external signer support has not been compiled."""
if not self.is_external_signer_compiled():
raise SkipTest("external signer support has not been compiled.")
def is_cli_compiled(self):
"""Checks whether umkoin-cli was compiled."""
return self.config["components"].getboolean("ENABLE_CLI")
def is_external_signer_compiled(self):
"""Checks whether external signer support was compiled."""
return self.config["components"].getboolean("ENABLE_EXTERNAL_SIGNER")
def is_wallet_compiled(self):
"""Checks whether the wallet module was compiled."""
return self.config["components"].getboolean("ENABLE_WALLET")
def is_wallet_tool_compiled(self):
"""Checks whether umkoin-wallet was compiled."""
return self.config["components"].getboolean("ENABLE_WALLET_TOOL")
def is_zmq_compiled(self):
"""Checks whether the zmq module was compiled."""
return self.config["components"].getboolean("ENABLE_ZMQ")
def is_sqlite_compiled(self):
"""Checks whether the wallet module was compiled with Sqlite support."""
return self.config["components"].getboolean("USE_SQLITE")
def is_bdb_compiled(self):
"""Checks whether the wallet module was compiled with BDB support."""
return self.config["components"].getboolean("USE_BDB")
def is_syscall_sandbox_compiled(self):
"""Checks whether the syscall sandbox was compiled."""
return self.config["components"].getboolean("ENABLE_SYSCALL_SANDBOX")
|
[] |
[] |
[
"PREVIOUS_RELEASES_DIR",
"PATH",
"UMKOINCLI",
"UMKOIND"
] |
[]
|
["PREVIOUS_RELEASES_DIR", "PATH", "UMKOINCLI", "UMKOIND"]
|
python
| 4 | 0 | |
examples/stommel2d/stommel2d.py
|
"""
Stommel gyre test case in 2D
============================
Wind-driven geostrophic gyre in large basin.
Setup is according to [1].
[1] Comblen, R., Lambrechts, J., Remacle, J.-F., and Legat, V. (2010).
Practical evaluation of five partly discontinuous finite element pairs
for the non-conservative shallow water equations. International Journal
for Numerical Methods in Fluids, 63(6):701-724.
"""
from thetis import *
lx = 1.0e6
nx = 20
mesh2d = RectangleMesh(nx, nx, lx, lx)
outputdir = 'outputs'
print_output('Exporting to ' + outputdir)
depth = 1000.0
t_end = 75*12*2*3600
t_export = 3600*2
if os.getenv('THETIS_REGRESSION_TEST') is not None:
t_end = 5*t_export
# bathymetry
P1_2d = FunctionSpace(mesh2d, 'CG', 1)
P1v_2d = VectorFunctionSpace(mesh2d, 'CG', 1)
bathymetry_2d = Function(P1_2d, name='Bathymetry')
bathymetry_2d.assign(depth)
# Coriolis forcing
coriolis_2d = Function(P1_2d)
f0, beta = 1.0e-4, 2.0e-11
y_0 = 0.0
x, y = SpatialCoordinate(mesh2d)
coriolis_2d.interpolate(f0 + beta*(y-y_0))
# Wind stress
wind_stress_2d = Function(P1v_2d, name='wind stress')
tau_max = 0.1
wind_stress_2d.interpolate(as_vector((tau_max*sin(pi*(y/lx - 0.5)), 0)))
# linear dissipation: tau_bot/(h*rho) = -bf_gamma*u
linear_drag_coefficient = Constant(1e-6)
# --- create solver ---
solver_obj = solver2d.FlowSolver2d(mesh2d, bathymetry_2d)
options = solver_obj.options
options.use_nonlinear_equations = False
options.coriolis_frequency = coriolis_2d
options.wind_stress = wind_stress_2d
options.linear_drag_coefficient = linear_drag_coefficient
options.simulation_export_time = t_export
options.simulation_end_time = t_end
options.timestepper_type = 'CrankNicolson'
options.timestep = 360.0
options.output_directory = outputdir
options.horizontal_velocity_scale = Constant(0.01)
options.check_volume_conservation_2d = True
options.fields_to_export = ['uv_2d', 'elev_2d']
options.fields_to_export_hdf5 = ['uv_2d', 'elev_2d']
solver_obj.iterate()
|
[] |
[] |
[
"THETIS_REGRESSION_TEST"
] |
[]
|
["THETIS_REGRESSION_TEST"]
|
python
| 1 | 0 | |
src/snapshot/cluster_snapshot_function.py
|
import os
import boto3
import constants
import utility as util
def lambda_create_cluster_snapshot(event, context):
"""create snapshot of db cluster"""
region = os.environ['Region']
rds = boto3.client('rds', region)
result = {}
cluster_id = event['identifier']
snapshot_id = event['identifier'] + constants.SNAPSHOT_POSTFIX
try:
rds.create_db_cluster_snapshot(
DBClusterSnapshotIdentifier = snapshot_id,
DBClusterIdentifier = cluster_id
)
if event['task'] == "create_snapshot_only":
result['taskname'] = constants.SNAPSHOT_ONLY
else:
result['taskname'] = constants.SNAPSHOT
result['identifier'] = cluster_id
return result
except Exception as error:
util.eval_snapshot_exception(error, cluster_id, rds)
|
[] |
[] |
[
"Region"
] |
[]
|
["Region"]
|
python
| 1 | 0 | |
cmd/ipfs/util/ulimit.go
|
package util
import (
"errors"
"fmt"
"os"
"strconv"
"syscall"
logging "gx/ipfs/QmZChCsSt8DctjceaL56Eibc29CVQq4dGKRXC5JRZ6Ppae/go-log"
)
var log = logging.Logger("ulimit")
var (
supportsFDManagement = false
// getlimit returns the soft and hard limits of file descriptors counts
getLimit func() (int64, int64, error)
// set limit sets the soft and hard limits of file descriptors counts
setLimit func(int64, int64) error
)
// maxFds is the maximum number of file descriptors that go-ipfs
// can use. The default value is 1024. This can be overwritten by the
// IPFS_FD_MAX env variable
var maxFds = uint64(2048)
// setMaxFds sets the maxFds value from IPFS_FD_MAX
// env variable if it's present on the system
func setMaxFds() {
// check if the IPFS_FD_MAX is set up and if it does
// not have a valid fds number notify the user
if val := os.Getenv("IPFS_FD_MAX"); val != "" {
fds, err := strconv.ParseUint(val, 10, 64)
if err != nil {
log.Errorf("bad value for IPFS_FD_MAX: %s", err)
return
}
maxFds = fds
}
}
// ManageFdLimit raise the current max file descriptor count
// of the process based on the IPFS_FD_MAX value
func ManageFdLimit() error {
if !supportsFDManagement {
return nil
}
setMaxFds()
soft, hard, err := getLimit()
if err != nil {
return err
}
max := int64(maxFds)
if max <= soft {
return nil
}
// the soft limit is the value that the kernel enforces for the
// corresponding resource
// the hard limit acts as a ceiling for the soft limit
// an unprivileged process may only set it's soft limit to a
// alue in the range from 0 up to the hard limit
if err = setLimit(max, max); err != nil {
if err != syscall.EPERM {
return fmt.Errorf("error setting: ulimit: %s", err)
}
// the process does not have permission so we should only
// set the soft value
if max > hard {
return errors.New(
"cannot set rlimit, IPFS_FD_MAX is larger than the hard limit",
)
}
if err = setLimit(max, hard); err != nil {
return fmt.Errorf("error setting ulimit wihout hard limit: %s", err)
}
}
fmt.Printf("Successfully raised file descriptor limit to %d.\n", max)
return nil
}
|
[
"\"IPFS_FD_MAX\""
] |
[] |
[
"IPFS_FD_MAX"
] |
[]
|
["IPFS_FD_MAX"]
|
go
| 1 | 0 | |
credentials/vault.go
|
package credentials
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// Gets the Vault token from the ENV or .vault_token file
func GetVaultToken() (string, error) {
if token := os.Getenv("VAULT_TOKEN"); token != "" {
return token, nil
}
homedir, err := os.UserHomeDir()
if err != nil {
return "", err
}
tokenFile := filepath.Join(homedir, ".vault-token")
if _, err := os.Stat(tokenFile); os.IsNotExist(err) {
return "", fmt.Errorf("No Vault token found. You must set a 'VAULT_TOKEN' env var or create a '.vault-token' file.")
}
if bytes, err := ioutil.ReadFile(tokenFile); err != nil {
return "", fmt.Errorf("Could not read Vault token")
} else {
return strings.TrimSpace(string(bytes)), nil
}
}
|
[
"\"VAULT_TOKEN\""
] |
[] |
[
"VAULT_TOKEN"
] |
[]
|
["VAULT_TOKEN"]
|
go
| 1 | 0 | |
app/app/settings.py
|
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
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!
SECRET_KEY = 'a*l_j+nku98-31jlfzsv0ms(()tfmcr8k&tf3uyxnr@=_jq1o2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'core',
'user',
'recipe',
]
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 = 'app.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 = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'core.User'
|
[] |
[] |
[
"DB_PASS",
"DB_USER",
"DB_NAME",
"DB_HOST"
] |
[]
|
["DB_PASS", "DB_USER", "DB_NAME", "DB_HOST"]
|
python
| 4 | 0 | |
install.py
|
# makes sure prerequisites are already installed
import os
import utils.system_utils as system
system.printSystemInfo()
pip3Path = os.getenv('PIP3')
if not pip3Path:
print("PIP3 environment variable not set")
cmd = ['which', 'pip3']
pip3Path = system.runCommand(cmd)
pip3Path = pip3Path.strip()
if not pip3Path:
print("pip3 path not found")
exit()
try:
import requests
print("package requests already installed")
except:
system.pipInstall('requests')
try:
import pandas
print("package pandas already installed")
except:
system.pipInstall('pandas')
system.runNodeCommand(['npm', 'i'])
print("Install Success")
|
[] |
[] |
[
"PIP3"
] |
[]
|
["PIP3"]
|
python
| 1 | 0 | |
04_test.py
|
import os
import sys
import importlib
import argparse
import csv
import numpy as np
import time
import pickle
import pathlib
import gzip
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import svmrank
import utilities
from utilities_tf import load_batch_gcnn
def load_batch_flat(sample_files, feats_type, augment_feats, normalize_feats):
cand_features = []
cand_choices = []
cand_scoress = []
for i, filename in enumerate(sample_files):
cand_states, cand_scores, cand_choice = utilities.load_flat_samples(filename, feats_type, 'scores', augment_feats, normalize_feats)
cand_features.append(cand_states)
cand_choices.append(cand_choice)
cand_scoress.append(cand_scores)
n_cands_per_sample = [v.shape[0] for v in cand_features]
cand_features = np.concatenate(cand_features, axis=0).astype(np.float32, copy=False)
cand_choices = np.asarray(cand_choices).astype(np.int32, copy=False)
cand_scoress = np.concatenate(cand_scoress, axis=0).astype(np.float32, copy=False)
n_cands_per_sample = np.asarray(n_cands_per_sample).astype(np.int32, copy=False)
return cand_features, n_cands_per_sample, cand_choices, cand_scoress
def padding(output, n_vars_per_sample, fill=-1e8):
n_vars_max = tf.reduce_max(n_vars_per_sample)
output = tf.split(
value=output,
num_or_size_splits=n_vars_per_sample,
axis=1,
)
output = tf.concat([
tf.pad(
x,
paddings=[[0, 0], [0, n_vars_max - tf.shape(x)[1]]],
mode='CONSTANT',
constant_values=fill)
for x in output
], axis=0)
return output
def process(policy, dataloader, top_k):
mean_kacc = np.zeros(len(top_k))
n_samples_processed = 0
for batch in dataloader:
if policy['type'] == 'gcnn':
c, ei, ev, v, n_cs, n_vs, n_cands, cands, best_cands, cand_scores = batch
pred_scores = policy['model']((c, ei, ev, v, tf.reduce_sum(n_cs, keepdims=True), tf.reduce_sum(n_vs, keepdims=True)), tf.convert_to_tensor(False))
# filter candidate variables
pred_scores = tf.expand_dims(tf.gather(tf.squeeze(pred_scores, 0), cands), 0)
elif policy['type'] == 'ml-competitor':
cand_feats, n_cands, best_cands, cand_scores = batch
# move to numpy
cand_feats = cand_feats.numpy()
n_cands = n_cands.numpy()
# feature normalization
cand_feats = (cand_feats - policy['feat_shift']) / policy['feat_scale']
pred_scores = policy['model'].predict(cand_feats)
# move back to TF
pred_scores = tf.convert_to_tensor(pred_scores.reshape((1, -1)), dtype=tf.float32)
# padding
pred_scores = padding(pred_scores, n_cands)
true_scores = padding(tf.reshape(cand_scores, (1, -1)), n_cands)
true_bestscore = tf.reduce_max(true_scores, axis=-1, keepdims=True)
assert all(true_bestscore.numpy() == np.take_along_axis(true_scores.numpy(), best_cands.numpy().reshape((-1, 1)), axis=1))
kacc = []
for k in top_k:
pred_top_k = tf.nn.top_k(pred_scores, k=k)[1].numpy()
pred_top_k_true_scores = np.take_along_axis(true_scores.numpy(), pred_top_k, axis=1)
kacc.append(np.mean(np.any(pred_top_k_true_scores == true_bestscore.numpy(), axis=1)))
kacc = np.asarray(kacc)
batch_size = int(n_cands.shape[0])
mean_kacc += kacc * batch_size
n_samples_processed += batch_size
mean_kacc /= n_samples_processed
return mean_kacc
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'problem',
help='MILP instance type to process.',
choices=['setcover', 'cauctions', 'facilities', 'indset'],
)
parser.add_argument(
'-g', '--gpu',
help='CUDA GPU id (-1 for CPU).',
type=int,
default=0,
)
args = parser.parse_args()
print(f"problem: {args.problem}")
print(f"gpu: {args.gpu}")
os.makedirs("results", exist_ok=True)
result_file = f"results/{args.problem}_validation_{time.strftime('%Y%m%d-%H%M%S')}.csv"
seeds = [0, 1, 2, 3, 4]
gcnn_models = ['baseline']
other_models = ['extratrees_gcnn_agg', 'lambdamart_khalil', 'svmrank_khalil']
test_batch_size = 128
top_k = [1, 3, 5, 10]
problem_folders = {
'setcover': 'setcover/500r_1000c_0.05d',
'cauctions': 'cauctions/100_500',
'facilities': 'facilities/100_100_5',
'indset': 'indset/500_4',
}
problem_folder = problem_folders[args.problem]
if args.problem == 'setcover':
gcnn_models += ['mean_convolution', 'no_prenorm']
result_file = f"results/{args.problem}_test_{time.strftime('%Y%m%d-%H%M%S')}"
result_file = result_file + '.csv'
os.makedirs('results', exist_ok=True)
### TENSORFLOW SETUP ###
if args.gpu == -1:
os.environ['CUDA_VISIBLE_DEVICES'] = ''
else:
os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}'
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.enable_eager_execution(config)
tf.executing_eagerly()
test_files = list(pathlib.Path(f"data/samples/{problem_folder}/test").glob('sample_*.pkl'))
test_files = [str(x) for x in test_files]
print(f"{len(test_files)} test samples")
evaluated_policies = [['gcnn', model] for model in gcnn_models] + \
[['ml-competitor', model] for model in other_models]
fieldnames = [
'policy',
'seed',
] + [
f'acc@{k}' for k in top_k
]
with open(result_file, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for policy_type, policy_name in evaluated_policies:
print(f"{policy_type}:{policy_name}...")
for seed in seeds:
rng = np.random.RandomState(seed)
tf.set_random_seed(rng.randint(np.iinfo(int).max))
policy = {}
policy['name'] = policy_name
policy['type'] = policy_type
if policy['type'] == 'gcnn':
# load model
sys.path.insert(0, os.path.abspath(f"models/{policy['name']}"))
import model
importlib.reload(model)
del sys.path[0]
policy['model'] = model.GCNPolicy()
policy['model'].restore_state(f"trained_models/{args.problem}/{policy['name']}/{seed}/best_params.pkl")
policy['model'].call = tfe.defun(policy['model'].call, input_signature=policy['model'].input_signature)
policy['batch_datatypes'] = [tf.float32, tf.int32, tf.float32,
tf.float32, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.float32]
policy['batch_fun'] = load_batch_gcnn
else:
# load feature normalization parameters
try:
with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/normalization.pkl", 'rb') as f:
policy['feat_shift'], policy['feat_scale'] = pickle.load(f)
except:
policy['feat_shift'], policy['feat_scale'] = 0, 1
# load model
if policy_name.startswith('svmrank'):
policy['model'] = svmrank.Model().read(f"trained_models/{args.problem}/{policy['name']}/{seed}/model.txt")
else:
with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/model.pkl", 'rb') as f:
policy['model'] = pickle.load(f)
# load feature specifications
with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/feat_specs.pkl", 'rb') as f:
feat_specs = pickle.load(f)
policy['batch_datatypes'] = [tf.float32, tf.int32, tf.int32, tf.float32]
policy['batch_fun'] = lambda x: load_batch_flat(x, feat_specs['type'], feat_specs['augment'], feat_specs['qbnorm'])
test_data = tf.data.Dataset.from_tensor_slices(test_files)
test_data = test_data.batch(test_batch_size)
test_data = test_data.map(lambda x: tf.py_func(
policy['batch_fun'], [x], policy['batch_datatypes']))
test_data = test_data.prefetch(2)
test_kacc = process(policy, test_data, top_k)
print(f" {seed} " + " ".join([f"acc@{k}: {100*acc:4.1f}" for k, acc in zip(top_k, test_kacc)]))
writer.writerow({
**{
'policy': f"{policy['type']}:{policy['name']}",
'seed': seed,
},
**{
f'acc@{k}': test_kacc[i] for i, k in enumerate(top_k)
},
})
csvfile.flush()
|
[] |
[] |
[
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_VISIBLE_DEVICES"]
|
python
| 1 | 0 | |
vendor/github.com/gophercloud/gophercloud/acceptance/clients/clients.go
|
// Package clients contains functions for creating OpenStack service clients
// for use in acceptance tests. It also manages the required environment
// variables to run the tests.
package clients
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
baremetalNoAuth "github.com/gophercloud/gophercloud/openstack/baremetal/noauth"
blockstorageNoAuth "github.com/gophercloud/gophercloud/openstack/blockstorage/noauth"
)
// AcceptanceTestChoices contains image and flavor selections for use by the acceptance tests.
type AcceptanceTestChoices struct {
// ImageID contains the ID of a valid image.
ImageID string
// FlavorID contains the ID of a valid flavor.
FlavorID string
// FlavorIDResize contains the ID of a different flavor available on the same OpenStack installation, that is distinct
// from FlavorID.
FlavorIDResize string
// FloatingIPPool contains the name of the pool from where to obtain floating IPs.
FloatingIPPoolName string
// MagnumKeypair contains the ID of a valid key pair.
MagnumKeypair string
// MagnumImageID contains the ID of a valid magnum image.
MagnumImageID string
// NetworkName is the name of a network to launch the instance on.
NetworkName string
// NetworkID is the ID of a network to launch the instance on.
NetworkID string
// SubnetID is the ID of a subnet to launch the instance on.
SubnetID string
// ExternalNetworkID is the network ID of the external network.
ExternalNetworkID string
// DBDatastoreType is the datastore type for DB tests.
DBDatastoreType string
// DBDatastoreTypeID is the datastore type version for DB tests.
DBDatastoreVersion string
}
// AcceptanceTestChoicesFromEnv populates a ComputeChoices struct from environment variables.
// If any required state is missing, an `error` will be returned that enumerates the missing properties.
func AcceptanceTestChoicesFromEnv() (*AcceptanceTestChoices, error) {
imageID := os.Getenv("OS_IMAGE_ID")
flavorID := os.Getenv("OS_FLAVOR_ID")
flavorIDResize := os.Getenv("OS_FLAVOR_ID_RESIZE")
magnumImageID := os.Getenv("OS_MAGNUM_IMAGE_ID")
magnumKeypair := os.Getenv("OS_MAGNUM_KEYPAIR")
networkName := os.Getenv("OS_NETWORK_NAME")
networkID := os.Getenv("OS_NETWORK_ID")
subnetID := os.Getenv("OS_SUBNET_ID")
floatingIPPoolName := os.Getenv("OS_POOL_NAME")
externalNetworkID := os.Getenv("OS_EXTGW_ID")
dbDatastoreType := os.Getenv("OS_DB_DATASTORE_TYPE")
dbDatastoreVersion := os.Getenv("OS_DB_DATASTORE_VERSION")
missing := make([]string, 0, 3)
if imageID == "" {
missing = append(missing, "OS_IMAGE_ID")
}
if flavorID == "" {
missing = append(missing, "OS_FLAVOR_ID")
}
if flavorIDResize == "" {
missing = append(missing, "OS_FLAVOR_ID_RESIZE")
}
if floatingIPPoolName == "" {
missing = append(missing, "OS_POOL_NAME")
}
if externalNetworkID == "" {
missing = append(missing, "OS_EXTGW_ID")
}
/* // Temporarily disabled, see https://github.com/gophercloud/gophercloud/issues/1345
if networkID == "" {
missing = append(missing, "OS_NETWORK_ID")
}
if subnetID == "" {
missing = append(missing, "OS_SUBNET_ID")
}
*/
if networkName == "" {
networkName = "private"
}
notDistinct := ""
if flavorID == flavorIDResize {
notDistinct = "OS_FLAVOR_ID and OS_FLAVOR_ID_RESIZE must be distinct."
}
if len(missing) > 0 || notDistinct != "" {
text := "You're missing some important setup:\n"
if len(missing) > 0 {
text += " * These environment variables must be provided: " + strings.Join(missing, ", ") + "\n"
}
if notDistinct != "" {
text += " * " + notDistinct + "\n"
}
return nil, fmt.Errorf(text)
}
return &AcceptanceTestChoices{
ImageID: imageID,
FlavorID: flavorID,
FlavorIDResize: flavorIDResize,
FloatingIPPoolName: floatingIPPoolName,
MagnumImageID: magnumImageID,
MagnumKeypair: magnumKeypair,
NetworkName: networkName,
NetworkID: networkID,
SubnetID: subnetID,
ExternalNetworkID: externalNetworkID,
DBDatastoreType: dbDatastoreType,
DBDatastoreVersion: dbDatastoreVersion,
}, nil
}
// NewBlockStorageV1Client returns a *ServiceClient for making calls
// to the OpenStack Block Storage v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewBlockStorageV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewBlockStorageV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewBlockStorageV2Client returns a *ServiceClient for making calls
// to the OpenStack Block Storage v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewBlockStorageV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewBlockStorageV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewBlockStorageV3Client returns a *ServiceClient for making calls
// to the OpenStack Block Storage v3 API. An error will be returned
// if authentication or client creation was not possible.
func NewBlockStorageV3Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewBlockStorageV3(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewBlockStorageV2NoAuthClient returns a noauth *ServiceClient for
// making calls to the OpenStack Block Storage v2 API. An error will be
// returned if client creation was not possible.
func NewBlockStorageV2NoAuthClient() (*gophercloud.ServiceClient, error) {
client, err := blockstorageNoAuth.NewClient(gophercloud.AuthOptions{
Username: os.Getenv("OS_USERNAME"),
TenantName: os.Getenv("OS_TENANT_NAME"),
})
if err != nil {
return nil, err
}
client = configureDebug(client)
return blockstorageNoAuth.NewBlockStorageNoAuth(client, blockstorageNoAuth.EndpointOpts{
CinderEndpoint: os.Getenv("CINDER_ENDPOINT"),
})
}
// NewBlockStorageV3NoAuthClient returns a noauth *ServiceClient for
// making calls to the OpenStack Block Storage v2 API. An error will be
// returned if client creation was not possible.
func NewBlockStorageV3NoAuthClient() (*gophercloud.ServiceClient, error) {
client, err := blockstorageNoAuth.NewClient(gophercloud.AuthOptions{
Username: os.Getenv("OS_USERNAME"),
TenantName: os.Getenv("OS_TENANT_NAME"),
})
if err != nil {
return nil, err
}
client = configureDebug(client)
return blockstorageNoAuth.NewBlockStorageNoAuth(client, blockstorageNoAuth.EndpointOpts{
CinderEndpoint: os.Getenv("CINDER_ENDPOINT"),
})
}
// NewComputeV2Client returns a *ServiceClient for making calls
// to the OpenStack Compute v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewComputeV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewComputeV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewBareMetalV1Client returns a *ServiceClient for making calls
// to the OpenStack Bare Metal v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewBareMetalV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewBareMetalV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewBareMetalV1NoAuthClient returns a *ServiceClient for making calls
// to the OpenStack Bare Metal v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewBareMetalV1NoAuthClient() (*gophercloud.ServiceClient, error) {
return baremetalNoAuth.NewBareMetalNoAuth(baremetalNoAuth.EndpointOpts{
IronicEndpoint: os.Getenv("IRONIC_ENDPOINT"),
})
}
// NewBareMetalIntrospectionV1Client returns a *ServiceClient for making calls
// to the OpenStack Bare Metal Introspection v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewBareMetalIntrospectionV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewBareMetalIntrospectionV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewDBV1Client returns a *ServiceClient for making calls
// to the OpenStack Database v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewDBV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewDBV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewDNSV2Client returns a *ServiceClient for making calls
// to the OpenStack Compute v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewDNSV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewDNSV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewIdentityV2Client returns a *ServiceClient for making calls
// to the OpenStack Identity v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewIdentityV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewIdentityV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewIdentityV2AdminClient returns a *ServiceClient for making calls
// to the Admin Endpoint of the OpenStack Identity v2 API. An error
// will be returned if authentication or client creation was not possible.
func NewIdentityV2AdminClient() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewIdentityV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
Availability: gophercloud.AvailabilityAdmin,
})
}
// NewIdentityV2UnauthenticatedClient returns an unauthenticated *ServiceClient
// for the OpenStack Identity v2 API. An error will be returned if
// authentication or client creation was not possible.
func NewIdentityV2UnauthenticatedClient() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.NewClient(ao.IdentityEndpoint)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewIdentityV2(client, gophercloud.EndpointOpts{})
}
// NewIdentityV3Client returns a *ServiceClient for making calls
// to the OpenStack Identity v3 API. An error will be returned
// if authentication or client creation was not possible.
func NewIdentityV3Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewIdentityV3(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewIdentityV3UnauthenticatedClient returns an unauthenticated *ServiceClient
// for the OpenStack Identity v3 API. An error will be returned if
// authentication or client creation was not possible.
func NewIdentityV3UnauthenticatedClient() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.NewClient(ao.IdentityEndpoint)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewIdentityV3(client, gophercloud.EndpointOpts{})
}
// NewImageServiceV2Client returns a *ServiceClient for making calls to the
// OpenStack Image v2 API. An error will be returned if authentication or
// client creation was not possible.
func NewImageServiceV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewImageServiceV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewNetworkV2Client returns a *ServiceClient for making calls to the
// OpenStack Networking v2 API. An error will be returned if authentication
// or client creation was not possible.
func NewNetworkV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewNetworkV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewObjectStorageV1Client returns a *ServiceClient for making calls to the
// OpenStack Object Storage v1 API. An error will be returned if authentication
// or client creation was not possible.
func NewObjectStorageV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewObjectStorageV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewSharedFileSystemV2Client returns a *ServiceClient for making calls
// to the OpenStack Shared File System v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewSharedFileSystemV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewSharedFileSystemV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewLoadBalancerV2Client returns a *ServiceClient for making calls to the
// OpenStack Octavia v2 API. An error will be returned if authentication
// or client creation was not possible.
func NewLoadBalancerV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewLoadBalancerV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewClusteringV1Client returns a *ServiceClient for making calls
// to the OpenStack Clustering v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewClusteringV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewClusteringV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewMessagingV2Client returns a *ServiceClient for making calls
// to the OpenStack Messaging (Zaqar) v2 API. An error will be returned
// if authentication or client creation was not possible.
func NewMessagingV2Client(clientID string) (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewMessagingV2(client, clientID, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewContainerV1Client returns a *ServiceClient for making calls
// to the OpenStack Container V1 API. An error will be returned
// if authentication or client creation was not possible.
func NewContainerV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewContainerV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewKeyManagerV1Client returns a *ServiceClient for making calls
// to the OpenStack Key Manager (Barbican) v1 API. An error will be
// returned if authentication or client creation was not possible.
func NewKeyManagerV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewKeyManagerV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// configureDebug will configure the provider client to print the API
// requests and responses if OS_DEBUG is enabled.
func configureDebug(client *gophercloud.ProviderClient) *gophercloud.ProviderClient {
if os.Getenv("OS_DEBUG") != "" {
client.HTTPClient = http.Client{
Transport: &LogRoundTripper{
Rt: &http.Transport{},
},
}
}
return client
}
// NewContainerInfraV1Client returns a *ServiceClient for making calls
// to the OpenStack Container Infra Management v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewContainerInfraV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewContainerInfraV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewWorkflowV2Client returns a *ServiceClient for making calls
// to the OpenStack Workflow v2 API (Mistral). An error will be returned if
// authentication or client creation failed.
func NewWorkflowV2Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewWorkflowV2(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
// NewOrchestrationV1Client returns a *ServiceClient for making calls
// to the OpenStack Orchestration v1 API. An error will be returned
// if authentication or client creation was not possible.
func NewOrchestrationV1Client() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
client, err := openstack.AuthenticatedClient(ao)
if err != nil {
return nil, err
}
client = configureDebug(client)
return openstack.NewOrchestrationV1(client, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
}
|
[
"\"OS_IMAGE_ID\"",
"\"OS_FLAVOR_ID\"",
"\"OS_FLAVOR_ID_RESIZE\"",
"\"OS_MAGNUM_IMAGE_ID\"",
"\"OS_MAGNUM_KEYPAIR\"",
"\"OS_NETWORK_NAME\"",
"\"OS_NETWORK_ID\"",
"\"OS_SUBNET_ID\"",
"\"OS_POOL_NAME\"",
"\"OS_EXTGW_ID\"",
"\"OS_DB_DATASTORE_TYPE\"",
"\"OS_DB_DATASTORE_VERSION\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_USERNAME\"",
"\"OS_TENANT_NAME\"",
"\"CINDER_ENDPOINT\"",
"\"OS_USERNAME\"",
"\"OS_TENANT_NAME\"",
"\"CINDER_ENDPOINT\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"IRONIC_ENDPOINT\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_DEBUG\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\"",
"\"OS_REGION_NAME\""
] |
[] |
[
"OS_MAGNUM_KEYPAIR",
"OS_DB_DATASTORE_VERSION",
"OS_FLAVOR_ID",
"OS_SUBNET_ID",
"OS_REGION_NAME",
"OS_USERNAME",
"OS_DEBUG",
"OS_TENANT_NAME",
"OS_NETWORK_NAME",
"CINDER_ENDPOINT",
"OS_POOL_NAME",
"OS_EXTGW_ID",
"OS_DB_DATASTORE_TYPE",
"IRONIC_ENDPOINT",
"OS_NETWORK_ID",
"OS_IMAGE_ID",
"OS_MAGNUM_IMAGE_ID",
"OS_FLAVOR_ID_RESIZE"
] |
[]
|
["OS_MAGNUM_KEYPAIR", "OS_DB_DATASTORE_VERSION", "OS_FLAVOR_ID", "OS_SUBNET_ID", "OS_REGION_NAME", "OS_USERNAME", "OS_DEBUG", "OS_TENANT_NAME", "OS_NETWORK_NAME", "CINDER_ENDPOINT", "OS_POOL_NAME", "OS_EXTGW_ID", "OS_DB_DATASTORE_TYPE", "IRONIC_ENDPOINT", "OS_NETWORK_ID", "OS_IMAGE_ID", "OS_MAGNUM_IMAGE_ID", "OS_FLAVOR_ID_RESIZE"]
|
go
| 18 | 0 | |
BachelorETL/manage.py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BachelorETL.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 | |
export-scripts/export_range_check.py
|
#!/usr/bin/env python
from common import *
configure_network()
subprocess.run(["cmake", "."])
subprocess.run(["make"])
print("running the export_range_check")
num_records = 1000
print("running the case for " + str(num_records) + " entries")
for i in range(5):
time.sleep(5)
range = pow(2, 8 + 4 * i)
write_configure_info(str(num_records) + " " + str(range))
subprocess.run(["bin/export_range_check", os.getenv("EMP_MY_PARTY_ID"), "5000"])
rename_result_file("range_check_100k_" + str(8 + 4 * i))
move_to_scale_mamba("range_check_100k_" + str(8 + 4 * i))
|
[] |
[] |
[
"EMP_MY_PARTY_ID"
] |
[]
|
["EMP_MY_PARTY_ID"]
|
python
| 1 | 0 | |
cmd/release-controller/main.go
|
package main
import (
"context"
"flag"
"fmt"
"net/http"
"net/url"
"os"
goruntime "runtime"
"sort"
"strings"
"sync"
"time"
_ "net/http/pprof" // until openshift/library-go#309 merges
lru "github.com/hashicorp/golang-lru"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/cobra"
"gopkg.in/fsnotify.v1"
"k8s.io/klog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/version"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
imagev1 "github.com/openshift/api/image/v1"
imageclientset "github.com/openshift/client-go/image/clientset/versioned"
imageinformers "github.com/openshift/client-go/image/informers/externalversions"
imagelisters "github.com/openshift/client-go/image/listers/image/v1"
"github.com/openshift/library-go/pkg/serviceability"
prowconfig "k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/config/secret"
"k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/plugins"
"github.com/openshift/release-controller/pkg/bugzilla"
"github.com/openshift/release-controller/pkg/signer"
)
type options struct {
ReleaseNamespaces []string
PublishNamespaces []string
JobNamespace string
ProwNamespace string
ProwJobKubeconfig string
NonProwJobKubeconfig string
ReleasesKubeconfig string
ToolsKubeconfig string
ProwConfigPath string
JobConfigPath string
ListenAddr string
ArtifactsHost string
AuditStorage string
AuditGCSServiceAccount string
SigningKeyring string
CLIImageForAudit string
ToolsImageStreamTag string
DryRun bool
LimitSources []string
VerifyBugzilla bool
PluginConfig string
github flagutil.GitHubOptions
bugzilla flagutil.BugzillaOptions
githubThrottle int
validateConfigs string
softDeleteReleaseTags bool
ReleaseArchitecture string
}
func main() {
serviceability.StartProfiler()
defer serviceability.Profile(os.Getenv("OPENSHIFT_PROFILE")).Stop()
// prow registers this on init
interrupts.OnInterrupt(func() { os.Exit(0) })
original := flag.CommandLine
klog.InitFlags(original)
original.Set("alsologtostderr", "true")
original.Set("v", "2")
opt := &options{
ListenAddr: ":8080",
ToolsImageStreamTag: ":tests",
}
cmd := &cobra.Command{
Run: func(cmd *cobra.Command, arguments []string) {
if f := cmd.Flags().Lookup("audit"); f.Changed && len(f.Value.String()) == 0 {
klog.Exitf("error: --audit must include a location to store audit logs")
}
if err := opt.Run(); err != nil {
klog.Exitf("error: %v", err)
}
},
}
flagset := cmd.Flags()
flagset.BoolVar(&opt.DryRun, "dry-run", opt.DryRun, "Perform no actions on the release streams")
flagset.StringVar(&opt.AuditStorage, "audit", opt.AuditStorage, "A storage location to report audit logs to, if specified. The location may be a file://path or gs:// GCS bucket and path.")
flagset.StringVar(&opt.AuditGCSServiceAccount, "audit-gcs-service-account", opt.AuditGCSServiceAccount, "An optional path to a service account file that should be used for uploading audit information to GCS.")
flagset.StringSliceVar(&opt.LimitSources, "only-source", opt.LimitSources, "The names of the image streams to operate on. Intended for testing.")
flagset.StringVar(&opt.SigningKeyring, "sign", opt.SigningKeyring, "The OpenPGP keyring to sign releases with. Only releases that can be verified will be signed.")
flagset.StringVar(&opt.CLIImageForAudit, "audit-cli-image", opt.CLIImageForAudit, "The command line image pullspec to use for audit and signing. This should be set to a digest under the signers control to prevent attackers from forging verification. If you pass 'local' the oc binary on the path will be used instead of running a job.")
flagset.StringVar(&opt.ToolsImageStreamTag, "tools-image-stream-tag", opt.ToolsImageStreamTag, "An image stream tag pointing to a release stream that contains the oc command and git (usually <master>:tests).")
var ignored string
flagset.StringVar(&ignored, "to", ignored, "REMOVED: The image stream in the release namespace to push releases to.")
flagset.StringVar(&opt.ProwJobKubeconfig, "prow-job-kubeconfig", opt.ProwJobKubeconfig, "The kubeconfig to use for interacting with ProwJobs. Defaults in-cluster config if unset.")
flagset.StringVar(&opt.NonProwJobKubeconfig, "non-prow-job-kubeconfig", opt.NonProwJobKubeconfig, "The kubeconfig to use for everything that is not prowjobs (namespaced, pods, batchjobs, ....). Falls back to incluster config if unset")
flagset.StringVar(&opt.ReleasesKubeconfig, "releases-kubeconfig", opt.ReleasesKubeconfig, "The kubeconfig to use for interacting with release imagestreams and jobs. Falls back to non-prow-job-kubeconfig and then incluster config if unset")
flagset.StringVar(&opt.ToolsKubeconfig, "tools-kubeconfig", opt.ToolsKubeconfig, "The kubeconfig to use for running the release-controller tools. Falls back to non-prow-job-kubeconfig and then incluster config if unset")
flagset.StringVar(&opt.JobNamespace, "job-namespace", opt.JobNamespace, "The namespace to execute jobs and hold temporary objects.")
flagset.StringSliceVar(&opt.ReleaseNamespaces, "release-namespace", opt.ReleaseNamespaces, "The namespace where the source image streams are located and where releases will be published to.")
flagset.StringSliceVar(&opt.PublishNamespaces, "publish-namespace", opt.PublishNamespaces, "Optional namespaces that the release might publish results to.")
flagset.StringVar(&opt.ProwNamespace, "prow-namespace", opt.ProwNamespace, "The namespace where the Prow jobs will be created (defaults to --job-namespace).")
flagset.StringVar(&opt.ProwConfigPath, "prow-config", opt.ProwConfigPath, "A config file containing the prow configuration.")
flagset.StringVar(&opt.JobConfigPath, "job-config", opt.JobConfigPath, "A config file containing the jobs to run against releases.")
flagset.StringVar(&opt.ArtifactsHost, "artifacts", opt.ArtifactsHost, "The public hostname of the artifacts server.")
flagset.StringVar(&opt.ListenAddr, "listen", opt.ListenAddr, "The address to serve release information on")
flagset.BoolVar(&opt.VerifyBugzilla, "verify-bugzilla", opt.VerifyBugzilla, "Update status of bugs fixed in accepted release to VERIFIED if PR was approved by QE.")
flagset.StringVar(&opt.PluginConfig, "plugin-config", opt.PluginConfig, "Path to Prow plugin config file. Used when verifying bugs, ignored otherwise.")
flagset.IntVar(&opt.githubThrottle, "github-throttle", 0, "Maximum number of GitHub requests per hour. Used by bugzilla verifier.")
flagset.StringVar(&opt.validateConfigs, "validate-configs", "", "Validate configs at specified directory and exit without running operator")
flagset.BoolVar(&opt.softDeleteReleaseTags, "soft-delete-release-tags", false, "If set to true, annotate imagestreamtags instead of deleting them")
flagset.StringVar(&opt.ReleaseArchitecture, "release-architecture", opt.ReleaseArchitecture, "The architecture of the releases to be created (defaults to 'amd64' if not specified).")
goFlagSet := flag.NewFlagSet("prowflags", flag.ContinueOnError)
opt.github.AddFlags(goFlagSet)
opt.bugzilla.AddFlags(goFlagSet)
flagset.AddGoFlagSet(goFlagSet)
flagset.AddGoFlag(original.Lookup("v"))
if err := setupKubeconfigWatches(opt); err != nil {
klog.Warningf("failed to set up kubeconfig watches: %v", err)
}
if err := cmd.Execute(); err != nil {
klog.Exitf("error: %v", err)
}
}
func (o *options) Run() error {
if o.validateConfigs != "" {
return validateConfigs(o.validateConfigs)
}
tagParts := strings.Split(o.ToolsImageStreamTag, ":")
if len(tagParts) != 2 || len(tagParts[1]) == 0 {
return fmt.Errorf("--tools-image-stream-tag must be STREAM:TAG or :TAG (default STREAM is the oldest release stream)")
}
if len(o.ReleaseNamespaces) == 0 {
return fmt.Errorf("no namespace set, use --release-namespace")
}
if len(o.JobNamespace) == 0 {
return fmt.Errorf("no job namespace set, use --job-namespace")
}
if len(o.ProwNamespace) == 0 {
o.ProwNamespace = o.JobNamespace
}
if sets.NewString(o.ReleaseNamespaces...).HasAny(o.PublishNamespaces...) {
return fmt.Errorf("--release-namespace and --publish-namespace may not overlap")
}
var architecture = "amd64"
if len(o.ReleaseArchitecture) > 0 {
architecture = o.ReleaseArchitecture
}
inClusterCfg, err := loadClusterConfig()
if err != nil {
return fmt.Errorf("failed to load incluster config: %w", err)
}
config, err := o.nonProwJobKubeconfig(inClusterCfg)
if err != nil {
return fmt.Errorf("failed to load config from %s: %w", o.NonProwJobKubeconfig, err)
}
releasesConfig, err := o.releasesKubeconfig(inClusterCfg)
if err != nil {
return fmt.Errorf("failed to load releases config from %s: %w", o.ReleasesKubeconfig, err)
}
toolsConfig, err := o.toolsKubeconfig(inClusterCfg)
if err != nil {
return fmt.Errorf("failed to load tools config from %s: %w", o.ToolsKubeconfig, err)
}
var mode string
switch {
case o.DryRun:
mode = "dry-run"
case len(o.AuditStorage) > 0:
mode = "audit"
case len(o.LimitSources) > 0:
mode = "manage"
default:
mode = "manage"
}
config.UserAgent = fmt.Sprintf("release-controller/%s (%s/%s) %s", version.Get().GitVersion, goruntime.GOOS, goruntime.GOARCH, mode)
releasesConfig.UserAgent = fmt.Sprintf("release-controller/%s (%s/%s) %s", version.Get().GitVersion, goruntime.GOOS, goruntime.GOARCH, mode)
toolsConfig.UserAgent = fmt.Sprintf("release-controller/%s (%s/%s) %s", version.Get().GitVersion, goruntime.GOOS, goruntime.GOARCH, mode)
client, err := clientset.NewForConfig(config)
if err != nil {
return fmt.Errorf("unable to create client: %v", err)
}
releasesClient, err := clientset.NewForConfig(releasesConfig)
if err != nil {
return fmt.Errorf("unable to create releases client: %v", err)
}
toolsClient, err := clientset.NewForConfig(toolsConfig)
if err != nil {
return fmt.Errorf("unable to create tools client: %v", err)
}
releaseNamespace := o.ReleaseNamespaces[0]
for _, ns := range o.ReleaseNamespaces {
if _, err := client.CoreV1().Namespaces().Get(context.TODO(), ns, metav1.GetOptions{}); err != nil {
return fmt.Errorf("unable to find release namespace: %s: %v", ns, err)
}
}
if o.JobNamespace != releaseNamespace {
if _, err := client.CoreV1().Namespaces().Get(context.TODO(), o.JobNamespace, metav1.GetOptions{}); err != nil {
return fmt.Errorf("unable to find job namespace: %v", err)
}
}
klog.Infof("%s releases will be sourced from the following namespaces: %s, and jobs will be run in %s", strings.Title(architecture), strings.Join(o.ReleaseNamespaces, " "), o.JobNamespace)
imageClient, err := imageclientset.NewForConfig(releasesConfig)
if err != nil {
return fmt.Errorf("unable to create image client: %v", err)
}
prowClient, err := o.prowJobClient(inClusterCfg)
if err != nil {
return fmt.Errorf("failed to create prowjob client: %v", err)
}
stopCh := wait.NeverStop
var hasSynced []cache.InformerSynced
batchFactory := informers.NewSharedInformerFactoryWithOptions(releasesClient, 10*time.Minute, informers.WithNamespace(o.JobNamespace))
jobs := batchFactory.Batch().V1().Jobs()
hasSynced = append(hasSynced, jobs.Informer().HasSynced)
configAgent := &prowconfig.Agent{}
if len(o.ProwConfigPath) > 0 {
if err := configAgent.Start(o.ProwConfigPath, o.JobConfigPath); err != nil {
return err
}
}
imageCache := newLatestImageCache(tagParts[0], tagParts[1])
execReleaseInfo := NewExecReleaseInfo(toolsClient, toolsConfig, o.JobNamespace, releaseNamespace, imageCache.Get)
releaseInfo := NewCachingReleaseInfo(execReleaseInfo, 64*1024*1024)
execReleaseFiles := NewExecReleaseFiles(toolsClient, toolsConfig, o.JobNamespace, releaseNamespace, releaseNamespace, imageCache.Get)
graph := NewUpgradeGraph(architecture)
c := NewController(
client.CoreV1(),
imageClient.ImageV1(),
releasesClient.BatchV1(),
jobs,
client.CoreV1(),
configAgent,
prowClient.Namespace(o.ProwNamespace),
o.JobNamespace,
o.ArtifactsHost,
releaseInfo,
graph,
o.softDeleteReleaseTags,
)
if o.VerifyBugzilla {
var tokens []string
// Append the path of bugzilla and github secrets.
if o.github.TokenPath != "" {
tokens = append(tokens, o.github.TokenPath)
}
if o.bugzilla.ApiKeyPath != "" {
tokens = append(tokens, o.bugzilla.ApiKeyPath)
}
secretAgent := &secret.Agent{}
if err := secretAgent.Start(tokens); err != nil {
return fmt.Errorf("Error starting secrets agent: %v", err)
}
ghClient, err := o.github.GitHubClient(secretAgent, false)
if err != nil {
return fmt.Errorf("Failed to create github client: %v", err)
}
ghClient.Throttle(o.githubThrottle, 0)
bzClient, err := o.bugzilla.BugzillaClient(secretAgent)
if err != nil {
return fmt.Errorf("Failed to create bugzilla client: %v", err)
}
pluginAgent := &plugins.ConfigAgent{}
if err := pluginAgent.Start(o.PluginConfig, false); err != nil {
return fmt.Errorf("Failed to create plugin agent: %v", err)
}
c.bugzillaVerifier = bugzilla.NewVerifier(bzClient, ghClient, pluginAgent.Config())
}
if len(o.AuditStorage) > 0 {
u, err := url.Parse(o.AuditStorage)
if err != nil {
return fmt.Errorf("--audit must be a valid file:// or gs:// URL: %v", err)
}
switch u.Scheme {
case "file":
path := u.Path
if !strings.HasSuffix(path, "/") {
path += "/"
}
store, err := NewFileAuditStore(path)
if err != nil {
return err
}
if err := store.Refresh(context.Background()); err != nil {
return err
}
c.auditStore = store
case "gs":
path := u.Path
if !strings.HasSuffix(path, "/") {
path += "/"
}
store, err := NewGCSAuditStore(u.Host, path, config.UserAgent, o.AuditGCSServiceAccount)
if err != nil {
return fmt.Errorf("unable to initialize audit store: %v", err)
}
if err := store.Refresh(context.Background()); err != nil {
return fmt.Errorf("unable to refresh audit store: %v", err)
}
c.auditStore = store
default:
return fmt.Errorf("--audit must be a valid file:// or gs:// URL")
}
}
if len(o.CLIImageForAudit) > 0 {
c.cliImageForAudit = o.CLIImageForAudit
}
if len(o.SigningKeyring) > 0 {
signer, err := signer.NewFromKeyring(o.SigningKeyring)
if err != nil {
return err
}
c.signer = signer
}
if len(o.ListenAddr) > 0 {
http.DefaultServeMux.Handle("/metrics", promhttp.Handler())
http.DefaultServeMux.HandleFunc("/graph", c.graphHandler)
http.DefaultServeMux.Handle("/", c.userInterfaceHandler())
go func() {
klog.Infof("Listening on %s for UI and metrics", o.ListenAddr)
if err := http.ListenAndServe(o.ListenAddr, nil); err != nil {
klog.Exitf("Server exited: %v", err)
}
}()
}
batchFactory.Start(stopCh)
// register the publish and release namespaces
publishNamespaces := sets.NewString(o.PublishNamespaces...)
for _, ns := range sets.NewString(o.ReleaseNamespaces...).Union(publishNamespaces).List() {
factory := imageinformers.NewSharedInformerFactoryWithOptions(imageClient, 10*time.Minute, imageinformers.WithNamespace(ns))
streams := factory.Image().V1().ImageStreams()
if publishNamespaces.Has(ns) {
c.AddPublishNamespace(ns, streams)
} else {
c.AddReleaseNamespace(ns, streams)
}
hasSynced = append(hasSynced, streams.Informer().HasSynced)
factory.Start(stopCh)
}
imageCache.SetLister(c.releaseLister.ImageStreams(releaseNamespace))
if len(o.ProwConfigPath) > 0 {
prowInformers := newDynamicSharedIndexInformer(prowClient, o.ProwNamespace, 10*time.Minute, labels.SelectorFromSet(labels.Set{"release.openshift.io/verify": "true"}))
hasSynced = append(hasSynced, prowInformers.HasSynced)
c.AddProwInformer(o.ProwNamespace, prowInformers)
go prowInformers.Run(stopCh)
go func() {
index := prowInformers.GetIndexer()
cache.WaitForCacheSync(stopCh, prowInformers.HasSynced)
wait.Until(func() {
for _, item := range index.List() {
job, ok := item.(*unstructured.Unstructured)
if !ok {
continue
}
annotations := job.GetAnnotations()
from, ok := annotations[releaseAnnotationFromTag]
if !ok {
continue
}
to, ok := annotations[releaseAnnotationToTag]
if !ok {
continue
}
jobArchitecture, ok := annotations[releaseAnnotationArchitecture]
if !ok {
continue
}
if jobArchitecture != architecture {
continue
}
status, ok := prowJobVerificationStatus(job)
if !ok {
continue
}
graph.Add(from, to, UpgradeResult{
State: status.State,
URL: status.URL,
})
}
}, 2*time.Minute, stopCh)
}()
if !o.DryRun {
go c.syncPeriodicJobs(prowInformers, stopCh)
}
}
klog.Infof("Waiting for caches to sync")
cache.WaitForCacheSync(stopCh, hasSynced...)
switch {
case o.DryRun:
klog.Infof("Dry run mode (no changes will be made)")
// read the graph
go syncGraphToSecret(graph, false, releasesClient.CoreV1().Secrets(releaseNamespace), releaseNamespace, "release-upgrade-graph", stopCh)
<-stopCh
return nil
case len(o.AuditStorage) > 0:
klog.Infof("Auditing releases to %s", o.AuditStorage)
// read the graph
go syncGraphToSecret(graph, false, releasesClient.CoreV1().Secrets(releaseNamespace), releaseNamespace, "release-upgrade-graph", stopCh)
c.RunAudit(4, stopCh)
return nil
case len(o.LimitSources) > 0:
klog.Infof("Managing only %s, no garbage collection", o.LimitSources)
// read the graph
go syncGraphToSecret(graph, false, releasesClient.CoreV1().Secrets(releaseNamespace), releaseNamespace, "release-upgrade-graph", stopCh)
c.RunSync(3, stopCh)
return nil
default:
klog.Infof("Managing releases")
// keep the graph in a more persistent form
go syncGraphToSecret(graph, true, releasesClient.CoreV1().Secrets(releaseNamespace), releaseNamespace, "release-upgrade-graph", stopCh)
// maintain the release pods
go refreshReleaseToolsEvery(2*time.Hour, execReleaseInfo, execReleaseFiles, stopCh)
c.RunSync(3, stopCh)
return nil
}
}
func (o *options) prowJobClient(cfg *rest.Config) (dynamic.NamespaceableResourceInterface, error) {
if o.ProwJobKubeconfig != "" {
var err error
cfg, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: o.ProwJobKubeconfig},
&clientcmd.ConfigOverrides{},
).ClientConfig()
if err != nil {
return nil, fmt.Errorf("failed to load prowjob kubeconfig from path %q: %v", o.ProwJobKubeconfig, err)
}
}
dynamicClient, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, fmt.Errorf("unable to create prow client: %v", err)
}
return dynamicClient.Resource(schema.GroupVersionResource{Group: "prow.k8s.io", Version: "v1", Resource: "prowjobs"}), nil
}
func (o *options) nonProwJobKubeconfig(inClusterCfg *rest.Config) (*rest.Config, error) {
if o.NonProwJobKubeconfig == "" {
return inClusterCfg, nil
}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: o.NonProwJobKubeconfig},
&clientcmd.ConfigOverrides{},
).ClientConfig()
}
func (o *options) releasesKubeconfig(inClusterCfg *rest.Config) (*rest.Config, error) {
if o.ReleasesKubeconfig == "" {
return o.nonProwJobKubeconfig(inClusterCfg)
}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: o.ReleasesKubeconfig},
&clientcmd.ConfigOverrides{},
).ClientConfig()
}
func (o *options) toolsKubeconfig(inClusterCfg *rest.Config) (*rest.Config, error) {
if o.ToolsKubeconfig == "" {
return o.nonProwJobKubeconfig(inClusterCfg)
}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: o.ToolsKubeconfig},
&clientcmd.ConfigOverrides{},
).ClientConfig()
}
// loadClusterConfig loads connection configuration
// for the cluster we're deploying to. We prefer to
// use in-cluster configuration if possible, but will
// fall back to using default rules otherwise.
func loadClusterConfig() (*rest.Config, error) {
cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
clusterConfig, err := cfg.ClientConfig()
if err != nil {
return nil, fmt.Errorf("could not load client configuration: %v", err)
}
return clusterConfig, nil
}
func newDynamicSharedIndexInformer(client dynamic.NamespaceableResourceInterface, namespace string, resyncPeriod time.Duration, selector labels.Selector) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = selector.String()
return client.Namespace(namespace).List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = selector.String()
return client.Namespace(namespace).Watch(context.TODO(), options)
},
},
&unstructured.Unstructured{},
resyncPeriod,
cache.Indexers{},
)
}
// latestImageCache tries to find the first valid tag matching
// the requested image stream with the matching name (or the first
// one when looking across all lexigraphically).
type latestImageCache struct {
imageStream string
tag string
interval time.Duration
cache *lru.Cache
lock sync.Mutex
lister imagelisters.ImageStreamNamespaceLister
last string
lastChecked time.Time
}
func newLatestImageCache(imageStream string, tag string) *latestImageCache {
cache, _ := lru.New(64)
return &latestImageCache{
imageStream: imageStream,
tag: tag,
interval: 10 * time.Minute,
cache: cache,
}
}
func (c *latestImageCache) SetLister(lister imagelisters.ImageStreamNamespaceLister) {
c.lock.Lock()
defer c.lock.Unlock()
c.lister = lister
}
func (c *latestImageCache) Get() (string, error) {
c.lock.Lock()
defer c.lock.Unlock()
if c.lister == nil {
return "", fmt.Errorf("not yet started")
}
if len(c.last) > 0 && c.lastChecked.After(time.Now().Add(-c.interval)) {
return c.last, nil
}
// Find the first image stream matching the desired stream name name, or the first
// one that isn't a stable image stream and has the requested tag. Stable image
// streams
var preferred *imagev1.ImageStream
items, _ := c.lister.List(labels.Everything())
sort.Slice(items, func(i, j int) bool { return items[i].Name < items[j].Name })
for _, item := range items {
if len(c.imageStream) > 0 {
if c.imageStream == item.Name {
preferred = item
break
}
continue
}
value, ok := item.Annotations[releaseAnnotationConfig]
if !ok {
continue
}
if spec := findImagePullSpec(item, c.tag); len(spec) == 0 {
continue
}
config, err := parseReleaseConfig(value, c.cache)
if err != nil {
continue
}
if config.As == releaseConfigModeStable {
continue
}
if preferred == nil {
preferred = item
continue
}
if len(c.imageStream) > 0 && c.imageStream == item.Name {
preferred = item
break
}
}
if preferred != nil {
if spec := findImagePullSpec(preferred, c.tag); len(spec) > 0 {
c.last = spec
c.lastChecked = time.Now()
klog.V(4).Infof("Resolved %s:%s to %s", c.imageStream, c.tag, spec)
return spec, nil
}
}
return "", fmt.Errorf("could not find a release image stream with :%s (tools=%s)", c.tag, c.imageStream)
}
func refreshReleaseToolsEvery(interval time.Duration, execReleaseInfo *ExecReleaseInfo, execReleaseFiles *ExecReleaseFiles, stopCh <-chan struct{}) {
wait.Until(func() {
err := wait.ExponentialBackoff(wait.Backoff{
Steps: 3,
Duration: 1 * time.Second,
Factor: 2,
}, func() (bool, error) {
success := true
if err := execReleaseInfo.refreshPod(); err != nil {
klog.Errorf("Unable to refresh git cache, waiting to retry: %v", err)
success = false
}
if err := execReleaseFiles.refreshPod(); err != nil {
klog.Errorf("Unable to refresh files cache, waiting to retry: %v", err)
success = false
}
return success, nil
})
if err != nil {
klog.Errorf("Unable to refresh git cache, waiting until next sync time")
}
}, interval, stopCh)
}
func setupKubeconfigWatches(o *options) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("failed to set up watcher: %w", err)
}
for _, candidate := range []string{o.ProwJobKubeconfig, o.NonProwJobKubeconfig, "/var/run/secrets/kubernetes.io/serviceaccount/token"} {
if _, err := os.Stat(candidate); err != nil {
continue
}
if err := watcher.Add(candidate); err != nil {
return fmt.Errorf("failed to watch %s: %w", candidate, err)
}
}
go func() {
for e := range watcher.Events {
if e.Op == fsnotify.Chmod {
// For some reason we get frequent chmod events from Openshift
continue
}
klog.Infof("event: %s, kubeconfig changed, exiting to make the kubelet restart us so we can pick them up", e.String())
interrupts.Terminate()
}
}()
return nil
}
|
[
"\"OPENSHIFT_PROFILE\""
] |
[] |
[
"OPENSHIFT_PROFILE"
] |
[]
|
["OPENSHIFT_PROFILE"]
|
go
| 1 | 0 | |
ilkbyte/client.py
|
import logging
import os
from typing import Dict
from ilkbyte.exception import ConfigurationError
from ilkbyte.session import IlkbyteAPISession
from ilkbyte.utils import PowerAction, DNSRecordType
logger = logging.getLogger(__name__)
class Ilkbyte(object):
def __init__(self, host: str = None, secret_key: str = None, access_key: str = None):
"""
Ilkbyte API client.
Args:
host (str): Hostname of the ilkbyte api.
secret_key (str): Secret key.
access_key (str): Access key.
"""
if not host:
host = os.getenv('ILKBYTE_HOST')
if not host:
logger.error("hostname variable or ILKBYTE_HOST environment variable is required!")
raise ConfigurationError()
if not secret_key:
secret_key = os.getenv('ILKBYTE_SECRET_KEY')
if not secret_key:
logger.error("secret_key variable or ILKBYTE_SECRET_KEY environment variable is required!")
raise ConfigurationError()
if not access_key:
access_key = os.getenv('ILKBYTE_ACCESS_KEY')
if not access_key:
logger.error("access_key variable or ILKBYTE_ACCESS_KEY environment variable is required!")
raise ConfigurationError()
self._session = IlkbyteAPISession(host, secret_key, access_key)
def get_account(self) -> Dict:
response = self._session.get_resource('account')
response.raise_for_status()
return response.json()
def get_users(self) -> Dict:
response = self._session.get_resource('account/users')
response.raise_for_status()
return response.json()
def get_all_servers(self, page_number: int = 1):
response = self._session.get_resource('server/list/all', params={
'p': page_number
})
response.raise_for_status()
return response.json()
def get_active_servers(self, page_number: int = 1):
response = self._session.get_resource('server/list', params={
'p': page_number
})
response.raise_for_status()
return response.json()
def get_plans(self, page_number: int = 1):
response = self._session.get_resource('server/create')
response.raise_for_status()
return response.json()
def create_server(self, username, name, os_id, app_id, package_id, sshkey, password=None):
params = {
'username': username,
'name': name,
'os_id': os_id,
'app_id': app_id,
'package_id': package_id,
'sshkey': sshkey,
}
if not password:
params['password'] = password
response = self._session.get_resource('server/create/config', params=params)
response.raise_for_status()
return response.json()
def get_server(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/show")
response.raise_for_status()
return response.json()
def set_power(self, server_name: str, action: PowerAction):
response = self._session.get_resource(f"server/manage/{server_name}/power", params={
'set': action.value
})
response.raise_for_status()
return response.json()
def get_ips(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/ip/list")
response.raise_for_status()
return response.json()
def get_ip_logs(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/ip/logs")
response.raise_for_status()
return response.json()
def get_ip_rdns(self, server_name: str, ip: str, rdns: str):
response = self._session.get_resource(f"server/manage/{server_name}/ip/rdns", params={
'ip': ip,
'rdns': rdns
})
response.raise_for_status()
return response.json()
def get_snapshots(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot")
response.raise_for_status()
return response.json()
def create_snapshot(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/create")
response.raise_for_status()
return response.json()
def restore_snapshot(self, server_name: str, snapshot_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/revert", params={
'name': snapshot_name
})
response.raise_for_status()
return response.json()
def update_snapshot(self, server_name: str, snapshot_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/update", params={
'name': snapshot_name
})
response.raise_for_status()
return response.json()
def delete_snapshot(self, server_name: str, snapshot_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/delete", params={
'name': snapshot_name
})
response.raise_for_status()
return response.json()
def set_cron(self, server_name: str, cron_name: str, day: int, hour: int, min: int):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/cron/add", params={
'name': cron_name,
'day': day,
'hour': hour,
'min': min
})
response.raise_for_status()
return response.json()
def delete_cron(self, server_name: str, cron_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/snapshot/cron/delete", params={
'name': cron_name
})
response.raise_for_status()
return response.json()
def get_backups(self, server_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/backup")
response.raise_for_status()
return response.json()
def restore_backup(self, server_name: str, backup_name: str):
response = self._session.get_resource(f"server/manage/{server_name}/backup/restore", params={
'backup_name': backup_name
})
response.raise_for_status()
return response.json()
def get_domains(self, p: int = 1):
response = self._session.get_resource("domain/list", params={
'p': p
})
response.raise_for_status()
return response.json()
def create_domain(self, domain: str, server: str, ipv6: bool):
response = self._session.get_resource("domain/create", params={
'domain': domain,
'server': server,
'ipv6': ipv6
})
response.raise_for_status()
return response.json()
def get_domain(self, domain_name: str):
response = self._session.get_resource(f"domain/manage/{domain_name}/show")
response.raise_for_status()
return response.json()
def add_dns_record(self, domain_name: str, record_name: str, record_type: DNSRecordType, record_content: str,
record_priority: int):
response = self._session.get_resource(f"domain/manage/{domain_name}/add", params={
'record_name': record_name,
'record_type': record_type.value,
'record_content': record_content,
'record_priority': record_priority
})
response.raise_for_status()
return response.json()
def update_dns_record(self, domain_name: str, record_id: int, record_content: str, record_priority: int):
response = self._session.get_resource(f"domain/manage/{domain_name}/update", params={
'record_id': record_id,
'record_content': record_content,
'record_priority': record_priority
})
response.raise_for_status()
return response.json()
def delete_dns_record(self, domain_name: str, record_id: int):
response = self._session.get_resource(f"domain/manage/{domain_name}/delete", params={
'record_id': record_id
})
response.raise_for_status()
return response.json()
def dns_push(self, domain_name: str):
response = self._session.get_resource(f"domain/manage/{domain_name}/push")
response.raise_for_status()
return response.json()
|
[] |
[] |
[
"ILKBYTE_HOST",
"ILKBYTE_SECRET_KEY",
"ILKBYTE_ACCESS_KEY"
] |
[]
|
["ILKBYTE_HOST", "ILKBYTE_SECRET_KEY", "ILKBYTE_ACCESS_KEY"]
|
python
| 3 | 0 | |
pkg/processor/build/runtime/python/test/python_test.go
|
// +build test_integration
// +build test_local
/*
Copyright 2017 The Nuclio 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 test
import (
"fmt"
"net/http"
"testing"
"github.com/nuclio/nuclio/pkg/platform"
"github.com/nuclio/nuclio/pkg/processor/build/runtime/test/suite"
"github.com/nuclio/nuclio/pkg/processor/trigger/http/test/suite"
"github.com/nuclio/nuclio/pkg/runtimeconfig"
"github.com/nuclio/errors"
"github.com/stretchr/testify/suite"
)
type TestSuite struct {
buildsuite.TestSuite
runtime string
}
func (suite *TestSuite) SetupSuite() {
suite.TestSuite.SetupSuite()
suite.TestSuite.RuntimeSuite = suite
suite.TestSuite.ArchivePattern = "python"
suite.Runtime = suite.runtime
}
func (suite *TestSuite) TestBuildWithBuildArgs() {
createFunctionOptions := suite.GetDeployOptions("func-with-build-args",
suite.GetFunctionPath(suite.GetTestFunctionsDir(), "common", "empty", "python"))
createFunctionOptions.FunctionConfig.Spec.Handler = "empty:handler"
// Configure custom pypi repository
pypiRepositoryURL := "https://test.pypi.org/simple"
runtimePlatformConfigurationCopy := suite.PlatformConfiguration.Runtime
suite.PlatformConfiguration.Runtime = &runtimeconfig.Config{
Python: &runtimeconfig.Python{
BuildArgs: map[string]string{
"PIP_INDEX_URL": pypiRepositoryURL,
},
},
}
defer func() {
// HACK - reset runtime platform configuration
// to avoid platform configuration effecting following tests
// NOTE: on >= 1.6.0 platform configuration would be re-initiated per test case and not per suite.
suite.PlatformConfiguration.Runtime = runtimePlatformConfigurationCopy
}()
// Try to deploy some non-existing package.
// The deployment will fail but if custom PyPI configuration is successful
// we should see "Looking in indexes: XXX" message in the logs
createFunctionOptions.FunctionConfig.Spec.Build.Commands = []string{"pip install non-existing-package"}
suite.PopulateDeployOptions(createFunctionOptions)
_, err := suite.Platform.CreateFunction(createFunctionOptions)
suite.Assert().NotNil(err)
// delete leftovers
defer suite.Platform.DeleteFunction(&platform.DeleteFunctionOptions{ // nolint: errcheck
FunctionConfig: createFunctionOptions.FunctionConfig,
})
stackTrace := errors.GetErrorStackString(err, 10)
suite.Assert().Contains(stackTrace, fmt.Sprintf("Looking in indexes: %s", pypiRepositoryURL))
}
func (suite *TestSuite) TestBuildWithBuildArgsExtended() {
createFunctionOptions := suite.GetDeployOptions("func-with-build-args-extended",
suite.GetFunctionPath(suite.GetTestFunctionsDir(), "common", "empty", "python"))
createFunctionOptions.FunctionConfig.Spec.Handler = "empty:handler"
createFunctionOptions.FunctionConfig.Spec.Build.Commands = []string{"pip install adbuzdugan"}
// Create a copy of function options since it's modified during deployment
createFunctionOptionsOriginal := *createFunctionOptions
// Sanity, verify deployment attempt without custom pypi repository fails
suite.DeployFunctionAndExpectError(createFunctionOptions, "Failed to deploy function")
// Configure custom pypi repository and re-deploy (should succeed)
runtimePlatformConfigurationCopy := suite.PlatformConfiguration.Runtime
suite.PlatformConfiguration.Runtime = &runtimeconfig.Config{
Python: &runtimeconfig.Python{
BuildArgs: map[string]string{
"PIP_INDEX_URL": "https://test.pypi.org/simple",
},
},
}
defer func() {
// HACK - reset runtime platform configuration
// to avoid platform configuration effecting following tests
// NOTE: on >= 1.6.0 platform configuration would be re-initiated per test case and not per suite.
suite.PlatformConfiguration.Runtime = runtimePlatformConfigurationCopy
}()
expectedStatusCode := http.StatusOK
suite.DeployFunctionAndRequest(&createFunctionOptionsOriginal,
&httpsuite.Request{
RequestMethod: "POST",
ExpectedResponseStatusCode: &expectedStatusCode,
})
}
func (suite *TestSuite) GetFunctionInfo(functionName string) buildsuite.FunctionInfo {
functionInfo := buildsuite.FunctionInfo{
Runtime: suite.runtime,
}
switch functionName {
case "reverser":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "reverser", "python", "reverser.py"}
functionInfo.Handler = "reverser:handler"
case "json-parser-with-function-config":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "json-parser-with-function-config", "python"}
case "json-parser-with-inline-function-config":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "json-parser-with-inline-function-config", "python", "parser.py"}
case "invalid-inline-config":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "invalid-inline-config", "python", "parser.py"}
case "long-initialization":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "long-initialization", "python", "sleepy.py"}
case "context-init-fail":
functionInfo.Path = []string{suite.GetTestFunctionsDir(), "common", "context-init-fail", "python", "contextinitfail.py"}
default:
suite.Logger.InfoWith("Test skipped", "functionName", functionName)
functionInfo.Skip = true
}
return functionInfo
}
func TestIntegrationSuite(t *testing.T) {
if testing.Short() {
return
}
for _, testCase := range []struct {
runtimeName string
}{
{runtimeName: "python:3.6"},
{runtimeName: "python:3.7"},
{runtimeName: "python:3.8"},
{runtimeName: "python:3.9"},
} {
t.Run(testCase.runtimeName, func(t *testing.T) {
testSuite := new(TestSuite)
testSuite.runtime = testCase.runtimeName
suite.Run(t, testSuite)
})
}
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
utils/CONSTANTS.py
|
import requests, os, re
from dotenv import load_dotenv
from utils.helpers import *
load_dotenv()
def load_constants(self):
self.TOKEN = os.environ.get("TOKEN")
self.REDDITID = os.environ.get("REDDITID")
self.REDDITSECRET = os.environ.get("REDDITSECRET")
self.USERAGENT = os.environ.get("USERAGENT")
self.MONGOURI = os.environ.get("MONGOURI")
self.TOPGG = os.environ.get("TOPGG")
self.TOPGGAUTH = os.environ.get("TOPGGAUTH")
self.ISLIVE = os.environ.get("ISLIVE") == "True"
self.PORT = os.environ.get("PORT", 5000)
self.URBANDICTKEY = os.environ.get("URBANDICTKEY")
self.URBANDICTHOST = os.environ.get("URBANDICTHOST")
self.DISCORDSUBHUB = os.environ.get("DISCORDSUBHUB")
self.BADWORDS = [
badword.strip("\n")
for badword in open(f"data/profanity.txt", "r", encoding="utf-8").readlines()
]
self.RANDOMWORDS = requests.get(
"https://raw.githubusercontent.com/sindresorhus/mnemonic-words/master/words.json"
).json()
self.RANDOMEMOJIS = [
"😳",
"😭",
"🤗",
"😴",
"😪",
"🤡",
"💩",
"👽",
"😋",
"👍",
"👎",
"👏",
"👑",
"🦋",
"🐸",
"🐝",
"🐍",
"🐄",
"🦧",
"🐄",
"🐈",
"🍄",
"💐",
"🌈",
"✨",
"❄️",
"🍆",
"🍑",
"🍒",
"🥑",
"🌽",
"🥐",
"🧀",
"🥞",
"🌭",
"🍭",
"🍰",
"🍺",
"🧂",
"⚽",
"🚀",
"✈️",
"🗿",
"🌋",
"☎️",
"💎",
"🔪",
"🦠",
"💉",
"🛀",
"🎁",
"🎈",
"🧮",
"📝",
"❤️",
"🆘",
"❌",
"💯",
"🔞",
"🆒",
"🎶",
]
self.CDN_URL = "https://cdn.hamood.app"
self.URL = "https://hamood.app"
def add_regexes(self):
self.re_validChannel = re.compile(
r"^(?:https?:)?\/\/?(?:www|m)\.?(?:youtube\.com|youtu.be)\/(?:[\w\-]+\?v=|embed\/|v\/)?([\w\-]+)/(\S+)?$"
)
self.re_getID_backup = re.compile(
r"<link rel=\"alternate\" type=\"application/rss\+xml\" title=\"RSS\" href=\"https://www\.youtube\.com/feeds/videos\.xml\?channel_id=(\S+)?\">"
)
self.re_YoutubeID = re.compile(
r"<meta property=\"og:url\" content=\"https://www\.youtube\.com/channel/(\S+)?\">"
)
self.re_YoutubeImage = re.compile(
r"<meta property=\"og:image\" content=\"(\S+)?\">"
)
self.re_YoutubeName = re.compile(r"<meta property=\"og:title\" content=\"(\S+)?\">")
self.re_RedditUrl = re.compile(
r"reddit\.com\/(?:r|u|user)\/\S{2,}\/comments\/([0-9a-z]+)"
)
self.re_ValidImageUrl = re.compile(
r"(https?:(?:(?!tenor|giphy|imgur)[/|.|\w|\s|-])*\.(?:jpg|gif|png))"
)
self.re_member = re.compile(r"(<@!?\d+>)")
self.re_emoji = re.compile(r"(<a?:\w+:?\d+>)")
self.re_role = re.compile(r"(<@&\d+>)")
self.re_channel = re.compile(r"(<#\d+>)")
def add_helpers(self):
self.pretty_dt = pretty_dt
self.quick_embed = quick_embed
self.pastel_color = pastel_color
self.flatten = flatten
self.named_flatten = named_flatten
class ANSI:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
BLUE = "\u001b[34m"
ORANGE = "\033[48:5:208:0m%s\033[m"
DORANGE = "\033[48:5:166:0m%s\033[m\n"
HAMOOD = """
██╗ ██╗ █████╗ ███╗ ███╗ ██████╗ ██████╗ ██████╗
██║ ██║██╔══██╗████╗ ████║██╔═══██╗██╔═══██╗██╔══██╗
███████║███████║██╔████╔██║██║ ██║██║ ██║██║ ██║
██╔══██║██╔══██║██║╚██╔╝██║██║ ██║██║ ██║██║ ██║
██║ ██║██║ ██║██║ ╚═╝ ██║╚██████╔╝╚██████╔╝██████╔╝
╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝"""
|
[] |
[] |
[
"ISLIVE",
"PORT",
"REDDITSECRET",
"USERAGENT",
"REDDITID",
"TOKEN",
"DISCORDSUBHUB",
"MONGOURI",
"TOPGG",
"URBANDICTHOST",
"URBANDICTKEY",
"TOPGGAUTH"
] |
[]
|
["ISLIVE", "PORT", "REDDITSECRET", "USERAGENT", "REDDITID", "TOKEN", "DISCORDSUBHUB", "MONGOURI", "TOPGG", "URBANDICTHOST", "URBANDICTKEY", "TOPGGAUTH"]
|
python
| 12 | 0 | |
python/fastapi/main.py
|
from typing import Dict, Optional, List, TypeVar
from fastapi import FastAPI, status, HTTPException
from todo import Todo, TodoKey, TodoValue
from id_generator import IdGenerator, Id
from json_types import JsonObject, JsonList
# Used to generate unique Ids for our `todos` dict keys
id_gen = IdGenerator()
todos: Dict[Id, Todo] = {}
app = FastAPI()
@app.get('/todos')
def index() -> JsonList[Todo]:
return list(todos.values())
@app.get('/todos/{item_id}')
def show(item_id: Id) -> JsonObject[Optional[Todo]]:
return { 'item': todos.get(item_id, None) }
@app.post('/todos', status_code=status.HTTP_201_CREATED)
def create(entry: dict) -> JsonObject[int]:
if 'description' not in entry or 'category' not in entry:
raise HTTPException(status_code=400, detail='JSON missing "description" or "category" field')
new_id: Id = id_gen.next()
todos[new_id] = Todo(entry['description'], entry['category'], new_id)
return { 'id': new_id }
@app.delete('/todos/{item_id}')
def delete(item_id: int) -> JsonObject[bool]:
delete_result: bool = todos.pop(item_id, None) is not None
return { "operation_succeeded": delete_result }
@app.put('/todos', status_code=status.HTTP_202_ACCEPTED)
def update(entry: dict):
if 'id' not in entry or 'todo' not in entry:
raise HTTPException(status_code=400, detail='JSON missing "id" or "todo" field')
if entry['id'] not in todos:
raise HTTPException(status_code=404, detail=f'Todo resource by id {entry["id"]} not found')
del entry['id']
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
class8/jnpr_devices.py
|
#!/usr/bin/env python
from getpass import getpass
import os
password = os.getenv("PYPLUS_PASS") if os.getenv("PYPLUS_PASS") else getpass()
srx2 = {
"host": "srx2.lasthop.io",
"user": "pyclass",
"password": password
}
|
[] |
[] |
[
"PYPLUS_PASS"
] |
[]
|
["PYPLUS_PASS"]
|
python
| 1 | 0 | |
src/xml_processing/code/lib/xml_to_json.py
|
"""
xml_to_json
===========
module that converts XMLs to JSON files
"""
import json
import urllib.request
import re
import os
import logging
import hashlib
import click
import coloredlogs
import sys
# from dotenv import load_dotenv
#
# load_dotenv()
# pipenv run python xml_to_json.py -f /home/azurebrd/git/agr_literature_service_demo/src/xml_processing/inputs/sample_set
#
# 22 minutes on dev.wormbase for 646727 documents from filesystem. 12G of xml to 6.0G of json
# 1 hour 55 minutes on agr-literature-dev for 649074 documents from filesystem. 15G of xml to 8.0G of json
# pipenv run python xml_to_json.py -u "http://tazendra.caltech.edu/~azurebrd/cgi-bin/forms/generic.cgi?action=ListPmids"
# not using author firstinit, nlm, issn
# update sample
# cp pubmed_json/32542232.json pubmed_sample
# cp pubmed_json/32644453.json pubmed_sample
# cp pubmed_json/33408224.json pubmed_sample
# cp pubmed_json/33002525.json pubmed_sample
# cp pubmed_json/33440160.json pubmed_sample
# cp pubmed_json/33410237.json pubmed_sample
# git add pubmed_sample/32542232.json
# git add pubmed_sample/32644453.json
# git add pubmed_sample/33408224.json
# git add pubmed_sample/33002525.json
# git add pubmed_sample/33440160.json
# git add pubmed_sample/33410237.json
# https://ftp.ncbi.nih.gov/pubmed/J_Medline.txt
# Processing CommentIn/CommentOn from commentsCorrections results in 12-deep recursive chain of PMID comments, e.g. 32919857, but also many others fairly deep.
# Removing CommentIn/CommentOn from allowed RefType values the deepest set is 4 deep, Recursive example 26757732 -> 26868856 -> 26582243 -> 26865040 -> 27032729
# Need to set up a queue that queries postgres to get a list of pubmed id that don't have a pubmed final flag
# Need to set up flags to take in pmids from postgres queue, file in filesystem, file in URL, list from command line
# to get set of pmids with search term 'elegans'
# https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=elegans&retmax=100000000
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG')
known_article_id_types = {
'pubmed': {'prefix': 'PMID:'},
'doi': {'prefix': 'DOI:'},
'pmc': {'prefix': 'PMCID:'}}
# 'pubmed': {'pages': 'PubMed', 'prefix': 'PMID:'},
# 'doi': {'pages': 'DOI', 'prefix': 'DOI:'},
# 'pmc': {'pages': 'PMC', 'prefix': 'PMCID:'}}
ignore_article_id_types = {'bookaccession', 'mid', 'pii', 'pmcid'}
unknown_article_id_types = set([])
def represents_int(s):
"""
:param s:
:return:
"""
try:
int(s)
return True
except ValueError:
return False
def month_name_to_number_string(string):
"""
:param string:
:return:
"""
m = {
'jan': '01',
'feb': '02',
'mar': '03',
'apr': '04',
'may': '05',
'jun': '06',
'jul': '07',
'aug': '08',
'sep': '09',
'oct': '10',
'nov': '11',
'dec': '12'}
s = string.strip()[:3].lower()
try:
out = m[s]
return out
except ValueError:
raise ValueError(string + ' is not a month')
def get_year_month_day_from_xml_date(pub_date):
"""
:param pub_date:
:return:
"""
date_list = []
year = ''
month = '01'
day = '01'
year_re_output = re.search("<Year>(.+?)</Year>", pub_date)
if year_re_output is not None:
year = year_re_output.group(1)
month_re_output = re.search("<Month>(.+?)</Month>", pub_date)
if month_re_output is not None:
month_text = month_re_output.group(1)
if represents_int(month_text):
month = month_text
else:
month = month_name_to_number_string(month_text)
day_re_output = re.search("<Day>(.+?)</Day>", pub_date)
if day_re_output is not None:
day = day_re_output.group(1)
date_list.append(year)
date_list.append(month)
date_list.append(day)
return date_list
def get_medline_date_from_xml_date(pub_date):
"""
:param pub_date:
:return:
"""
medline_re_output = re.search('<MedlineDate>(.+?)</MedlineDate>', pub_date)
if medline_re_output is not None:
return medline_re_output.group(1)
def generate_json(pmids, previous_pmids, base_path): # noqa: C901
"""
:param pmids:
:param previous_pmids:
:return:
"""
# open input xml file and read data in form of python dictionary using xmltodict module
md5data = ''
# storage_path = base_path + 'pubmed_xml_20210322/'
# json_storage_path = base_path + 'pubmed_json_20210322/'
storage_path = base_path + 'pubmed_xml/'
json_storage_path = base_path + 'pubmed_json/'
if not os.path.exists(storage_path):
os.makedirs(storage_path)
if not os.path.exists(json_storage_path):
os.makedirs(json_storage_path)
# new_pmids = []
# ref_types = []
new_pmids_set = set([])
ref_types_set = set([])
for pmid in pmids:
filename = storage_path + pmid + '.xml'
# if getting pmids from directories split into multiple sub-subdirectories
# filename = get_path_from_pmid(pmid, 'xml')
if not os.path.exists(filename):
continue
# logger.info("processing %s", filename)
with open(filename) as xml_file:
xml = xml_file.read()
# print (xml)
# xmltodict is treating html markup like <i>text</i> as xml,
# which is creating mistaken structure in the conversion.
# may be better to parse full xml instead.
# data_dict = xmltodict.parse(xml_file.read())
xml_file.close()
# print (pmid)
data_dict = {}
# e.g. 21290765 has BookDocument and ArticleTitle
book_re_output = re.search('<BookDocument>', xml)
if book_re_output is not None:
data_dict['is_book'] = 'book'
title_re_output = re.search('<ArticleTitle[^>]*?>(.+?)</ArticleTitle>', xml, re.DOTALL)
if title_re_output is not None:
# print title
title = title_re_output.group(1).rstrip()
title = re.sub(r'\s+', ' ', title)
data_dict['title'] = title
if 'is_book' not in data_dict:
data_dict['is_journal'] = 'journal'
else:
# e.g. 33054145 21413221
book_title_re_output = re.search('<BookTitle[^>]*?>(.+?)</BookTitle>', xml, re.DOTALL)
if book_title_re_output is not None:
# print title
title = book_title_re_output.group(1).rstrip()
title = re.sub(r'\s+', ' ', title)
data_dict['title'] = title
data_dict['is_book'] = 'book'
else:
# e.g. 28304499 28308877
vernacular_title_re_output = re.search('<VernacularTitle[^>]*?>(.+?)</VernacularTitle>', xml, re.DOTALL)
if vernacular_title_re_output is not None:
# print title
title = vernacular_title_re_output.group(1).rstrip()
title = re.sub(r'\s+', ' ', title)
data_dict['title'] = title
data_dict['is_vernacular'] = 'vernacular'
else:
logger.info("%s has no title", pmid)
journal_re_output = re.search('<MedlineTA>(.+?)</MedlineTA>', xml)
if journal_re_output is not None:
data_dict['journal'] = journal_re_output.group(1)
pages_re_output = re.search('<MedlinePgn>(.+?)</MedlinePgn>', xml)
if pages_re_output is not None:
data_dict['pages'] = pages_re_output.group(1)
volume_re_output = re.search('<Volume>(.+?)</Volume>', xml)
if volume_re_output is not None:
data_dict['volume'] = volume_re_output.group(1)
issue_re_output = re.search('<Issue>(.+?)</Issue>', xml)
if issue_re_output is not None:
data_dict['issueName'] = issue_re_output.group(1)
pubstatus_re_output = re.search('<PublicationStatus>(.+?)</PublicationStatus>', xml)
if pubstatus_re_output is not None:
# print pubstatus
data_dict['publicationStatus'] = pubstatus_re_output.group(1)
if re.findall('<PublicationType>(.+?)</PublicationType>', xml):
types_group = re.findall('<PublicationType>(.+?)</PublicationType>', xml)
data_dict['pubMedType'] = types_group
elif re.findall('<PublicationType UI=\".*?\">(.+?)</PublicationType>', xml):
types_group = re.findall('<PublicationType UI=\".*?\">(.+?)</PublicationType>', xml)
data_dict['pubMedType'] = types_group
# <CommentsCorrectionsList><CommentsCorrections RefType="CommentIn"><RefSource>Mult Scler.
# 1999 Dec;5(6):378</RefSource><PMID Version="1">10644162</PMID></CommentsCorrections><CommentsCorrections
# RefType="CommentIn"><RefSource>Mult Scler. 2000 Aug;6(4):291-2</RefSource><PMID Version="1">10962551</PMID>
# </CommentsCorrections></CommentsCorrectionsList>
comments_corrections_group = re.findall('<CommentsCorrections (.+?)</CommentsCorrections>', xml, re.DOTALL)
if len(comments_corrections_group) > 0:
data_dict['commentsCorrections'] = dict()
for comcor_xml in comments_corrections_group:
ref_type = ''
other_pmid = ''
ref_type_re_output = re.search("RefType=\"(.*?)\"", comcor_xml)
if ref_type_re_output is not None:
ref_type = ref_type_re_output.group(1)
other_pmid_re_output = re.search("<PMID[^>]*?>(.+?)</PMID>", comcor_xml)
if other_pmid_re_output is not None:
other_pmid = other_pmid_re_output.group(1)
if (other_pmid != '') and (ref_type != '') and (ref_type != 'CommentIn') \
and (ref_type != 'CommentOn'):
if ref_type in data_dict['commentsCorrections']:
if other_pmid not in data_dict['commentsCorrections'][ref_type]:
data_dict['commentsCorrections'][ref_type].append(other_pmid)
else:
data_dict['commentsCorrections'][ref_type] = []
data_dict['commentsCorrections'][ref_type].append(other_pmid)
# print(pmid + " COMCOR " + ref_type + " " + other_pmid)
ref_types_set.add(ref_type)
if other_pmid not in pmids and other_pmid not in previous_pmids:
new_pmids_set.add(other_pmid)
# this will need to be restructured to match schema
authors_group = re.findall('<Author.*?>(.+?)</Author>', xml, re.DOTALL)
if len(authors_group) > 0:
authors_list = []
authors_rank = 0
for author_xml in authors_group:
authors_rank = authors_rank + 1
lastname = ''
firstname = ''
firstinit = ''
collective_name = ''
fullname = ''
orcid = ''
affiliation = []
author_cross_references = []
lastname_re_output = re.search('<LastName>(.+?)</LastName>', author_xml)
if lastname_re_output is not None:
lastname = lastname_re_output.group(1)
firstname_re_output = re.search('<ForeName>(.+?)</ForeName>', author_xml)
if firstname_re_output is not None:
firstname = firstname_re_output.group(1)
firstinit_re_output = re.search('<Initials>(.+?)</Initials>', author_xml)
if firstinit_re_output is not None:
firstinit = firstinit_re_output.group(1)
if firstinit and not firstname:
firstname = firstinit
# e.g. 27899353 30979869
collective_re_output = re.search('<CollectiveName>(.+?)</CollectiveName>', author_xml, re.DOTALL)
if collective_re_output is not None:
collective_name = collective_re_output.group(1).replace('\n', ' ').replace('\r', '')
collective_name = re.sub(r'\s+', ' ', collective_name)
# e.g. 30003105 <Identifier Source="ORCID">0000-0002-9948-4783</Identifier>
# e.g. 30002370 <Identifier Source="ORCID">http://orcid.org/0000-0003-0416-374X</Identifier>
# orcid_re_output = re.search("<Identifier Source=\"ORCID\">(.+?)</Identifier>", author_xml)
orcid_re_output = re.search('<Identifier Source=\"ORCID\">.*?([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]).*?</Identifier>', author_xml)
if orcid_re_output is not None:
orcid = orcid_re_output.group(1)
orcid_dict = {'id': 'ORCID:' + orcid_re_output.group(1), 'pages': ['person/orcid']}
author_cross_references.append(orcid_dict)
# e.g. 30003105 30002370
# <AffiliationInfo>
# <Affiliation>Department of Animal Medical Sciences, Faculty of Life Sciences, Kyoto Sangyo University , Kyoto , Japan.</Affiliation>
# </AffiliationInfo>
affiliation_list = []
affiliation_info_group = re.findall('<AffiliationInfo>(.*?)</AffiliationInfo>', author_xml, re.DOTALL)
for affiliation_info in affiliation_info_group:
# print(pmid + " AIDL " + affiliation_info)
affiliation_group = re.findall('<Affiliation>(.+?)</Affiliation>', affiliation_info, re.DOTALL)
for affiliation in affiliation_group:
# print(pmid + " subset " + affiliation)
if affiliation not in affiliation_list:
affiliation_list.append(affiliation)
author_dict = {}
# if (firstname and firstinit):
# print "GOOD\t" + pmid
# elif firstname:
# print "FN\t" + pmid + "\t" + firstname
# elif firstinit:
# print "FI\t" + pmid + "\t" + firstinit
# else:
# print "NO\t" + pmid
if firstname != '':
author_dict['firstname'] = firstname
if firstinit != '':
author_dict['firstinit'] = firstinit
if lastname != '':
author_dict['lastname'] = lastname
if collective_name != '':
author_dict['collectivename'] = collective_name
if (firstname != '') and (lastname != ''):
fullname = firstname + ' ' + lastname
elif collective_name != '':
fullname = collective_name
elif lastname != '':
fullname = lastname
else:
logger.info('%s has no name match %s', pmid, author_xml)
if orcid != '':
author_dict['orcid'] = orcid
author_dict['name'] = fullname
author_dict['authorRank'] = authors_rank
if len(affiliation_list) > 0:
author_dict['affiliation'] = affiliation_list
if len(author_cross_references) > 0:
author_dict['crossReferences'] = author_cross_references
# print fullname
authors_list.append(author_dict)
data_dict['authors'] = authors_list
pub_date_re_output = re.search('<PubDate>(.+?)</PubDate>', xml, re.DOTALL)
if pub_date_re_output is not None:
pub_date = pub_date_re_output.group(1)
date_list = get_year_month_day_from_xml_date(pub_date)
if date_list[0]:
date_string = "-".join(date_list)
# print date_string
date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1],
'day': date_list[2]}
# datePublished is a string, not a date-time
data_dict['datePublished'] = date_string
data_dict['issueDate'] = date_dict
else:
# 1524678 2993907 have MedlineDate instead of Year Month Day
medline_date = get_medline_date_from_xml_date(pub_date)
if medline_date:
data_dict['date_string'] = medline_date
data_dict['datePublished'] = medline_date
date_revised_re_output = re.search("<DateRevised>(.+?)</DateRevised>", xml, re.DOTALL)
if date_revised_re_output is not None:
date_revised = date_revised_re_output.group(1)
date_list = get_year_month_day_from_xml_date(date_revised)
if date_list[0]:
date_string = '-'.join(date_list)
date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1],
'day': date_list[2]}
data_dict['dateLastModified'] = date_dict
date_received_re_output = re.search('<PubMedPubDate PubStatus=\"received\">(.+?)</PubMedPubDate>', xml, re.DOTALL)
if date_received_re_output is not None:
date_received = date_received_re_output.group(1)
date_list = get_year_month_day_from_xml_date(date_received)
if date_list[0]:
date_string = "-".join(date_list)
date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1],
'day': date_list[2]}
data_dict['dateArrivedInPubmed'] = date_dict
cross_references = []
has_self_pmid = False # e.g. 20301347, 21413225 do not have the PMID itself in the ArticleIdList, so must be appended to the cross_references
article_id_list_re_output = re.search('<ArticleIdList>(.*?)</ArticleIdList>', xml, re.DOTALL)
if article_id_list_re_output is not None:
article_id_list = article_id_list_re_output.group(1)
article_id_group = re.findall('<ArticleId IdType=\"(.*?)\">(.+?)</ArticleId>', article_id_list)
if len(article_id_group) > 0:
type_has_value = set()
for type_value in article_id_group:
type = type_value[0]
value = type_value[1]
# convert the only html entities found in DOIs < > &#60; &#62;
# e.g. PMID:8824556 PMID:10092111
value = value.replace('<', '<').replace('>', '>').replace('&#60;', '<').replace('&#62;', '>')
# print pmid + " type " + type + " value " + value
if type in known_article_id_types:
if value == pmid:
has_self_pmid = True
if type in type_has_value:
logger.info('%s has multiple for type %s', pmid, type)
type_has_value.add(type)
# cross_references.append({'id': known_article_id_types[type]['prefix'] + value, 'pages': [known_article_id_types[type]['pages']]})
cross_references.append({'id': known_article_id_types[type]['prefix'] + value})
data_dict[type] = value # for cleaning up crossReferences when reading dqm data
else:
if type not in ignore_article_id_types:
logger.info('%s has unexpected type %s', pmid, type)
unknown_article_id_types.add(type)
if not has_self_pmid:
cross_references.append({'id': 'PMID:' + pmid})
medline_journal_info_re_output = re.search('<MedlineJournalInfo>(.*?)</MedlineJournalInfo>', xml, re.DOTALL)
if medline_journal_info_re_output is not None:
medline_journal_info = medline_journal_info_re_output.group(1)
# print pmid + " medline_journal_info " + medline_journal_info
nlm = ''
issn = ''
journal_abbrev = ''
nlm_re_output = re.search('<NlmUniqueID>(.+?)</NlmUniqueID>', medline_journal_info)
if nlm_re_output is not None:
nlm = nlm_re_output.group(1)
cross_references.append({'id': 'NLM:' + nlm})
# cross_references.append({'id': 'NLM:' + nlm, 'pages': ['NLM']})
issn_re_output = re.search('<ISSNLinking>(.+?)</ISSNLinking>', medline_journal_info)
if issn_re_output is not None:
issn = issn_re_output.group(1)
cross_references.append({'id': 'ISSN:' + issn})
# cross_references.append({'id': 'ISSN:' + issn, 'pages': ['ISSN']})
journal_abbrev_re_output = re.search('<MedlineTA>(.+?)</MedlineTA>', medline_journal_info)
if journal_abbrev_re_output is not None:
journal_abbrev = journal_abbrev_re_output.group(1)
data_dict['nlm'] = nlm # for mapping to resource
data_dict['issn'] = issn # for mapping to MOD data to resource
data_dict['resourceAbbreviation'] = journal_abbrev
# check whether all xml has an nlm or issn, for WB set, they all do
# if (nlm and issn):
# print "GOOD\t" + pmid
# elif nlm:
# print "NLM\t" + pmid + "\t" + nlm
# elif issn:
# print "ISSN\t" + pmid + "\t" + issn
# else:
# print "NO\t" + pmid
if len(cross_references) > 0:
data_dict['crossReferences'] = cross_references
publisher_re_output = re.search('<PublisherName>(.+?)</PublisherName>', xml)
if publisher_re_output is not None:
publisher = publisher_re_output.group(1)
# print publisher
data_dict['publisher'] = publisher
# previously was only getting all abstract text together, but this was causing different types of abstracts to be concatenated
# regex_abstract_output = re.findall("<AbstractText.*?>(.+?)</AbstractText>", xml, re.DOTALL)
# if len(regex_abstract_output) > 0:
# abstract = " ".join(regex_abstract_output)
# data_dict['abstract'] = re.sub(r'\s+', ' ', abstract)
main_abstract_list = []
regex_abstract_output = re.findall('<Abstract>(.+?)</Abstract>', xml, re.DOTALL)
if len(regex_abstract_output) > 0:
for abs in regex_abstract_output:
regex_abstract_text_output = re.findall('<AbstractText.*?>(.+?)</AbstractText>', abs, re.DOTALL)
if len(regex_abstract_text_output) > 0:
for abstext in regex_abstract_text_output:
main_abstract_list.append(abstext)
main_abstract = ' '.join(main_abstract_list)
if main_abstract != '':
main_abstract = re.sub(r'\s+', ' ', main_abstract)
pip_abstract_list = []
plain_abstract_list = []
lang_abstract_list = []
regex_other_abstract_output = re.findall('<OtherAbstract (.+?)</OtherAbstract>', xml, re.DOTALL)
if len(regex_other_abstract_output) > 0:
for other_abstract in regex_other_abstract_output:
abs_type = ''
abs_lang = ''
abs_type_re_output = re.search('Type=\"(.*?)\"', other_abstract)
if abs_type_re_output is not None:
abs_type = abs_type_re_output.group(1)
abs_lang_re_output = re.search('Language=\"(.*?)\"', other_abstract)
if abs_lang_re_output is not None:
abs_lang = abs_lang_re_output.group(1)
if abs_type == 'Publisher':
lang_abstract_list.append(abs_lang)
else:
regex_abstract_text_output = re.findall('<AbstractText.*?>(.+?)</AbstractText>', other_abstract, re.DOTALL)
if len(regex_abstract_text_output) > 0:
for abstext in regex_abstract_text_output:
if abs_type == 'plain-language-summary':
plain_abstract_list.append(abstext)
elif abs_type == 'PIP':
pip_abstract_list.append(abstext)
pip_abstract = ' '.join(pip_abstract_list) # e.g. 9643811 has pip but not main
if pip_abstract != '':
pip_abstract = re.sub(r'\s+', ' ', pip_abstract)
plain_abstract = ' '.join(plain_abstract_list)
if plain_abstract != '': # e.g. 32338603 has plain abstract
data_dict['plainLanguageAbstract'] = re.sub(r'\s+', ' ', plain_abstract)
if len(lang_abstract_list) > 0: # e.g. 30160698 has fre and spa
data_dict['pubmedAbstractLanguages'] = lang_abstract_list
if main_abstract != '':
data_dict['abstract'] = main_abstract
elif pip_abstract != '': # e.g. 9643811 has pip but not main abstract
data_dict['abstract'] = pip_abstract
# some xml has keywords spanning multiple lines e.g. 30110134
# others get captured inside other keywords e.g. 31188077
regex_keyword_output = re.findall('<Keyword .*?>(.+?)</Keyword>', xml, re.DOTALL)
if len(regex_keyword_output) > 0:
keywords = []
for keyword in regex_keyword_output:
keyword = re.sub('<[^>]+?>', '', keyword)
keyword = keyword.replace('\n', ' ').replace('\r', '')
keyword = re.sub(r'\s+', ' ', keyword)
keyword = keyword.lstrip()
keywords.append(keyword)
data_dict['keywords'] = keywords
meshs_group = re.findall('<MeshHeading>(.+?)</MeshHeading>', xml, re.DOTALL)
if len(meshs_group) > 0:
meshs_list = []
for mesh_xml in meshs_group:
descriptor_re_output = re.search('<DescriptorName.*?>(.+?)</DescriptorName>', mesh_xml, re.DOTALL)
if descriptor_re_output is not None:
mesh_heading_term = descriptor_re_output.group(1)
qualifier_group = re.findall('<QualifierName.*?>(.+?)</QualifierName>', mesh_xml, re.DOTALL)
if len(qualifier_group) > 0:
for mesh_qualifier_term in qualifier_group:
mesh_dict = {'referenceId': 'PMID:' + pmid, 'meshHeadingTerm': mesh_heading_term,
'meshQualifierTerm': mesh_qualifier_term}
meshs_list.append(mesh_dict)
else:
mesh_dict = {'referenceId': 'PMID:' + pmid, 'meshHeadingTerm': mesh_heading_term}
meshs_list.append(mesh_dict)
# for mesh_xml in meshs_group:
# descriptor_group = re.findall("<DescriptorName.*?UI=\"(.+?)\".*?>(.+?)</DescriptorName>",
# mesh_xml, re.DOTALL)
# if len(descriptor_group) > 0:
# for id_name in descriptor_group:
# mesh_dict = {}
# mesh_dict["referenceId"] = id_name[0]
# mesh_dict["meshHeadingTerm"] = id_name[1]
# meshs_list.append(mesh_dict)
# qualifier_group = re.findall("<QualifierName.*?UI=\"(.+?)\".*?>(.+?)</QualifierName>",
# mesh_xml, re.DOTALL)
# if len(qualifier_group) > 0:
# for id_name in qualifier_group:
# mesh_dict = {}
# mesh_dict["referenceId"] = id_name[0]
# mesh_dict["meshQualifierTerm"] = id_name[1]
# meshs_list.append(mesh_dict)
data_dict['meshTerms'] = meshs_list
# generate the object using json.dumps()
# corresponding to json data
# minified
# json_data = json.dumps(data_dict)
# pretty-print
json_data = json.dumps(data_dict, indent=4, sort_keys=True)
# Write the json data to output json file
# UNCOMMENT TO write to json directory
json_filename = json_storage_path + pmid + '.json'
# if getting pmids from directories split into multiple sub-subdirectories
# json_filename = get_path_from_pmid(pmid, 'json')
with open(json_filename, 'w') as json_file:
json_file.write(json_data)
json_file.close()
md5sum = hashlib.md5(json_data.encode('utf-8')).hexdigest()
md5data += pmid + '\t' + md5sum + '\n'
md5file = json_storage_path + 'md5sum'
logger.info('Writing md5sum mappings to %s', md5file)
with open(md5file, 'a') as md5file_fh:
md5file_fh.write(md5data)
for unknown_article_id_type in unknown_article_id_types:
logger.warning('unknown_article_id_type %s', unknown_article_id_type)
for ref_type in ref_types_set:
logger.info('ref_type %s', ref_type)
new_pmids = sorted(new_pmids_set)
for pmid in new_pmids:
logger.info('new_pmid %s', pmid)
return new_pmids
@click.command()
@click.option('-c', '--commandline', 'cli', multiple=True, help='take input from command line flag', required=False)
@click.option('-d', '--database', 'db', help='take input from database query', required=False)
@click.option('-f', '--file', 'ffile', help='take input from entries in file with full path', required=False)
@click.option('-r', '--restapi', 'api', help='take input from rest api', required=False)
@click.option('-s', '--sample', 'sample', help='test sample input from hardcoded entries', required=False, default=False, is_flag=True)
@click.option('-u', '--url', 'url', help='take input from entries in file at url', required=False)
def process_tasks(cli, db, ffile, api, sample, url):
"""
:param cli:
:param db:
:param ffile:
:param api:
:param sample:
:param url:
:return:
"""
# set storage location
# todo: see if environment variable check works
# base_path = '/home/azurebrd/git/agr_literature_service_demo/src/xml_processing/'
if len(os.environ.get('XML_PATH')) == 0:
sys.exit()
else:
base_path = os.environ.get('XML_PATH')
storage_path = base_path + 'pubmed_xml/'
logger.info('Base path is at ' + base_path)
logger.info('XMLs will be saved on ' + storage_path)
pmids = [] # list that will contain the PMIDs to be converted
# checking parameters
if db:
# python xml_to_json.py -d
logger.info('Processing database entries')
elif api:
# python xml_to_json.py -r
logger.info('Processing rest api entries')
elif ffile:
# python xml_to_json.py -f /home/azurebrd/git/agr_literature_service_demo/src/xml_processing/inputs/pmid_file.txt
logger.info('Processing file input from ' + ffile)
# this requires a well structured input
pmids = open(ffile).read().splitlines()
elif url:
# python xml_to_json.py -u http://tazendra.caltech.edu/~azurebrd/var/work/pmid_sample
logger.info('Processing url input from %s', url)
req = urllib.request.urlopen(url)
data = req.read()
lines = data.splitlines()
for pmid in lines:
pmids.append(str(int(pmid)))
elif cli:
# python xml_to_json.py -c 1234 4576 1828
logger.info('Processing commandline input')
for pmid in cli:
pmids.append(pmid)
elif sample:
# python xml_to_json.py -s
logger.info('Processing hardcoded sample input')
pmids = ['12345678', '12345679', '12345680']
# else:
# logger.info("Processing database entries")
# when iterating manually through list of PMIDs from PubMed XML CommentsCorrections,
# and wanting to exclude PMIDs that have already been looked at from original alliance DQM input, or previous iterations.
previous_pmids = []
previous_pmids_files = []
# previous_pmids_files = ['inputs/alliance_pmids', 'inputs/comcor_add1', 'inputs/comcor_add2', 'inputs/comcor_add3']
# previous_pmids_files = ['inputs/alliance_pmids', 'inputs/comcor_add1', 'inputs/comcor_add2',
# 'inputs/comcor_add3', 'inputs/comcor_add4', 'inputs/comcor_add5', 'inputs/comcor_add6',
# 'inputs/comcor_add7', 'inputs/comcor_add8', 'inputs/comcor_add9', 'inputs/comcor_add10',
# 'inputs/comcor_add11']
for previous_pmids_file in previous_pmids_files:
with open(previous_pmids_file, 'r') as fp:
pmid = fp.readline()
while pmid:
previous_pmids.append(pmid.rstrip())
pmid = fp.readline()
generate_json(pmids, previous_pmids, base_path)
logger.info("Done converting XML to JSON")
if __name__ == '__main__':
"""
call main start function
"""
process_tasks()
|
[] |
[] |
[
"XML_PATH"
] |
[]
|
["XML_PATH"]
|
python
| 1 | 0 | |
main.go
|
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
)
//Debug ... turn on or off Debug mode
var Debug, NetDebug bool
// Configuration variables
var configFile, configFileSet = os.LookupEnv("CONFIG_FILE")
var refreshInterval int
var devicename, devicetype, symbol, defaultHSV string
var EffectiveDeviceConfig DeviceConfig
// Read the configuration json file and populate DeviceConfig struct
func loadDeviceConfiguration() DeviceConfig {
// Set a default configfile if its not set already
if !configFileSet {
configFile = "config.json"
}
// Read the Config file
jsonFile, err := ioutil.ReadFile(configFile)
if err != nil {
fmt.Println(fmt.Sprintf("ERROR: Could not read from file: %s, err: %s", configFile, err))
}
//Declare a map variable
EffectiveDeviceConfig = DeviceConfig{}
// Read file as byte array
err = json.Unmarshal([]byte(jsonFile), &EffectiveDeviceConfig)
if err != nil {
fmt.Println(fmt.Sprintf("ERROR: Could not Unmarshall json: %s, err: %s", configFile, err))
}
return EffectiveDeviceConfig
}
func init() {
// Lookup DEBUG environment variable and set it globally
v := os.Getenv("DEBUG")
var err error
Debug, err = strconv.ParseBool(v)
if err != nil {
Debug = false
}
// Lookup DEBUG environment variable and set it globally
n := os.Getenv("NET_DEBUG")
NetDebug, err = strconv.ParseBool(n)
if err != nil {
NetDebug = false
}
config := loadDeviceConfiguration()
// Set flags (overriding the file configuration if it exists)
flag.IntVar(&refreshInterval, "n", -1, "Specifies the number of seconds to lookup stock price")
flag.StringVar(&devicename, "name", config.DefaultDeviceName, "Specifies the target device")
flag.StringVar(&devicetype, "type", config.DeviceType, "Specifies the target device type")
flag.StringVar(&symbol, "symbol", config.DefaultSymbol, "Specifies the symbol to lookup")
}
func main() {
flag.Parse()
fmt.Println("INFO: Loaded configuration: ", EffectiveDeviceConfig)
var device Device
if devicetype == "colorbulb" {
device = NewColorBulbDevice()
} else {
device = NewSimpleDevice()
}
changePercent := readChangePercent(symbol)
device.Render(changePercent, &EffectiveDeviceConfig)
}
|
[
"\"DEBUG\"",
"\"NET_DEBUG\""
] |
[] |
[
"NET_DEBUG",
"DEBUG"
] |
[]
|
["NET_DEBUG", "DEBUG"]
|
go
| 2 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.