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 |
---|---|---|---|---|---|---|---|---|---|---|
operator-application-scaler/scaler/application_resource.go
|
package scaler
import (
"fmt"
"os"
"path/filepath"
applicationoperatorv1beta1 "github.com/ibm/operator-sample-go/operator-application/api/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)
func getApplicationResource() error {
config, err := rest.InClusterConfig()
if err != nil {
kubeconfig := filepath.Join(
os.Getenv("HOME"), ".kube", "config",
)
fmt.Println("Using kubeconfig file: ", kubeconfig)
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return err
}
}
var GroupVersion = schema.GroupVersion{Group: "applications.application.sample.ibm.com", Version: "v1beta1"}
var SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
var databaseOperatorScheme *runtime.Scheme
fmt.Println("Attempting SchemeBuilder.Build")
databaseOperatorScheme, err = SchemeBuilder.Build()
if err != nil {
return err
}
fmt.Println("Attempting AddToScheme")
err = applicationoperatorv1beta1.AddToScheme(databaseOperatorScheme)
if err != nil {
return err
}
fmt.Println("Attempting client.New")
kubernetesClient, err = client.New(config, client.Options{Scheme: databaseOperatorScheme})
if err != nil {
return err
}
fmt.Println("Attempting kubernetesClient.Get")
applicationResource = &applicationoperatorv1beta1.Application{}
err = kubernetesClient.Get(applicationContext, types.NamespacedName{Name: applicationName, Namespace: applicationNamespace}, applicationResource)
if err != nil {
return err
}
return nil
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
examples/volumes/main.go
|
package main
import (
"context"
"fmt"
"github.com/antihax/optional"
"github.com/outscale/osc-sdk-go/osc"
"os"
)
func main() {
client := osc.NewAPIClient(osc.NewConfiguration())
auth := context.WithValue(context.Background(), osc.ContextAWSv4, osc.AWSv4{
AccessKey: os.Getenv("OSC_ACCESS_KEY"),
SecretKey: os.Getenv("OSC_SECRET_KEY"),
})
read, httpRes, err := client.VolumeApi.ReadVolumes(auth, nil)
if err != nil {
fmt.Fprintln(os.Stderr, "Error while reading volumes")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("We currently have", len(read.Volumes), "volumes:")
for _, volume := range read.Volumes {
println("-", volume.VolumeId)
}
println("Creating 10GB GP2 volume")
creationOpts := osc.CreateVolumeOpts{
CreateVolumeRequest: optional.NewInterface(
osc.CreateVolumeRequest{
Size: 10,
VolumeType: "gp2",
SubregionName: "eu-west-2a",
}),
}
creation, httpRes, err := client.VolumeApi.CreateVolume(auth, &creationOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while creating volume ")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("Created volume", creation.Volume.VolumeId)
println("Reading created volume details")
readOpts := osc.ReadVolumesOpts{
ReadVolumesRequest: optional.NewInterface(
osc.ReadVolumesRequest{
Filters: osc.FiltersVolume{
VolumeIds: []string{creation.Volume.VolumeId},
},
}),
}
read, httpRes, err = client.VolumeApi.ReadVolumes(auth, &readOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while reading volumes ")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println(creation.Volume.VolumeId, "details:")
volume := read.Volumes[0]
println("- Id:", volume.VolumeId)
println("- Size:", volume.Size)
println("- Type:", volume.VolumeType)
println("- State:", volume.State)
println("Deleting volume", creation.Volume.VolumeId)
deletionOpts := osc.DeleteVolumeOpts{
DeleteVolumeRequest: optional.NewInterface(
osc.DeleteVolumeRequest{
VolumeId: creation.Volume.VolumeId,
}),
}
_, httpRes, err = client.VolumeApi.DeleteVolume(auth, &deletionOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while deleting volume ")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("Deleted volume", creation.Volume.VolumeId)
}
|
[
"\"OSC_ACCESS_KEY\"",
"\"OSC_SECRET_KEY\""
] |
[] |
[
"OSC_ACCESS_KEY",
"OSC_SECRET_KEY"
] |
[]
|
["OSC_ACCESS_KEY", "OSC_SECRET_KEY"]
|
go
| 2 | 0 | |
cmd/cmdtest/testutils.go
|
// Copyright © 2019 IBM Corporation and others.
//
// 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 cmdtest
import (
"bufio"
"bytes"
"encoding/json"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"github.com/appsody/appsody/cmd"
"gopkg.in/yaml.v2"
)
const CLEANUP = true
const TravisTesting = false
// Repository struct represents an appsody repository
type Repository struct {
Name string
URL string
}
type TestSandbox struct {
*testing.T
ProjectDir string
TestDataPath string
ProjectName string
ConfigDir string
ConfigFile string
Verbose bool
}
func inArray(haystack []string, needle string) bool {
for _, value := range haystack {
if needle == value {
return true
}
}
return false
}
func TestSetup(t *testing.T, parallel bool) {
if parallel {
t.Parallel()
}
}
func TestSetupWithSandbox(t *testing.T, parallel bool) (*TestSandbox, func()) {
var testDirPath, _ = filepath.Abs(filepath.Join("..", "cmd", "testdata"))
TestSetup(t, parallel)
// default to verbose mode
sandbox := &TestSandbox{T: t, Verbose: true}
// create a temporary dir to create the project and run the test
dirPrefix := "appsody-" + t.Name() + "-"
dirPrefix = strings.ReplaceAll(dirPrefix, "/", "-")
dirPrefix = strings.ReplaceAll(dirPrefix, "\\", "-")
testDir, err := ioutil.TempDir("", dirPrefix)
if err != nil {
t.Fatal("Error creating temporary directory: ", err)
}
// remove symlinks from the path
// on mac, TMPDIR is set to /var which is a symlink to /private/var.
// Docker by default shares mounts with /private but not /var,
// so resolving the symlinks ensures docker can mount the temp dir
testDir, err = filepath.EvalSymlinks(testDir)
if err != nil {
t.Fatal("Error evaluating symlinks: ", err)
}
sandbox.ProjectName = strings.ToLower(strings.Replace(filepath.Base(testDir), "appsody-", "", 1))
sandbox.ProjectDir = filepath.Join(testDir, sandbox.ProjectName)
sandbox.ConfigDir = filepath.Join(testDir, "config")
sandbox.TestDataPath = filepath.Join(testDir, "testdata")
err = os.MkdirAll(sandbox.ProjectDir, 0755)
if err != nil {
t.Fatal("Error creating project dir: ", err)
}
t.Log("Created testing project dir: ", sandbox.ProjectDir)
err = os.MkdirAll(sandbox.ConfigDir, 0755)
if err != nil {
t.Fatal("Error creating project dir: ", err)
}
t.Log("Created testing project dir: ", sandbox.ProjectDir)
t.Log("Created testing config dir: ", sandbox.ConfigDir)
// Create the config file if it does not already exist.
sandbox.ConfigFile = filepath.Join(sandbox.ConfigDir, "config.yaml")
data := []byte("home: " + sandbox.ConfigDir + "\n" + "generated-by-tests: Yes" + "\n")
err = ioutil.WriteFile(sandbox.ConfigFile, data, 0644)
if err != nil {
t.Fatal("Error writing config file: ", err)
}
var outBuffer bytes.Buffer
log := &cmd.LoggingConfig{}
log.InitLogging(&outBuffer, &outBuffer)
file, err := cmd.Exists(testDirPath)
if err != nil {
t.Fatalf("Cannot find source directory %s to copy. Error: %v", testDirPath, err)
}
if !file {
t.Fatalf("The file %s could not be found.", testDirPath)
}
err = cmd.CopyDir(log, testDirPath, sandbox.TestDataPath)
if err != nil {
t.Fatalf("Could not copy %s to %s - output of copy command %s", testDirPath, testDir, err)
}
t.Log(outBuffer.String())
t.Logf("Directory copy of %s to %s was successful \n", testDirPath, testDir)
configFolders := []string{}
files, err := ioutil.ReadDir(sandbox.TestDataPath)
if err != nil {
t.Fatal(err)
}
// Compile an array of the repository files in the test directory
for _, f := range files {
if strings.Contains(f.Name(), "_repository_") {
configFolders = append(configFolders, f.Name())
}
}
for _, config := range configFolders {
file, err := ioutil.ReadFile(filepath.Join(sandbox.TestDataPath, config, "config.yaml"))
if err != nil {
t.Fatal(err)
}
lines := strings.Split(string(file), "\n")
for i, line := range lines {
if strings.Contains(line, "home:") {
oldLine := strings.SplitN(line, " ", -1)
lines[i] = "home: " + filepath.Join(testDir, oldLine[1])
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(filepath.Join(sandbox.TestDataPath, config, "config.yaml"), []byte(output), 0644)
if err != nil {
t.Fatal(err)
}
}
cleanupFunc := func() {
if CLEANUP {
err := os.RemoveAll(testDir)
if err != nil {
t.Log("WARNING - ignoring error cleaning up test directory: ", err)
}
}
}
return sandbox, cleanupFunc
}
func (s *TestSandbox) SetConfigInTestData(pathUnderTestdata string) {
if pathUnderTestdata != "" {
s.ConfigDir = filepath.Join(s.TestDataPath, pathUnderTestdata)
s.ConfigFile = filepath.Join(s.ConfigDir, "config.yaml")
}
}
// RunAppsody runs the appsody CLI with the given args, using
// the sandbox for the project dir and config home.
// The stdout and stderr are captured, printed and returned
// args will be passed to the appsody command
func RunAppsody(t *TestSandbox, args ...string) (string, error) {
if t.Verbose && !(inArray(args, "-v") || inArray(args, "--verbose")) {
args = append(args, "-v")
}
if !inArray(args, "--config") {
// Set appsody args to use custom home directory.
args = append(args, "--config", t.ConfigFile)
}
// // Buffer cmd output, to be logged if there is a failure
var outBuffer bytes.Buffer
// Direct cmd console output to a buffer
outReader, outWriter := io.Pipe()
// copy the output to the buffer, and also to the test log
outScanner := bufio.NewScanner(outReader)
var wg sync.WaitGroup
wg.Add(1)
go func() {
for outScanner.Scan() {
out := outScanner.Bytes()
outBuffer.Write(out)
outBuffer.WriteByte('\n')
t.Log(string(out))
}
wg.Done()
}()
t.Log("Running appsody in the test sandbox with args: ", args)
err := cmd.ExecuteE("vlatest", "latest", t.ProjectDir, outWriter, outWriter, args)
if err != nil {
t.Log("Error returned from appsody command: ", err)
}
// close the writer first, so it sends an EOF to the scanner above,
// then wait for the scanner to finish before closing the reader
outWriter.Close()
wg.Wait()
outReader.Close()
return outBuffer.String(), err
}
// ParseRepoList takes in the string from 'appsody repo list' command
// and returns an array of Repository structs from the string.
func ParseRepoList(repoListString string) []Repository {
repoStrs := strings.Split(repoListString, "\n")
var repos []Repository
for _, repoStr := range repoStrs {
fields := strings.Fields(repoStr)
if len(fields) == 2 {
if fields[0] != "NAME" && fields[0] != "Using" {
repos = append(repos, Repository{fields[0], fields[1]})
}
}
}
return repos
}
// ParseJSON finds the json on the output string
func ParseJSON(repoListString string) string {
jsonString := ""
repoStrings := strings.Split(repoListString, "\n")
for _, repoStr := range repoStrings {
if strings.HasPrefix(repoStr, "{") || strings.HasPrefix(repoStr, "[{") {
jsonString = repoStr
break
}
}
return jsonString
}
// ParseYAML finds the start of the yaml string
func ParseYAML(output string) string {
var outputLines = strings.Split(output, "\n")
var splitIndex int
for index, line := range outputLines {
if (strings.HasPrefix(line, "-") || strings.Contains(line, ":")) && !strings.HasPrefix(line, "[") {
splitIndex = index
break
}
}
return strings.Join(outputLines[splitIndex:], "\n")
}
// ParseRepoListJSON takes the json from 'appsody repo list -o json'
// and returns a RepositoryFile from the string.
func ParseRepoListJSON(jsonString string) (cmd.RepositoryFile, error) {
var repos cmd.RepositoryFile
e := json.Unmarshal([]byte(jsonString), &repos)
if e != nil {
return repos, e
}
return repos, nil
}
// ParseRepoListYAML takes the yaml from 'appsody repo list -o yaml'
// and returns a RepositoryFile from the string.
func ParseRepoListYAML(yamlString string) (cmd.RepositoryFile, error) {
var repos cmd.RepositoryFile
yamlString = strings.Replace(yamlString, "\n\n", "\n", -1)
e := yaml.Unmarshal([]byte(yamlString), &repos)
if e != nil {
return repos, e
}
return repos, nil
}
// ParseListJSON takes the json from 'appsody list -o json'
// and returns an array of IndexOutputFormat from the string.
func ParseListJSON(jsonString string) (cmd.IndexOutputFormat, error) {
var index cmd.IndexOutputFormat
err := json.Unmarshal([]byte(jsonString), &index)
if err != nil {
return index, err
}
return index, nil
}
// ParseListYAML takes the yaml from 'appsody list -o yaml'
// and returns an array of IndexOutputFormat from the string.
func ParseListYAML(yamlString string) (cmd.IndexOutputFormat, error) {
var index cmd.IndexOutputFormat
err := yaml.Unmarshal([]byte(yamlString), &index)
if err != nil {
return index, err
}
return index, nil
}
// AddLocalRepo calls the `appsody repo add` command with the repo index located
// at the local file path. The path may be relative to the current working directory.
// Returns the URL of the repo added.
func AddLocalRepo(t *TestSandbox, repoName string, repoFilePath string) (string, error) {
absPath, err := filepath.Abs(repoFilePath)
if err != nil {
return "", err
}
var repoURL string
if runtime.GOOS == "windows" {
// for windows, add a leading slash and convert to unix style slashes
absPath = "/" + filepath.ToSlash(absPath)
}
repoURL = "file://" + absPath
// add a new repo
_, err = RunAppsody(t, "repo", "add", repoName, repoURL)
if err != nil {
return "", err
}
return repoURL, nil
}
// RunDockerCmdExec runs the docker command with the given args in a new process
// The stdout and stderr are captured, printed, and returned
// args will be passed to the docker command
// workingDir will be the directory the command runs in
func RunDockerCmdExec(args []string, t *testing.T) (string, error) {
cmdArgs := []string{"docker"}
cmdArgs = append(cmdArgs, args...)
t.Log(cmdArgs)
execCmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
outReader, outWriter := io.Pipe()
execCmd.Stdout = outWriter
execCmd.Stderr = outWriter
outScanner := bufio.NewScanner(outReader)
var outBuffer bytes.Buffer
var wg sync.WaitGroup
wg.Add(1)
go func() {
for outScanner.Scan() {
out := outScanner.Bytes()
outBuffer.Write(out)
outBuffer.WriteByte('\n')
t.Log(string(out))
}
wg.Done()
}()
err := execCmd.Start()
if err != nil {
return "", err
}
err = execCmd.Wait()
// close the writer first, so it sends an EOF to the scanner above,
// then wait for the scanner to finish before closing the reader
outWriter.Close()
wg.Wait()
outReader.Close()
return outBuffer.String(), err
}
// Checks whether an inode (it does not bother
// about file or folder) exists or not.
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func GetEnvStacksList() string {
stacksList := os.Getenv("STACKS_LIST")
if stacksList == "" {
stacksList = "incubator/nodejs"
}
return stacksList
}
|
[
"\"STACKS_LIST\""
] |
[] |
[
"STACKS_LIST"
] |
[]
|
["STACKS_LIST"]
|
go
| 1 | 0 | |
stages/midonet_agents/fabfile.py
|
#
# Copyright (c) 2015 Midokura SARL, 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
from senbazuru.config import Config
from senbazuru.utils import Puppet
from fabric.api import env,parallel,roles,run
from fabric.colors import green
from fabric.utils import puts
metadata = Config(os.environ["CONFIGFILE"])
@parallel
@roles('midonet_agents', 'midonet_gateways')
def midonet_agents():
puts(green("installing MidoNet agent on %s" % env.host_string))
zk = []
for zkhost in metadata.roles['zookeeper']:
zk.append("{'ip' => '%s', 'port' => '2181'}" % metadata.servers[zkhost]['internal_ip'])
cs = []
for cshost in metadata.roles['cassandra']:
cs.append("'%s'" % metadata.servers[cshost]['internal_ip'])
args = {}
args['zk_servers'] = "[%s]" % ",".join(zk)
args['cassandra_seeds'] = "[%s]" % ",".join(cs)
Puppet.apply('midonet::midonet_agent', args, metadata)
run("""
cat >/tmp/buffer.json <<EOF
agent {
datapath {
max_flow_count=200000
send_buffer_pool_buf_size_kb=2048
send_buffer_pool_initial_size=2048
send_buffer_pool_max_size=4096
}
}
EOF
# TODO mn-conf set -t default < /tmp/buffer.json
""")
#
# modify the init script to allow higher number of open files
#
run("""
SCRIPT="/usr/share/midolman/midolman-start-senbazuru"
cat >/etc/init/senbazuru.conf <<EOF
description "Midolman with more open files"
start on runlevel [2345]
stop on runlevel [016]
respawn
respawn limit 2 120
kill timeout 5
umask 022
console none
pre-start script
exec /usr/share/midolman/midolman-prepare
end script
script
exec ${SCRIPT}
end script
EOF
chmod 0755 /etc/init/senbazuru.conf
cat >"${SCRIPT}" <<EOF
#!/bin/bash
set -e
ulimit -n 1000000
/usr/share/midolman/midolman-start
EOF
chmod 0755 "${SCRIPT}"
service midolman restart
""")
|
[] |
[] |
[
"CONFIGFILE"
] |
[]
|
["CONFIGFILE"]
|
python
| 1 | 0 | |
main.go
|
package main
import (
"crypto/rand"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"io/fs"
random "math/rand"
"net/http"
"os"
"path"
"path/filepath"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/liimee/idk/board"
"github.com/liimee/idk/user"
)
type User = user.User
type H struct {
clis map[*Cli]bool
bc chan []byte
reg chan *Cli
unreg chan *Cli
}
type Cli struct {
n *H
co *websocket.Conn
send chan []byte
game string
id string
}
type Game struct {
Players []User
Start bool
Turn string
Bid float64
Bidd User
Biddi bool
Biddd []string
BidPos int
}
//go:embed build/*
var f embed.FS
var dev = os.Getenv("DEV") == "y"
var gs = map[string]Game{}
var hu *H
func main() {
e := mux.NewRouter()
e.Path("/api/new").Methods("POST").HandlerFunc(New)
e.Path("/api/board").Methods("GET").HandlerFunc(func(w http.ResponseWriter, h *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
b, _ := json.Marshal(board.Board)
w.Write([]byte(b))
})
e.Path("/api/exists/{game}").Methods("GET").HandlerFunc(GameExists)
hu = &H{
bc: make(chan []byte),
reg: make(chan *Cli),
unreg: make(chan *Cli),
clis: make(map[*Cli]bool),
}
go hu.Run()
e.Path("/api/ws").HandlerFunc(func(w http.ResponseWriter, h *http.Request) {
Ws(hu, w, h)
})
s := ":3000"
if dev {
s = ":4000"
}
p, pp := os.LookupEnv("PORT")
if pp {
s = ":" + p
}
if !dev {
e.PathPrefix("/").HandlerFunc(fe)
}
fmt.Println("running")
http.Handle("/", e)
http.ListenAndServe(s, nil)
}
func New(w http.ResponseWriter, h *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", os.Getenv("CL"))
id := GetRandom()
gs[id] = Game{Players: []User{}, Start: false, Turn: "", Bid: 0, Bidd: User{}, Biddi: false, Biddd: []string{}, BidPos: 0}
m, _ := json.Marshal(map[string]string{"id": id})
w.Write([]byte(m))
}
func GetRandom() string {
b := make([]byte, 6)
rand.Read(b)
return hex.EncodeToString(b)
}
func Ws(hu *H, w http.ResponseWriter, h *http.Request) {
s := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
c, _ := s.Upgrade(w, h, nil)
client := &Cli{n: hu, co: c, send: make(chan []byte, 256), id: "", game: ""}
client.n.reg <- client
go client.ReadWs()
}
func fe(w http.ResponseWriter, r *http.Request) {
s, _ := fs.Sub(f, "build")
d, _ := filepath.Abs(r.URL.Path)
_, er := fs.Stat(f, path.Join("build", d))
if os.IsNotExist(er) {
g, _ := f.ReadFile("build/index.html")
w.Write(g)
return
}
http.FileServer(http.FS(s)).ServeHTTP(w, r)
}
func (h *H) Run() {
for {
select {
case client := <-h.reg:
h.clis[client] = true
case client := <-h.unreg:
if _, ok := h.clis[client]; ok {
delete(h.clis, client)
close(client.send)
}
}
}
}
func (c *Cli) ReadWs() {
for {
_, m, err := c.co.ReadMessage()
if err != nil {
if c.game != "" {
d := gs[c.game]
d.Players = RemovePlayer(c.game, c.id)
gs[c.game] = d
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
}
hu.unreg <- c
break
}
var s map[string]string
json.Unmarshal(m, &s)
if s["s"] == "join" {
r := GetRandom()
l := gs[s["id"]]
if l.Start {
c.co.WriteJSON(map[string]string{
"S": "err",
"E": "The game has started",
})
c.co.Close()
hu.unreg <- c
return
}
random.Seed(time.Now().UnixNano())
cols := []string{"#B10606", "#B08205", "#05B014", "#0566B0"}
l.Players = append(gs[s["id"]].Players, User{
Name: s["as"],
Money: 1500,
Id: r,
Pos: 0,
Owns: []int{},
InJail: false,
Color: cols[random.Intn(len(cols))],
Mo: []int{},
Ho: map[int]int{},
})
gs[s["id"]] = l
c.id = r
c.game = s["id"]
c.co.WriteJSON(map[string]string{"S": "id", "Id": c.id})
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "start" {
n := gs[c.game]
n.Start = true
n.Turn = gs[c.game].Players[0].Id
gs[c.game] = n
mr, _ := json.Marshal(struct {
S string
Start bool
}{S: "start", Start: gs[c.game].Start})
gs[c.game].BcGame(mr)
Turn(c.game)
} else if s["s"] == "roll" {
if c.id != gs[c.game].Turn {
return
}
g := gs[c.game]
ss := &g.Players[GetIndexById(g.Turn, g)]
random.Seed(time.Now().UnixNano())
ss.Pos += (random.Intn(11) + 1)
if ss.Pos > 39 {
ss.Pos -= 40
ss.Money += 200
}
if ss.Pos == 30 {
ss.Pos = 10
ss.InJail = true
}
if WhoOwnsIt(c.game, ss.Pos) != c.id && WhoOwnsIt(c.game, ss.Pos) != "" && !IsMortgaged(ss.Pos, gs[c.game]) && ss.Pos%10 != 5 {
ss.Money -= board.Board[ss.Pos].Rent[gs[c.game].Players[GetIndexById(WhoOwnsIt(c.game, ss.Pos), gs[c.game])].Ho[ss.Pos]] // "0"
gs[c.game].Players[GetIndexById(WhoOwnsIt(c.game, ss.Pos), gs[c.game])].Money += board.Board[ss.Pos].Rent[gs[c.game].Players[GetIndexById(WhoOwnsIt(c.game, ss.Pos), gs[c.game])].Ho[ss.Pos]]
}
if ss.Pos == 4 {
ss.Money -= 200
}
if ss.Pos == 38 {
ss.Money -= 100
}
if board.Board[ss.Pos].Name == "Chance" {
random.Seed(time.Now().UnixNano())
rk := random.Intn(len(board.ChanceCards))
c.co.WriteJSON(map[string]string{
"S": "card",
"Str": board.ChanceCards[rk].Str,
"T": "a",
})
g.Players[GetIndexById(g.Turn, g)] = board.ChanceCards[rk].Fun(GetPlayerById(c.id, g))
}
if board.Board[ss.Pos].Name == "Community Chest" {
random.Seed(time.Now().UnixNano())
rk := random.Intn(len(board.CommunityChestCards))
c.co.WriteJSON(map[string]string{
"S": "card",
"Str": board.CommunityChestCards[rk].Str,
"T": "b",
})
g.Players[GetIndexById(g.Turn, g)] = board.CommunityChestCards[rk].Fun(GetPlayerById(c.id, g))
}
if ss.Pos%10 == 5 {
n := Stations(gs[c.game].Players[GetIndexById(WhoOwnsIt(c.game, ss.Pos), gs[c.game])].Id, c.game)
ss.Money -= board.Board[ss.Pos].Rent[0] * n
gs[c.game].Players[GetIndexById(WhoOwnsIt(c.game, ss.Pos), gs[c.game])].Money += board.Board[ss.Pos].Rent[0] * n
}
gs[c.game] = g
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "endturn" {
if c.id != gs[c.game].Turn {
return
}
n := gs[c.game]
if WhoOwnsIt(c.game, GetPlayerById(c.id, n).Pos) == "" && board.Board[GetPlayerById(c.id, n).Pos].Price > 0 {
n.Bid = 0
n.Bidd = User{}
n.Biddi = true
n.BidPos = GetPlayerById(c.id, n).Pos
s, _ := json.Marshal(map[string]interface{}{
"S": "bid",
"Bid": n.Bid,
"Biddi": n.Biddi,
"Pa": n.Biddd,
"Biddd": n.BidPos,
})
gs[c.game].BcGame(s)
gs[c.game] = n
} else {
d := GetIndexById(n.Turn, n) + 1
if d >= len(n.Players) {
d = 0
}
n.Turn = n.Players[d].Id
gs[c.game] = n
Turn(c.game)
}
} else if s["s"] == "buy" {
if c.id != gs[c.game].Turn || GetPlayerById(c.id, gs[c.game]).Money < board.Board[GetPlayerById(c.id, gs[c.game]).Pos].Price {
return
}
//TODO: check
s := gs[c.game]
m := s.Players[GetIndexById(c.id, s)]
m.Owns = append(m.Owns, m.Pos)
m.Money -= board.Board[m.Pos].Price
s.Players[GetIndexById(c.id, s)] = m
gs[c.game] = s
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "bid" {
if gs[c.game].Biddi {
var s map[string]interface{}
json.Unmarshal(m, &s)
f := gs[c.game]
if s["bid"].(float64) > gs[c.game].Bid && s["bid"].(float64) <= float64(GetPlayerById(c.id, f).Money) {
f.Bid = s["bid"].(float64)
f.Bidd = GetPlayerById(c.id, f)
f.Biddd = []string{}
gs[c.game] = f
s, _ := json.Marshal(map[string]interface{}{
"S": "bid",
"Bid": f.Bid,
"Biddi": f.Biddi,
"Pa": f.Biddd,
"Biddd": f.BidPos,
})
gs[c.game].BcGame(s)
}
}
} else if s["s"] == "pass" {
f := gs[c.game]
f.Biddd = append(f.Biddd, c.id)
if len(f.Biddd) == len(f.Players) {
if f.Bid > 0 {
mmm := f.Players[GetIndexById(f.Bidd.Id, f)]
mmm.Money -= int(f.Bid)
mmm.Owns = append(mmm.Owns, f.BidPos)
f.Players[GetIndexById(f.Bidd.Id, f)] = mmm
}
f.Bid = 0
f.Bidd = User{}
f.Biddd = []string{}
f.Biddi = false
d := GetIndexById(f.Turn, f) + 1
if d >= len(f.Players) {
d = 0
}
f.Turn = f.Players[d].Id
gs[c.game] = f
Turn(c.game)
}
gs[c.game] = f
s, _ := json.Marshal(map[string]interface{}{
"S": "bid",
"Bid": f.Bid,
"Biddi": f.Biddi,
"Pa": f.Biddd,
"Biddd": f.BidPos,
})
gs[c.game].BcGame(s)
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "payjail" {
m := GetPlayerById(c.id, gs[c.game])
m.Money -= 50
m.InJail = false
gs[c.game].Players[GetIndexById(c.id, gs[c.game])] = m
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "resign" {
d := gs[c.game]
mm := GetIndexById(c.id, d)
d.Players = RemovePlayer(c.game, c.id)
gs[c.game] = d
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
if len(gs[c.game].Players) == 1 {
co := GetClisById(d.Players[0].Id).co
co.WriteJSON(map[string]string{
"S": "win",
})
co.Close()
} else {
mm += 1
if mm >= len(d.Players) {
mm = 0
}
d.Turn = d.Players[mm].Id
gs[c.game] = d
Turn(c.game)
}
} else if s["s"] == "mortgage" {
var s map[string]interface{}
json.Unmarshal(m, &s)
pos := int(s["pos"].(float64))
or := false
for _, v := range GetPlayerById(c.id, gs[c.game]).Owns {
if board.Board[v].Set == board.Board[pos].Set {
if GetPlayerById(c.id, gs[c.game]).Ho[v] > 0 {
or = true
}
}
}
if WhoOwnsIt(c.game, pos) == c.id && !or {
n := gs[c.game]
u := &n.Players[GetIndexById(c.game, n)]
if !IsMortgaged(pos, gs[c.game]) {
u.Money += (board.Board[pos].Price / 2)
u.Mo = append(u.Mo, pos)
} else {
ps := board.Board[pos].Price / 2
u.Money -= (ps + int((0.1 * float64(ps))))
index := 0
for i, vv := range u.Mo {
if vv == pos {
index = i
break
}
}
u.Mo = append(u.Mo[:index], u.Mo[index+1:]...)
}
gs[c.game] = n
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
}
} else if s["s"] == "ho" {
var s map[string]interface{}
json.Unmarshal(m, &s)
pos := int(s["pos"].(float64))
pl := GetPlayerById(c.id, gs[c.game])
if _, ok := pl.Ho[pos]; !ok {
pl.Ho[pos] = 0
}
if !IsMortgaged(pos, gs[c.game]) && SameOwner(pos, pl, gs[c.game]) && pl.Ho[pos] < 5 {
switch board.Board[pos].Set {
case 1, 2:
pl.Money -= 50
case 3, 4:
pl.Money -= 100
case 5, 6:
pl.Money -= 150
case 7, 8:
pl.Money -= 200
}
pl.Ho[pos] += 1
}
g := gs[c.game]
g.Players[GetIndexById(c.id, g)] = pl
gs[c.game] = g
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
} else if s["s"] == "sell" {
var s map[string]interface{}
json.Unmarshal(m, &s)
pos := int(s["pos"].(float64))
pl := GetPlayerById(c.id, gs[c.game])
if _, ok := pl.Ho[pos]; !ok {
pl.Ho[pos] = 0
}
if !IsMortgaged(pos, gs[c.game]) && SameOwner(pos, pl, gs[c.game]) && pl.Ho[pos] > 0 {
switch board.Board[pos].Set {
case 1, 2:
pl.Money += 50 / 2
case 3, 4:
pl.Money += 100 / 2
case 5, 6:
pl.Money += 150 / 2
case 7, 8:
pl.Money += 200 / 2
}
pl.Ho[pos] -= 1
}
g := gs[c.game]
g.Players[GetIndexById(c.id, g)] = pl
gs[c.game] = g
br, _ := json.Marshal(struct {
S string
Data []User
}{S: "data", Data: gs[c.game].Players})
gs[c.game].BcGame(br)
}
}
}
func SameOwner(p int, u User, gm Game) bool {
set := board.Board[p].Set
or := 0
for _, v := range board.Board {
if v.Set == set {
or++
}
}
pp := 0
for _, v := range u.Owns {
if board.Board[v].Set == set && !IsMortgaged(v, gm) {
pp++
}
}
return or == pp
}
func Turn(g string) {
GetClisById(gs[g].Turn).co.WriteJSON(map[string]string{
"S": "turn",
})
}
func GetPlayerById(s string, g Game) User {
var j User
for _, v := range g.Players {
if v.Id == s {
j = v
break
}
}
return j
}
func GetIndexById(s string, g Game) int {
var j int
for v, d := range g.Players {
if d.Id == s {
j = v
break
}
}
return j
}
func GetClisById(s string) *Cli {
var n *Cli
for f := range hu.clis {
if f.id == s {
n = f
}
}
return n
}
func (g Game) BcGame(d []byte) {
for _, f := range g.Players {
GetClisById(f.Id).co.WriteMessage(websocket.TextMessage, d)
}
}
func WhoOwnsIt(g string, n int) string {
var f string
for _, s := range gs[g].Players {
for _, j := range s.Owns {
if n == j {
f = s.Id
break
}
}
}
return f
}
func Stations(g string, j string) int {
var s = 0
for _, k := range []int{5, 15, 25, 35} {
if WhoOwnsIt(j, k) == g {
s++
}
}
return s
}
func IsMortgaged(id int, g Game) bool {
s := false
for _, u := range g.Players {
for _, p := range u.Mo {
if p == id {
s = true
break
}
}
}
return s
}
func RemovePlayer(s string, d string) []User {
n := gs[s].Players
for k, f := range gs[s].Players {
if f.Id == d {
n = append(n[:k], n[k+1:]...)
}
}
return n
}
func GameExists(w http.ResponseWriter, h *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", os.Getenv("CL"))
p := mux.Vars(h)
_, ok := gs[p["game"]]
j, _ := json.Marshal(map[string]bool{
"Exists": ok,
})
w.Write(j)
}
|
[
"\"DEV\"",
"\"CL\"",
"\"CL\""
] |
[] |
[
"CL",
"DEV"
] |
[]
|
["CL", "DEV"]
|
go
| 2 | 0 | |
resources/distance_view.pb.go
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.15.8
// source: google/ads/googleads/v8/resources/distance_view.proto
package resources
import (
enums "github.com/felicson/google-ads-go/enums"
_ "google.golang.org/genproto/googleapis/api/annotations"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// A distance view with metrics aggregated by the user's distance from an
// advertiser's location extensions. Each DistanceBucket includes all
// impressions that fall within its distance and a single impression will
// contribute to the metrics for all DistanceBuckets that include the user's
// distance.
type DistanceView struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Output only. The resource name of the distance view.
// Distance view resource names have the form:
//
// `customers/{customer_id}/distanceViews/1~{distance_bucket}`
ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"`
// Output only. Grouping of user distance from location extensions.
DistanceBucket enums.DistanceBucketEnum_DistanceBucket `protobuf:"varint,2,opt,name=distance_bucket,json=distanceBucket,proto3,enum=google.ads.googleads.v8.enums.DistanceBucketEnum_DistanceBucket" json:"distance_bucket,omitempty"`
// Output only. True if the DistanceBucket is using the metric system, false otherwise.
MetricSystem *bool `protobuf:"varint,4,opt,name=metric_system,json=metricSystem,proto3,oneof" json:"metric_system,omitempty"`
}
func (x *DistanceView) Reset() {
*x = DistanceView{}
if protoimpl.UnsafeEnabled {
mi := &file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DistanceView) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DistanceView) ProtoMessage() {}
func (x *DistanceView) ProtoReflect() protoreflect.Message {
mi := &file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DistanceView.ProtoReflect.Descriptor instead.
func (*DistanceView) Descriptor() ([]byte, []int) {
return file_google_ads_googleads_v8_resources_distance_view_proto_rawDescGZIP(), []int{0}
}
func (x *DistanceView) GetResourceName() string {
if x != nil {
return x.ResourceName
}
return ""
}
func (x *DistanceView) GetDistanceBucket() enums.DistanceBucketEnum_DistanceBucket {
if x != nil {
return x.DistanceBucket
}
return enums.DistanceBucketEnum_DistanceBucket(0)
}
func (x *DistanceView) GetMetricSystem() bool {
if x != nil && x.MetricSystem != nil {
return *x.MetricSystem
}
return false
}
var File_google_ads_googleads_v8_resources_distance_view_proto protoreflect.FileDescriptor
var file_google_ads_googleads_v8_resources_distance_view_proto_rawDesc = []byte{
0x0a, 0x35, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x38, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72,
0x63, 0x65, 0x73, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x76, 0x69, 0x65,
0x77, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x21, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x38,
0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x1a, 0x33, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73,
0x2f, 0x76, 0x38, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e,
0x63, 0x65, 0x5f, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a,
0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c,
0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73,
0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x8f, 0x03, 0x0a, 0x0c, 0x44, 0x69,
0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x56, 0x69, 0x65, 0x77, 0x12, 0x52, 0x0a, 0x0d, 0x72, 0x65,
0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x42, 0x2d, 0xe0, 0x41, 0x03, 0xfa, 0x41, 0x27, 0x0a, 0x25, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x56, 0x69, 0x65, 0x77,
0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6e,
0x0a, 0x0f, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x62, 0x75, 0x63, 0x6b, 0x65,
0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x40, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76,
0x38, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x2e, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65,
0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x45, 0x6e, 0x75, 0x6d, 0x2e, 0x44, 0x69, 0x73, 0x74, 0x61,
0x6e, 0x63, 0x65, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0e,
0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x12, 0x2d,
0x0a, 0x0d, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x18,
0x04, 0x20, 0x01, 0x28, 0x08, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x48, 0x00, 0x52, 0x0c, 0x6d, 0x65,
0x74, 0x72, 0x69, 0x63, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x88, 0x01, 0x01, 0x3a, 0x7a, 0xea,
0x41, 0x77, 0x0a, 0x25, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x69, 0x73,
0x74, 0x61, 0x6e, 0x63, 0x65, 0x56, 0x69, 0x65, 0x77, 0x12, 0x4e, 0x63, 0x75, 0x73, 0x74, 0x6f,
0x6d, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69,
0x64, 0x7d, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x56, 0x69, 0x65, 0x77, 0x73,
0x2f, 0x7b, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x5f, 0x63, 0x68,
0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x7d, 0x7e, 0x7b, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63,
0x65, 0x5f, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x7d, 0x42, 0x10, 0x0a, 0x0e, 0x5f, 0x6d, 0x65,
0x74, 0x72, 0x69, 0x63, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x42, 0xfe, 0x01, 0x0a, 0x25,
0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x38, 0x2e, 0x72, 0x65, 0x73, 0x6f,
0x75, 0x72, 0x63, 0x65, 0x73, 0x42, 0x11, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x56,
0x69, 0x65, 0x77, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x4a, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65,
0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69,
0x73, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f,
0x76, 0x38, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x3b, 0x72, 0x65, 0x73,
0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0xa2, 0x02, 0x03, 0x47, 0x41, 0x41, 0xaa, 0x02, 0x21, 0x47,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x41, 0x64, 0x73, 0x2e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x41, 0x64, 0x73, 0x2e, 0x56, 0x38, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73,
0xca, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x41, 0x64, 0x73, 0x5c, 0x47, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x5c, 0x56, 0x38, 0x5c, 0x52, 0x65, 0x73, 0x6f, 0x75,
0x72, 0x63, 0x65, 0x73, 0xea, 0x02, 0x25, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x41,
0x64, 0x73, 0x3a, 0x3a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x3a, 0x3a, 0x56,
0x38, 0x3a, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x33,
}
var (
file_google_ads_googleads_v8_resources_distance_view_proto_rawDescOnce sync.Once
file_google_ads_googleads_v8_resources_distance_view_proto_rawDescData = file_google_ads_googleads_v8_resources_distance_view_proto_rawDesc
)
func file_google_ads_googleads_v8_resources_distance_view_proto_rawDescGZIP() []byte {
file_google_ads_googleads_v8_resources_distance_view_proto_rawDescOnce.Do(func() {
file_google_ads_googleads_v8_resources_distance_view_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_ads_googleads_v8_resources_distance_view_proto_rawDescData)
})
return file_google_ads_googleads_v8_resources_distance_view_proto_rawDescData
}
var file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_google_ads_googleads_v8_resources_distance_view_proto_goTypes = []interface{}{
(*DistanceView)(nil), // 0: google.ads.googleads.v8.resources.DistanceView
(enums.DistanceBucketEnum_DistanceBucket)(0), // 1: google.ads.googleads.v8.enums.DistanceBucketEnum.DistanceBucket
}
var file_google_ads_googleads_v8_resources_distance_view_proto_depIdxs = []int32{
1, // 0: google.ads.googleads.v8.resources.DistanceView.distance_bucket:type_name -> google.ads.googleads.v8.enums.DistanceBucketEnum.DistanceBucket
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_google_ads_googleads_v8_resources_distance_view_proto_init() }
func file_google_ads_googleads_v8_resources_distance_view_proto_init() {
if File_google_ads_googleads_v8_resources_distance_view_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DistanceView); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes[0].OneofWrappers = []interface{}{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_google_ads_googleads_v8_resources_distance_view_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_google_ads_googleads_v8_resources_distance_view_proto_goTypes,
DependencyIndexes: file_google_ads_googleads_v8_resources_distance_view_proto_depIdxs,
MessageInfos: file_google_ads_googleads_v8_resources_distance_view_proto_msgTypes,
}.Build()
File_google_ads_googleads_v8_resources_distance_view_proto = out.File
file_google_ads_googleads_v8_resources_distance_view_proto_rawDesc = nil
file_google_ads_googleads_v8_resources_distance_view_proto_goTypes = nil
file_google_ads_googleads_v8_resources_distance_view_proto_depIdxs = nil
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
common/utils.go
|
package common
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
)
// P2E panic to error
func P2E(perr *error) {
if x := recover(); x != nil {
if e, ok := x.(error); ok {
*perr = e
} else {
panic(x)
}
}
}
// E2P error to panic
func E2P(err error) {
if err != nil {
panic(err)
}
}
// CatchP catch panic to error
func CatchP(f func()) (rerr error) {
defer P2E(&rerr)
f()
return nil
}
// PanicIf name is clear
func PanicIf(cond bool, err error) {
if cond {
panic(err)
}
}
// MustAtoi 走must逻辑
func MustAtoi(s string) int {
r, err := strconv.Atoi(s)
if err != nil {
E2P(errors.New("convert to int error: " + s))
}
return r
}
// OrString return the first not empty string
func OrString(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}
// If ternary operator
func If(condition bool, trueObj interface{}, falseObj interface{}) interface{} {
if condition {
return trueObj
}
return falseObj
}
// MustMarshal checked version for marshal
func MustMarshal(v interface{}) []byte {
b, err := json.Marshal(v)
E2P(err)
return b
}
// MustMarshalString string version of MustMarshal
func MustMarshalString(v interface{}) string {
return string(MustMarshal(v))
}
// MustUnmarshal checked version for unmarshal
func MustUnmarshal(b []byte, obj interface{}) {
err := json.Unmarshal(b, obj)
E2P(err)
}
// MustUnmarshalString string version of MustUnmarshal
func MustUnmarshalString(s string, obj interface{}) {
MustUnmarshal([]byte(s), obj)
}
// MustRemarshal marshal and unmarshal, and check error
func MustRemarshal(from interface{}, to interface{}) {
b, err := json.Marshal(from)
E2P(err)
err = json.Unmarshal(b, to)
E2P(err)
}
// GetGinApp init and return gin
func GetGinApp() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
app := gin.Default()
app.Use(func(c *gin.Context) {
body := ""
if c.Request.Body != nil {
rb, err := c.GetRawData()
E2P(err)
if len(rb) > 0 {
body = string(rb)
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rb))
}
}
began := time.Now()
logrus.Printf("begin %s %s query: %s body: %s", c.Request.Method, c.FullPath(), c.Request.URL.RawQuery, body)
c.Next()
logrus.Printf("used %d ms %s %s query: %s body: %s", time.Since(began).Milliseconds(), c.Request.Method, c.FullPath(), c.Request.URL.RawQuery, body)
})
app.Any("/api/ping", func(c *gin.Context) { c.JSON(200, M{"msg": "pong"}) })
return app
}
// WrapHandler name is clear
func WrapHandler(fn func(*gin.Context) (interface{}, error)) gin.HandlerFunc {
return func(c *gin.Context) {
r, err := fn(c)
var b = []byte{}
if err == nil {
b, err = json.Marshal(r)
}
if err != nil {
logrus.Printf("status: 500, code: 500 message: %s", err.Error())
c.JSON(500, M{"code": 500, "message": err.Error()})
} else {
logrus.Printf("status: 200, content: %s", string(b))
c.Status(200)
c.Writer.Header().Add("Content-Type", "application/json")
_, err = c.Writer.Write(b)
E2P(err)
}
}
}
// RestyClient the resty object
var RestyClient = resty.New()
func init() {
// RestyClient.SetTimeout(3 * time.Second)
// RestyClient.SetRetryCount(2)
// RestyClient.SetRetryWaitTime(1 * time.Second)
RestyClient.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
if IsDockerCompose() {
r.URL = strings.Replace(r.URL, "localhost", "host.docker.internal", 1)
}
logrus.Printf("requesting: %s %s %v %v", r.Method, r.URL, r.Body, r.QueryParam)
return nil
})
RestyClient.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
r := resp.Request
logrus.Printf("requested: %s %s %s", r.Method, r.URL, resp.String())
return nil
})
}
// CheckRestySuccess panic if error or resp not success
func CheckRestySuccess(resp *resty.Response, err error) {
E2P(err)
if !strings.Contains(resp.String(), "SUCCESS") {
panic(fmt.Errorf("resty response not success: %s", resp.String()))
}
}
// formatter 自定义formatter
type formatter struct{}
// Format 进行格式化
func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
var b *bytes.Buffer = &bytes.Buffer{}
if entry.Buffer != nil {
b = entry.Buffer
}
n := time.Now()
ts := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d.%03d", n.Year(), n.Month(), n.Day(), n.Hour(), n.Minute(), n.Second(), n.Nanosecond()/1000000)
var file string
var line int
for i := 1; ; i++ {
_, file, line, _ = runtime.Caller(i)
if strings.Contains(file, "dtm") {
break
}
}
b.WriteString(fmt.Sprintf("%s %s:%d %s\n", ts, path.Base(file), line, entry.Message))
return b.Bytes(), nil
}
// InitApp init config
func InitApp(dir string, config interface{}) {
logrus.SetFormatter(&formatter{})
cont, err := ioutil.ReadFile(dir + "/conf.yml")
if err != nil {
cont, err = ioutil.ReadFile(dir + "/conf.sample.yml")
}
logrus.Printf("cont is: \n%s", string(cont))
E2P(err)
err = yaml.Unmarshal(cont, config)
E2P(err)
}
// MustGetwd must version of os.Getwd
func MustGetwd() string {
wd, err := os.Getwd()
E2P(err)
return wd
}
// GetCurrentCodeDir name is clear
func GetCurrentCodeDir() string {
_, file, _, _ := runtime.Caller(1)
return filepath.Dir(file)
}
// GetProjectDir name is clear
func GetProjectDir() string {
_, file, _, _ := runtime.Caller(1)
for ; !strings.HasSuffix(file, "/dtm"); file = filepath.Dir(file) {
}
return file
}
// GetFuncName get current call func name
func GetFuncName() string {
pc, _, _, _ := runtime.Caller(1)
return runtime.FuncForPC(pc).Name()
}
// IsDockerCompose name is clear
func IsDockerCompose() bool {
return os.Getenv("IS_DOCKER_COMPOSE") != ""
}
|
[
"\"IS_DOCKER_COMPOSE\""
] |
[] |
[
"IS_DOCKER_COMPOSE"
] |
[]
|
["IS_DOCKER_COMPOSE"]
|
go
| 1 | 0 | |
apipass.go
|
package main
import (
"context"
"flag"
"log"
"os"
"strconv"
)
func apipass() {
var server, token string
fg := flag.NewFlagSet("apipass", flag.ExitOnError)
fg.StringVar(&server, "server", "", "server")
fg.StringVar(&token, "token", "", "token (env BRIDGE_TOKEN)")
fg.Parse(os.Args[2:])
if len(token) == 0 {
token = os.Getenv("BRIDGE_TOKEN")
}
cl := NewClient()
cl.host = server
cl.token = token
owner := GetOwner()
project := GetProject()
pr, _, err := cl.gh.PullRequests.Get(context.Background(), owner, project, GetReqId())
if err != nil {
log.Fatal(err)
}
var body struct {
Pass bool `json:"pass"`
Msg string `json:"msg"`
}
params := map[string]string{
"group": owner,
"project": project,
"branch": getBranch(),
"request_id": strconv.Itoa(GetReqId()),
"request_event": getEvent(),
"commit_id": pr.Head.GetSHA(),
}
log.Println("parmas", params)
resp, err := cl.R().
SetQueryParams(params).
SetResult(&body).
Get(cl.host + "/api/apicheck/status")
if err != nil {
log.Println(err)
}
if resp.StatusCode() != 200 {
log.Fatal(resp.Status())
}
if !body.Pass {
log.Fatal(body.Msg)
}
}
|
[
"\"BRIDGE_TOKEN\""
] |
[] |
[
"BRIDGE_TOKEN"
] |
[]
|
["BRIDGE_TOKEN"]
|
go
| 1 | 0 | |
zilencer/management/commands/sync_api_key.py
|
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from django.core.management.base import BaseCommand
from zerver.models import get_user_profile_by_email, UserProfile
import os
from six.moves.configparser import SafeConfigParser
class Command(BaseCommand):
help = """Sync your API key from ~/.zuliprc into your development instance"""
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
config_file = os.path.join(os.environ["HOME"], ".zuliprc")
if not os.path.exists(config_file):
raise RuntimeError("No ~/.zuliprc found")
config = SafeConfigParser()
with open(config_file, 'r') as f:
config.readfp(f, config_file)
api_key = config.get("api", "key")
email = config.get("api", "email")
try:
user_profile = get_user_profile_by_email(email)
user_profile.api_key = api_key
user_profile.save(update_fields=["api_key"])
except UserProfile.DoesNotExist:
print("User %s does not exist; not syncing API key" % (email,))
|
[] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
python
| 1 | 0 | |
ldap_integration/ldap_test.go
|
package ldap_integration_test
import (
"io/ioutil"
"os"
"strconv"
"github.com/pivotal-michael-stergianis/cf-mgmt/config"
. "github.com/pivotal-michael-stergianis/cf-mgmt/ldap"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Ldap", func() {
var ldapManager *Manager
Describe("given a ldap manager", func() {
BeforeEach(func() {
var host string
var port int
var err error
if os.Getenv("LDAP_PORT_389_TCP_ADDR") == "" {
host = "127.0.0.1"
port = 389
} else {
host = os.Getenv("LDAP_PORT_389_TCP_ADDR")
port, _ = strconv.Atoi(os.Getenv("LDAP_PORT_389_TCP_PORT"))
}
ldapConfig := &config.LdapConfig{
BindDN: "cn=admin,dc=pivotal,dc=org",
BindPassword: "password",
UserSearchBase: "ou=users,dc=pivotal,dc=org",
UserNameAttribute: "uid",
UserMailAttribute: "mail",
GroupSearchBase: "dc=pivotal,dc=org",
GroupAttribute: "member",
LdapHost: host,
LdapPort: port,
}
ldapManager, err = NewManager(ldapConfig)
Expect(err).ShouldNot(HaveOccurred())
})
AfterEach(func() {
ldapManager.Close()
})
Context("when cn with special characters", func() {
It("then it should return 1 Entry", func() {
entry, err := ldapManager.GetUserByDN(`cn=Washburn\2c Caleb,ou=users,dc=pivotal,dc=org`)
Expect(err).Should(BeNil())
Expect(entry).ShouldNot(BeNil())
})
It("then it should return 1 Entry", func() {
entry, err := ldapManager.GetUserByDN("cn=Ekın Toğulmoç 88588,ou=users,dc=pivotal,dc=org")
Expect(err).Should(BeNil())
Expect(entry).ShouldNot(BeNil())
})
})
Context("when cn has a period", func() {
It("then it should return 1 Entry", func() {
entry, err := ldapManager.GetUserByDN("cn=Caleb A. Washburn,ou=users,dc=pivotal,dc=org")
Expect(err).Should(BeNil())
Expect(entry).ShouldNot(BeNil())
})
})
Context("when called with a valid group", func() {
It("then it should return 5 users", func() {
users, err := ldapManager.GetUserDNs("space_developers")
Expect(err).Should(BeNil())
Expect(len(users)).Should(Equal(6))
Expect(users).To(ConsistOf([]string{
"cn=cwashburn,ou=users,dc=pivotal,dc=org",
"cn=Washburn\\2C Caleb,ou=users,dc=pivotal,dc=org",
"cn=special\\2C (char) - username,ou=users,dc=pivotal,dc=org",
"cn=Caleb A. Washburn,ou=users,dc=pivotal,dc=org",
"cn=cwashburn1,ou=users,dc=pivotal,dc=org",
"cn=Washburn\\2C Caleb\\2C cwashburn,ou=users,dc=pivotal,dc=org"}))
})
})
Context("when called with a valid group with special characters", func() {
It("then it should return 4 users", func() {
users, err := ldapManager.GetUserDNs("special (char) group,name")
Expect(err).Should(BeNil())
Expect(len(users)).Should(Equal(4))
})
})
Context("GetUser()", func() {
It("then it should return 1 user", func() {
user, err := ldapManager.GetUserByID("cwashburn")
Expect(err).Should(BeNil())
Expect(user).ShouldNot(BeNil())
Expect(user.UserID).Should(Equal("cwashburn"))
Expect(user.UserDN).Should(Equal("cn=cwashburn,ou=users,dc=pivotal,dc=org"))
Expect(user.Email).Should(Equal("[email protected]"))
})
})
Describe("given a ldap manager with userObjectClass", func() {
BeforeEach(func() {
var host string
var port int
var err error
if os.Getenv("LDAP_PORT_389_TCP_ADDR") == "" {
host = "127.0.0.1"
port = 389
} else {
host = os.Getenv("LDAP_PORT_389_TCP_ADDR")
port, _ = strconv.Atoi(os.Getenv("LDAP_PORT_389_TCP_PORT"))
}
ldapConfig := &config.LdapConfig{
BindDN: "cn=admin,dc=pivotal,dc=org",
BindPassword: "password",
UserSearchBase: "ou=users,dc=pivotal,dc=org",
UserNameAttribute: "uid",
UserMailAttribute: "mail",
GroupSearchBase: "dc=pivotal,dc=org",
GroupAttribute: "member",
LdapHost: host,
LdapPort: port,
UserObjectClass: "inetOrgPerson",
}
ldapManager, err = NewManager(ldapConfig)
Expect(err).ShouldNot(HaveOccurred())
})
AfterEach(func() {
ldapManager.Close()
})
Context("when cn with special characters", func() {
It("then it should return 1 Entry", func() {
entry, err := ldapManager.GetUserByDN(`cn=Washburn\2c Caleb,ou=users,dc=pivotal,dc=org`)
Expect(err).Should(BeNil())
Expect(entry).ShouldNot(BeNil())
})
})
Context("GetUser()", func() {
It("then it should return 1 user", func() {
user, err := ldapManager.GetUserByID("cwashburn")
Expect(err).Should(BeNil())
Expect(user).ShouldNot(BeNil())
Expect(user.UserID).Should(Equal("cwashburn"))
Expect(user.UserDN).Should(Equal("cn=cwashburn,ou=users,dc=pivotal,dc=org"))
Expect(user.Email).Should(Equal("[email protected]"))
})
})
Context("GetLdapUser()", func() {
It("then it should return 1 user", func() {
data, _ := ioutil.ReadFile("./fixtures/user1.txt")
user, err := ldapManager.GetUserByDN(string(data))
Expect(err).Should(BeNil())
Expect(user).ShouldNot(BeNil())
Expect(user.UserID).Should(Equal("cwashburn2"))
Expect(user.Email).Should(Equal("[email protected]"))
})
})
})
})
})
|
[
"\"LDAP_PORT_389_TCP_ADDR\"",
"\"LDAP_PORT_389_TCP_ADDR\"",
"\"LDAP_PORT_389_TCP_PORT\"",
"\"LDAP_PORT_389_TCP_ADDR\"",
"\"LDAP_PORT_389_TCP_ADDR\"",
"\"LDAP_PORT_389_TCP_PORT\""
] |
[] |
[
"LDAP_PORT_389_TCP_PORT",
"LDAP_PORT_389_TCP_ADDR"
] |
[]
|
["LDAP_PORT_389_TCP_PORT", "LDAP_PORT_389_TCP_ADDR"]
|
go
| 2 | 0 | |
stats.go
|
// Copyright 2018. Akamai Technologies, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
time "time"
akamai "github.com/akamai/cli-common-golang"
"github.com/fatih/color"
"github.com/google/uuid"
)
// Akamai CLI (optionally) tracks upgrades, package installs, and updates anonymously
//
// This is done by generating an anonymous UUID that events are tied to
const statsVersion string = "1.1"
func firstRunCheckStats(bannerShown bool) bool {
anonymous := color.New(color.FgWhite, color.Bold).Sprint("anonymous")
if getConfigValue("cli", "enable-cli-statistics") == "" {
if !bannerShown {
bannerShown = true
showBanner()
}
fmt.Fprintf(akamai.App.Writer, "Help Akamai improve Akamai CLI by automatically sending %s diagnostics and usage data.\n", anonymous)
fmt.Fprintln(akamai.App.Writer, "Examples of data being sent include upgrade statistics, and packages installed and updated.")
fmt.Fprintf(akamai.App.Writer, "Note: if you choose to opt-out, a single %s event will be submitted to help track overall usage.", anonymous)
fmt.Fprintf(akamai.App.Writer, "\n\nSend %s diagnostics and usage data to Akamai? [Y/n]: ", anonymous)
answer := ""
fmt.Scanln(&answer)
if answer != "" && strings.ToLower(answer) != "y" {
trackEvent("first-run", "stats-opt-out", "true")
setConfigValue("cli", "enable-cli-statistics", "false")
saveConfig()
return bannerShown
}
setConfigValue("cli", "enable-cli-statistics", statsVersion)
setConfigValue("cli", "last-ping", "never")
setupUUID()
saveConfig()
trackEvent("first-run", "stats-enabled", statsVersion)
} else if getConfigValue("cli", "enable-cli-statistics") != "false" {
migrateStats(bannerShown)
}
return bannerShown
}
func migrateStats(bannerShown bool) bool {
currentVersion := getConfigValue("cli", "stats-version")
if currentVersion == statsVersion {
return bannerShown
}
if !bannerShown {
bannerShown = true
showBanner()
}
var newStats []string
switch currentVersion {
case "1.0":
newStats = []string{"command name executed (no arguments)", "command version executed"}
}
anonymous := color.New(color.FgWhite, color.Bold).Sprint("anonymous")
fmt.Fprintf(akamai.App.Writer, "Akamai CLI has changed the %s data it collects. It now additionally collects the following: \n\n", anonymous)
for _, value := range newStats {
fmt.Fprintf(akamai.App.Writer, " - %s\n", value)
}
fmt.Fprintf(akamai.App.Writer, "\nTo continue collecting %s statistics, Akamai CLI requires that you re-affirm you decision.\n", anonymous)
fmt.Fprintln(akamai.App.Writer, "Note: if you choose to opt-out, a single anonymous event will be submitted to help track overall usage.")
fmt.Fprintf(akamai.App.Writer, "\nContinue sending %s diagnostics and usage data to Akamai? [Y/n]: ", anonymous)
answer := ""
fmt.Scanln(&answer)
if answer != "" && strings.ToLower(answer) != "y" {
trackEvent("first-run", "stats-update-opt-out", statsVersion)
setConfigValue("cli", "enable-cli-statistics", "false")
saveConfig()
return bannerShown
}
setConfigValue("cli", "stats-version", statsVersion)
saveConfig()
trackEvent("first-run", "stats-update-opt-in", statsVersion)
return bannerShown
}
func setupUUID() error {
if getConfigValue("cli", "client-id") == "" {
uuid, err := uuid.NewRandom()
if err != nil {
return err
}
setConfigValue("cli", "client-id", uuid.String())
saveConfig()
}
return nil
}
func trackEvent(category string, action string, value string) {
if getConfigValue("cli", "enable-cli-statistics") == "false" {
return
}
clientId := "anonymous"
if val := getConfigValue("cli", "client-id"); val != "" {
clientId = val
}
form := url.Values{}
form.Add("tid", "UA-34796267-23")
form.Add("v", "1") // Version 1
form.Add("aip", "1") // Anonymize IP
form.Add("cid", clientId) // Client ID
form.Add("t", "event") // Type
form.Add("ec", category) // Category
form.Add("ea", action) // Action
form.Add("el", value) // Label
hc := http.Client{}
debug := os.Getenv("AKAMAI_CLI_DEBUG_ANALYTICS")
var req *http.Request
var err error
if debug != "" {
req, err = http.NewRequest("POST", "https://www.google-analytics.com/debug/collect", strings.NewReader(form.Encode()))
} else {
req, err = http.NewRequest("POST", "https://www.google-analytics.com/collect", strings.NewReader(form.Encode()))
}
if err != nil {
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := hc.Do(req)
if debug != "" {
body, _ := ioutil.ReadAll(res.Body)
fmt.Fprintln(akamai.App.Writer, string(body))
}
}
func checkPing() {
if getConfigValue("cli", "enable-cli-statistics") == "false" {
return
}
data := strings.TrimSpace(getConfigValue("cli", "last-ping"))
doPing := false
if data == "" || data == "never" {
doPing = true
} else {
configValue := strings.TrimPrefix(strings.TrimSuffix(string(data), "\""), "\"")
lastPing, err := time.Parse(time.RFC3339, configValue)
if err != nil {
return
}
currentTime := time.Now()
if lastPing.Add(time.Hour * 24).Before(currentTime) {
doPing = true
}
}
if doPing {
trackEvent("ping", "daily", "pong")
setConfigValue("cli", "last-ping", time.Now().Format(time.RFC3339))
saveConfig()
}
}
|
[
"\"AKAMAI_CLI_DEBUG_ANALYTICS\""
] |
[] |
[
"AKAMAI_CLI_DEBUG_ANALYTICS"
] |
[]
|
["AKAMAI_CLI_DEBUG_ANALYTICS"]
|
go
| 1 | 0 | |
classifier/examples/main.py
|
"""
Downloads the MovieLens dataset, ETLs it into Parquet, trains an
ALS model, and uses the ALS model to train a Keras neural network.
See README.rst for more details.
"""
import click
import os
import mlflow
from mlflow.utils import mlflow_tags
from mlflow.entities import RunStatus
from mlflow.utils.logging_utils import eprint
import six
from mlflow.tracking.fluent import _get_experiment_id
def _already_ran(entry_point_name, parameters, git_commit, experiment_id=None):
"""Best-effort detection of if a run with the given entrypoint name,
parameters, and experiment id already ran. The run must have completed
successfully and have at least the parameters provided.
"""
experiment_id = experiment_id if experiment_id is not None else _get_experiment_id()
client = mlflow.tracking.MlflowClient()
all_run_infos = reversed(client.list_run_infos(experiment_id))
for run_info in all_run_infos:
full_run = client.get_run(run_info.run_id)
tags = full_run.data.tags
if tags.get(mlflow_tags.MLFLOW_PROJECT_ENTRY_POINT, None) != entry_point_name:
continue
match_failed = False
for param_key, param_value in six.iteritems(parameters):
run_value = full_run.data.params.get(param_key)
if run_value != param_value:
match_failed = True
break
if match_failed:
continue
if run_info.to_proto().status != RunStatus.FINISHED:
eprint(("Run matched, but is not FINISHED, so skipping "
"(run_id=%s, status=%s)") % (run_info.run_id, run_info.status))
continue
previous_version = tags.get(mlflow_tags.MLFLOW_GIT_COMMIT, None)
if git_commit != previous_version:
eprint(("Run matched, but has a different source version, so skipping "
"(found=%s, expected=%s)") % (previous_version, git_commit))
continue
return client.get_run(run_info.run_id)
eprint("No matching run has been found.")
return None
# TODO(aaron): This is not great because it doesn't account for:
# - changes in code
# - changes in dependant steps
def _get_or_run(entrypoint, parameters, git_commit, use_cache=True):
existing_run = _already_ran(entrypoint, parameters, git_commit)
if use_cache and existing_run:
print("Found existing run for entrypoint=%s and parameters=%s" % (entrypoint, parameters))
return existing_run
print("Launching new run for entrypoint=%s and parameters=%s" % (entrypoint, parameters))
submitted_run = mlflow.run(".", entrypoint, parameters=parameters)
return mlflow.tracking.MlflowClient().get_run(submitted_run.run_id)
@click.command()
@click.option("--als-max-iter", default=10, type=int)
@click.option("--keras-hidden-units", default=20, type=int)
@click.option("--max-row-limit", default=100000, type=int)
def workflow(als_max_iter, keras_hidden_units, max_row_limit):
# Note: The entrypoint names are defined in MLproject. The artifact directories
# are documented by each step's .py file.
with mlflow.start_run() as active_run:
os.environ['SPARK_CONF_DIR'] = os.path.abspath('.')
git_commit = active_run.data.tags.get(mlflow_tags.MLFLOW_GIT_COMMIT)
load_raw_data_run = _get_or_run("load_raw_data", {}, git_commit)
ratings_csv_uri = os.path.join(load_raw_data_run.info.artifact_uri, "ratings-csv-dir")
etl_data_run = _get_or_run("etl_data",
{"ratings_csv": ratings_csv_uri,
"max_row_limit": max_row_limit},
git_commit)
ratings_parquet_uri = os.path.join(etl_data_run.info.artifact_uri, "ratings-parquet-dir")
# We specify a spark-defaults.conf to override the default driver memory. ALS requires
# significant memory. The driver memory property cannot be set by the application itself.
als_run = _get_or_run("als",
{"ratings_data": ratings_parquet_uri, "max_iter": str(als_max_iter)},
git_commit)
als_model_uri = os.path.join(als_run.info.artifact_uri, "als-model")
keras_params = {
"ratings_data": ratings_parquet_uri,
"als_model_uri": als_model_uri,
"hidden_units": keras_hidden_units,
}
_get_or_run("train_keras", keras_params, git_commit, use_cache=False)
if __name__ == '__main__':
workflow()
|
[] |
[] |
[
"SPARK_CONF_DIR"
] |
[]
|
["SPARK_CONF_DIR"]
|
python
| 1 | 0 | |
src/run.py
|
import importlib
import os
import pickle
import sys
import hydra
import neptune
import numpy as np
import pandas as pd
from omegaconf import DictConfig
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold
sys.path.append('../utils')
from data_loader import load_datasets, load_target
from GCSOperator import GCSOperator
from logging_metrics import logging_classification
# global variable
NUM_FOLDS = 3
API_TOKEN = os.environ.get('NEPTUNE_API_TOKEN')
scoring = accuracy_score # evaluation metrics
def get_gcs_operator(config,
project_id=os.environ.get('GOOGLE_CLOUD_PROJECT')):
# setup GCS operator
bucket_name = config['bucket_name']
gcso = GCSOperator(project_id, bucket_name)
return gcso
def load_data(config, base_dir):
# load config
feats = config['features']
target_name = config['target_name']
cloud = config['cloud']
# load data
X_train_all, X_test = load_datasets(feats, base_dir=base_dir, cloud=cloud)
y_train_all = load_target(target_name, base_dir=base_dir, cloud=cloud)
return X_train_all, y_train_all, X_test
def train(X_train_all, y_train_all, X_test, module, config):
params = dict(config['model']['parameters'])
y_test_preds = []
oof_preds = []
scores = []
models = []
kf = StratifiedKFold(n_splits=NUM_FOLDS, shuffle=True, random_state=0)
for ind, (train_index,
valid_index) in enumerate(kf.split(X=X_train_all,
y=y_train_all)):
X_train, X_valid = (X_train_all.iloc[train_index, :],
X_train_all.iloc[valid_index, :])
y_train, y_valid = y_train_all[train_index], y_train_all[valid_index]
res = module.train_and_predict(X_train, X_valid, y_train, y_valid,
X_test, params, ind, scoring)
# for evaluation and stacking
if res['y_val_pred'].ndim > 1:
y_val_pred = np.argmax(res['y_val_pred'], axis=1)
else:
y_val_pred = res['y_val_pred']
oof_pred = pd.DataFrame([y_valid.index, y_val_pred]).T
oof_pred.columns = ['index', 'pred']
# save result
y_test_preds.append(res['y_test_pred'])
oof_preds.append(oof_pred)
models.append(res['model'])
scores.append(res['score'])
# logging result
logging_classification(y_valid, res['y_val_pred'])
return y_test_preds, oof_preds, models, scores
def save_models(models, config, base_dir):
gcso = get_gcs_operator(config)
print('***** Save models *****')
for ind, model in enumerate(models):
fname = f'{neptune.get_experiment().id}_model_{ind}.pkl'
fpath = os.path.join(base_dir, 'models', fname)
gcs_path = os.path.join('model', fname)
with open(fpath, mode='wb') as fp:
pickle.dump(model, fp)
# ここにクラウド用のを書く
gcso.upload_file(gcs_path, fpath)
def save_oof(oof_preds, config, base_dir):
gcso = get_gcs_operator(config)
print('***** Save oof *****')
# concat oof result and save
df_oof = pd.concat(oof_preds)
df_oof = df_oof.sort_values(by='index').reset_index(drop=True)
# for technical reason
df_temp = pd.DataFrame(df_oof['pred'])
df_temp.columns = [f'pred_{neptune.get_experiment().id}']
# save data
fname = f"features/valid_pred_{neptune.get_experiment().id}.feather"
df_temp.to_feather(os.path.join(base_dir, fname))
df_temp.to_feather(gcso.get_fullpath(fname))
def prepare_submission(y_test_preds, config, base_dir):
gcso = get_gcs_operator(config)
target_name = config['target_name']
print('***** Prepare submission *****')
# aggregate result
y_sub = sum(y_test_preds) / len(y_test_preds)
if y_sub.shape[1] > 1:
y_sub = np.argmax(y_sub, axis=1)
# prepare submit data
ID_name = config['ID_name']
sub = pd.DataFrame(
pd.read_csv(gcso.get_fullpath('data/input/test.csv'))[ID_name])
sub[target_name] = y_sub
sub.to_csv(os.path.join(
base_dir, f'data/output/test_pred_{neptune.get_experiment().id}.csv'),
index=False,
header=None)
@hydra.main(config_path='../config', config_name='config')
def main(config: DictConfig) -> None:
# set data
os.environ['GOOGLE_CLOUD_PROJECT'] = config['project_id']
params = dict(config['model']['parameters'])
# get base directory
base_dir = os.path.dirname(hydra.utils.get_original_cwd())
# load training API
module = importlib.import_module(config['model']['file'])
# load data
X_train_all, y_train_all, X_test = load_data(config, base_dir)
# start logging
neptune.init(api_token=API_TOKEN,
project_qualified_name='tokuma09/Example')
neptune.create_experiment(params=params,
name='sklearn-quick',
tags=[config['model']['name']])
# train model using CV
print('***** Train model *****')
y_test_preds, oof_preds, models, scores = train(X_train_all, y_train_all,
X_test, module, config)
# CV score
print('***** log CV score *****')
score = np.mean(scores)
neptune.log_metric('CV score', score)
for i in range(NUM_FOLDS):
neptune.log_metric('fold score', scores[i])
# save model
save_models(models, config, base_dir)
# save oof result
save_oof(oof_preds, config, base_dir)
# prepare submission
prepare_submission(y_test_preds, config, base_dir)
neptune.stop()
if __name__ == '__main__':
main()
|
[] |
[] |
[
"GOOGLE_CLOUD_PROJECT",
"NEPTUNE_API_TOKEN"
] |
[]
|
["GOOGLE_CLOUD_PROJECT", "NEPTUNE_API_TOKEN"]
|
python
| 2 | 0 | |
cvpack/torch_modeling/engine/engine.py
|
# encoding: utf-8
import os
import os.path as osp
import time
import argparse
import torch
import torch.distributed as dist
from collections import OrderedDict
from cvpack.utils.pyt_utils import (
parse_torch_devices, extant_file, link_file, ensure_dir)
from cvpack.utils.logger import get_logger
from .checkpoint import load_model
class State(object):
def __init__(self):
self.iteration = 0
self.model = None
self.optimizer = None
self.scheduler = None
def register(self, **kwargs):
for k, v in kwargs.items():
assert k in ['iteration', 'model', 'optimizer', 'scheduler']
setattr(self, k, v)
class Engine(object):
def __init__(self, cfg, custom_parser=None):
self.version = 0.1
self.state = State()
self.devices = None
self.distributed = False
self.logger = None
self.cfg = cfg
if custom_parser is None:
self.parser = argparse.ArgumentParser()
else:
assert isinstance(custom_parser, argparse.ArgumentParser)
self.parser = custom_parser
self.inject_default_parser()
self.args = self.parser.parse_args()
self.continue_state_object = self.args.continue_fpath
if 'WORLD_SIZE' in os.environ:
self.distributed = int(os.environ['WORLD_SIZE']) > 1
if self.distributed:
self.local_rank = self.args.local_rank
self.world_size = int(os.environ['WORLD_SIZE']) # nproc_per_node * node
# self.world_rank = int(os.environ['RANK'])
torch.cuda.set_device(self.local_rank)
dist_url = self.args.dist_url #'env://'
dist.init_process_group(backend="nccl", init_method=dist_url, world_size=self.world_size, rank=self.local_rank) # 'env://', rank=1, world_size=self.world_size
dist.barrier()
self.devices = [i for i in range(self.world_size)]
else:
self.local_rank = 0
self.devices = parse_torch_devices(self.args.devices)
def setup_log(self, name='train', log_dir=None, file_name=None):
if not self.logger:
self.logger = get_logger(
name, log_dir, self.args.local_rank, filename=file_name)
else:
self.logger.warning('already exists logger')
return self.logger
def inject_default_parser(self):
self.parser.add_argument(
'-d', '--devices', default='0',
help='set data parallel training')
self.parser.add_argument(
'-c', '--continue', type=extant_file, metavar="FILE",
dest="continue_fpath",
help='continue from one certain checkpoint')
self.parser.add_argument(
'--local_rank', default=0, type=int, # local ranking ?
help='process rank on node')
self.parser.add_argument('--dist_url',
default='tcp://127.0.0.1:23457',
type=str,
help='url used to set up distributed training')
def register_state(self, **kwargs):
self.state.register(**kwargs)
def update_iteration(self, iteration):
self.state.iteration = iteration
def save_checkpoint(self, path):
self.logger.info("Saving checkpoint to file {}".format(path))
t_start = time.time()
state_dict = {}
new_state_dict = OrderedDict()
for k, v in self.state.model.state_dict().items():
key = k
if k.split('.')[0] == 'module':
key = k[7:]
new_state_dict[key] = v
state_dict['model'] = new_state_dict
if self.state.optimizer:
state_dict['optimizer'] = self.state.optimizer.state_dict()
if self.state.scheduler:
state_dict['scheduler'] = self.state.scheduler.state_dict()
if self.state.iteration:
state_dict['iteration'] = self.state.iteration
t_io_begin = time.time()
torch.save(state_dict, path)
t_end = time.time()
del state_dict
del new_state_dict
self.logger.info(
"Save checkpoint to file {}, "
"Time usage:\n\tprepare snapshot: {}, IO: {}".format(
path, t_io_begin - t_start, t_end - t_io_begin))
def save_best_model(self, path):
self.logger.info("Saving best model to file {}".format(path))
t_start = time.time()
state_dict = {}
new_state_dict = OrderedDict()
for k, v in self.state.model.state_dict().items():
key = k
if k.split('.')[0] == 'module':
key = k[7:]
new_state_dict[key] = v
state_dict['model'] = new_state_dict
if self.state.optimizer:
state_dict['optimizer'] = self.state.optimizer.state_dict()
if self.state.scheduler:
state_dict['scheduler'] = self.state.scheduler.state_dict()
if self.state.iteration:
state_dict['iteration'] = self.state.iteration
t_io_begin = time.time()
torch.save(state_dict, path)
t_end = time.time()
del state_dict
del new_state_dict
self.logger.info(
"Save best model to file {}, "
"Time usage:\n\tprepare snapshot: {}, IO: {}".format(
path, t_io_begin - t_start, t_end - t_io_begin))
def load_checkpoint(self, weights, is_restore=False):
t_start = time.time()
if weights.endswith(".pkl"):
# for caffe2 model
from maskrcnn_benchmark.utils.c2_model_loading import \
load_c2_format
loaded = load_c2_format(self.cfg, weights)
else:
loaded = torch.load(weights, map_location=torch.device("cpu"))
t_io_end = time.time()
if "model" not in loaded:
loaded = dict(model=loaded)
self.state.model = load_model(
self.state.model, loaded['model'], self.logger,
is_restore=is_restore)
if "optimizer" in loaded:
self.state.optimizer.load_state_dict(loaded['optimizer'])
if "iteration" in loaded:
self.state.iteration = loaded['iteration']
if "scheduler" in loaded:
self.state.scheduler.load_state_dict(loaded["scheduler"])
del loaded
t_end = time.time()
self.logger.info(
"Load checkpoint from file {}, "
"Time usage:\n\tIO: {}, restore snapshot: {}".format(
weights, t_io_end - t_start, t_end - t_io_end))
def save_and_link_checkpoint(self, snapshot_dir):
ensure_dir(snapshot_dir)
current_iter_checkpoint = osp.join(
snapshot_dir, 'iter-{}.pth'.format(self.state.iteration))
self.save_checkpoint(current_iter_checkpoint)
last_iter_checkpoint = osp.join(
snapshot_dir, 'iter-last.pth')
link_file(current_iter_checkpoint, last_iter_checkpoint)
def restore_checkpoint(self, is_restore=True):
self.load_checkpoint(self.continue_state_object, is_restore=is_restore)
def __exit__(self, type, value, tb):
torch.cuda.empty_cache()
if type is not None:
self.logger.warning(
"A exception occurred during Engine initialization, "
"give up running process")
return False
def __enter__(self):
return self
|
[] |
[] |
[
"RANK",
"WORLD_SIZE"
] |
[]
|
["RANK", "WORLD_SIZE"]
|
python
| 2 | 0 | |
python/ciphers/cipher.py
|
# Copyright 2018 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import copy
class Cipher(object):
def copy(self): return copy.deepcopy(self)
def name(self):
return type(self).__name__
@property
def variant(self):
return self._variant
def _setup_variant(self):
pass
@variant.setter
def variant(self, value):
if value not in self.variants():
raise Exception(f"Not a variant: {value}")
self._variant = value
self._setup_variant()
def choose_variant(self, criterion):
for v in self.variants():
if criterion(v):
self.variant = v
return
raise Exception("No variant matching criterion")
def lengths(self):
return self.variant["lengths"]
def test_input_lengths(self):
yield self.lengths()
# External test vectors for this variant
def external_testvectors(self, tvdir):
if False:
yield None
def linux_name(self):
return self.name()
class Bijection(Cipher):
def make_testvector(self, input, description):
input = input.copy()
if "plaintext" in input:
pt = input["plaintext"]
del input["plaintext"]
ct = self.encrypt(pt, **input)
else:
ct = input["ciphertext"]
del input["ciphertext"]
pt = self.decrypt(ct, **input)
return {
"cipher": self.variant,
"description": description,
"input": input,
"plaintext": pt,
"ciphertext": ct,
}
def check_testvector(self, tv):
self.variant = tv["cipher"]
assert tv["ciphertext"] == self.encrypt(tv["plaintext"], **tv["input"])
assert tv["plaintext"] == self.decrypt(tv["ciphertext"], **tv["input"])
def linux_testvec_struct(self):
return 'cipher_testvec'
class Blockcipher(Bijection):
def test_input_lengths(self):
v = dict(self.lengths())
b = v['block']
del v['block']
for m in "plaintext", "ciphertext":
yield {**v, m: b}
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
bin/sentinel.py
|
#!/usr/bin/env python
import sys
import os
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../lib')))
import init
import config
import misc
from kzcashd import KZCashDaemon
from models import Superblock, Proposal, GovernanceObject, Watchdog
from models import VoteSignals, VoteOutcomes, Transient
import socket
from misc import printdbg
import time
from bitcoinrpc.authproxy import JSONRPCException
import signal
import atexit
import random
from scheduler import Scheduler
import argparse
# sync kzcashd gobject list with our local relational DB backend
def perform_kzcashd_object_sync(kzcashd):
GovernanceObject.sync(kzcashd)
# delete old watchdog objects, create new when necessary
def watchdog_check(kzcashd):
printdbg("in watchdog_check")
# delete expired watchdogs
for wd in Watchdog.expired(kzcashd):
printdbg("\tFound expired watchdog [%s], voting to delete" % wd.object_hash)
wd.vote(kzcashd, VoteSignals.delete, VoteOutcomes.yes)
# now, get all the active ones...
active_wd = Watchdog.active(kzcashd)
active_count = active_wd.count()
# none exist, submit a new one to the network
if 0 == active_count:
# create/submit one
printdbg("\tNo watchdogs exist... submitting new one.")
wd = Watchdog(created_at=int(time.time()))
wd.submit(kzcashd)
else:
wd_list = sorted(active_wd, key=lambda wd: wd.object_hash)
# highest hash wins
winner = wd_list.pop()
printdbg("\tFound winning watchdog [%s], voting VALID" % winner.object_hash)
winner.vote(kzcashd, VoteSignals.valid, VoteOutcomes.yes)
# if remaining Watchdogs exist in the list, vote delete
for wd in wd_list:
printdbg("\tFound losing watchdog [%s], voting DELETE" % wd.object_hash)
wd.vote(kzcashd, VoteSignals.delete, VoteOutcomes.yes)
printdbg("leaving watchdog_check")
def attempt_superblock_creation(kzcashd):
import kzcashlib
if not kzcashd.is_masternode():
print("We are not a Masternode... can't submit superblocks!")
return
# query votes for this specific ebh... if we have voted for this specific
# ebh, then it's voted on. since we track votes this is all done using joins
# against the votes table
#
# has this masternode voted on *any* superblocks at the given event_block_height?
# have we voted FUNDING=YES for a superblock for this specific event_block_height?
event_block_height = kzcashd.next_superblock_height()
if Superblock.is_voted_funding(event_block_height):
# printdbg("ALREADY VOTED! 'til next time!")
# vote down any new SBs because we've already chosen a winner
for sb in Superblock.at_height(event_block_height):
if not sb.voted_on(signal=VoteSignals.funding):
sb.vote(kzcashd, VoteSignals.funding, VoteOutcomes.no)
# now return, we're done
return
if not kzcashd.is_govobj_maturity_phase():
printdbg("Not in maturity phase yet -- will not attempt Superblock")
return
proposals = Proposal.approved_and_ranked(proposal_quorum=kzcashd.governance_quorum(), next_superblock_max_budget=kzcashd.next_superblock_max_budget())
budget_max = kzcashd.get_superblock_budget_allocation(event_block_height)
sb_epoch_time = kzcashd.block_height_to_epoch(event_block_height)
sb = kzcashlib.create_superblock(proposals, event_block_height, budget_max, sb_epoch_time)
if not sb:
printdbg("No superblock created, sorry. Returning.")
return
# find the deterministic SB w/highest object_hash in the DB
dbrec = Superblock.find_highest_deterministic(sb.hex_hash())
if dbrec:
dbrec.vote(kzcashd, VoteSignals.funding, VoteOutcomes.yes)
# any other blocks which match the sb_hash are duplicates, delete them
for sb in Superblock.select().where(Superblock.sb_hash == sb.hex_hash()):
if not sb.voted_on(signal=VoteSignals.funding):
sb.vote(kzcashd, VoteSignals.delete, VoteOutcomes.yes)
printdbg("VOTED FUNDING FOR SB! We're done here 'til next superblock cycle.")
return
else:
printdbg("The correct superblock wasn't found on the network...")
# if we are the elected masternode...
if (kzcashd.we_are_the_winner()):
printdbg("we are the winner! Submit SB to network")
sb.submit(kzcashd)
def check_object_validity(kzcashd):
# vote (in)valid objects
for gov_class in [Proposal, Superblock]:
for obj in gov_class.select():
obj.vote_validity(kzcashd)
def is_kzcashd_port_open(kzcashd):
# test socket open before beginning, display instructive message to MN
# operators if it's not
port_open = False
try:
info = kzcashd.rpc_command('getgovernanceinfo')
port_open = True
except (socket.error, JSONRPCException) as e:
print("%s" % e)
return port_open
def main():
kzcashd = KZCashDaemon.from_kzcash_conf(config.kzcash_conf)
options = process_args()
# check kzcashd connectivity
if not is_kzcashd_port_open(kzcashd):
print("Cannot connect to kzcashd. Please ensure kzcashd is running and the JSONRPC port is open to Sentinel.")
return
# check kzcashd sync
if not kzcashd.is_synced():
print("kzcashd not synced with network! Awaiting full sync before running Sentinel.")
return
# ensure valid masternode
if not kzcashd.is_masternode():
print("Invalid Masternode Status, cannot continue.")
return
# register a handler if SENTINEL_DEBUG is set
if os.environ.get('SENTINEL_DEBUG', None):
import logging
logger = logging.getLogger('peewee')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
if options.bypass:
# bypassing scheduler, remove the scheduled event
printdbg("--bypass-schedule option used, clearing schedule")
Scheduler.clear_schedule()
if not Scheduler.is_run_time():
printdbg("Not yet time for an object sync/vote, moving on.")
return
if not options.bypass:
# delay to account for cron minute sync
Scheduler.delay()
# running now, so remove the scheduled event
Scheduler.clear_schedule()
# ========================================================================
# general flow:
# ========================================================================
#
# load "gobject list" rpc command data, sync objects into internal database
perform_kzcashd_object_sync(kzcashd)
# delete old watchdog objects, create a new if necessary
watchdog_check(kzcashd)
# auto vote network objects as valid/invalid
# check_object_validity(kzcashd)
# create a Superblock if necessary
attempt_superblock_creation(kzcashd)
# schedule the next run
Scheduler.schedule_next_run()
def signal_handler(signum, frame):
print("Got a signal [%d], cleaning up..." % (signum))
Transient.delete('SENTINEL_RUNNING')
sys.exit(1)
def cleanup():
Transient.delete(mutex_key)
def process_args():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bypass-scheduler',
action='store_true',
help='Bypass scheduler and sync/vote immediately',
dest='bypass')
args = parser.parse_args()
return args
if __name__ == '__main__':
atexit.register(cleanup)
signal.signal(signal.SIGINT, signal_handler)
# ensure another instance of Sentinel is not currently running
mutex_key = 'SENTINEL_RUNNING'
# assume that all processes expire after 'timeout_seconds' seconds
timeout_seconds = 90
is_running = Transient.get(mutex_key)
if is_running:
printdbg("An instance of Sentinel is already running -- aborting.")
sys.exit(1)
else:
Transient.set(mutex_key, misc.now(), timeout_seconds)
# locked to this instance -- perform main logic here
main()
Transient.delete(mutex_key)
|
[] |
[] |
[
"SENTINEL_DEBUG"
] |
[]
|
["SENTINEL_DEBUG"]
|
python
| 1 | 0 | |
tests/commands/test_runner.py
|
import os
import subprocess
import sys
from ..base import BaseTestCase
def inject_sitecustomize(path):
"""Creates a new environment, injecting a ``sitecustomize.py`` module in
the current PYTHONPATH.
:param path: package path containing ``sitecustomize.py`` module, starting
from the ddtrace root folder
:returns: a cloned environment that includes an altered PYTHONPATH with
the given `sitecustomize.py`
"""
from ddtrace import __file__ as root_file
root_folder = os.path.dirname(root_file)
# Copy the current environment and replace the PYTHONPATH. This is
# required otherwise `ddtrace` scripts are not found when `env` kwarg is
# passed
env = os.environ.copy()
sitecustomize = os.path.join(root_folder, '..', path)
# Add `bootstrap` directory to the beginning of PYTHONTPATH so we know
# if `import sitecustomize` is run that it'll be the one we specify
python_path = [sitecustomize] + list(sys.path)
env['PYTHONPATH'] = ':'.join(python_path)
return env
class DdtraceRunTest(BaseTestCase):
def test_service_name_passthrough(self):
"""
$DATADOG_SERVICE_NAME gets passed through to the program
"""
with self.override_env(dict(DATADOG_SERVICE_NAME='my_test_service')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_service.py']
)
assert out.startswith(b'Test success')
def test_env_name_passthrough(self):
"""
$DATADOG_ENV gets passed through to the global tracer as an 'env' tag
"""
with self.override_env(dict(DATADOG_ENV='test')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_env.py']
)
assert out.startswith(b'Test success')
def test_env_enabling(self):
"""
DATADOG_TRACE_ENABLED=false allows disabling of the global tracer
"""
with self.override_env(dict(DATADOG_TRACE_ENABLED='false')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_disabled.py']
)
assert out.startswith(b'Test success')
with self.override_env(dict(DATADOG_TRACE_ENABLED='true')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_enabled.py']
)
assert out.startswith(b'Test success')
def test_patched_modules(self):
"""
Using `ddtrace-run` registers some generic patched modules
"""
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_patched_modules.py']
)
assert out.startswith(b'Test success')
def test_integration(self):
out = subprocess.check_output(
['ddtrace-run', 'python', '-m', 'tests.commands.ddtrace_run_integration']
)
assert out.startswith(b'Test success')
def test_debug_enabling(self):
"""
DATADOG_TRACE_DEBUG=true allows setting debug logging of the global tracer
"""
with self.override_env(dict(DATADOG_TRACE_DEBUG='false')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_no_debug.py']
)
assert out.startswith(b'Test success')
with self.override_env(dict(DATADOG_TRACE_DEBUG='true')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_debug.py']
)
assert out.startswith(b'Test success')
def test_host_port_from_env(self):
"""
DATADOG_TRACE_AGENT_HOSTNAME|PORT point to the tracer
to the correct host/port for submission
"""
with self.override_env(dict(DATADOG_TRACE_AGENT_HOSTNAME='172.10.0.1',
DATADOG_TRACE_AGENT_PORT='8120')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_hostname.py']
)
assert out.startswith(b'Test success')
def test_host_port_from_env_dd(self):
"""
DD_AGENT_HOST|DD_TRACE_AGENT_PORT point to the tracer
to the correct host/port for submission
"""
with self.override_env(dict(DD_AGENT_HOST='172.10.0.1',
DD_TRACE_AGENT_PORT='8120')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_hostname.py']
)
assert out.startswith(b'Test success')
# Do we get the same results without `ddtrace-run`?
out = subprocess.check_output(
['python', 'tests/commands/ddtrace_run_hostname.py']
)
assert out.startswith(b'Test success')
def test_dogstatsd_client_env_host_and_port(self):
"""
DD_AGENT_HOST and DD_DOGSTATSD_PORT used to configure dogstatsd with udp in tracer
"""
with self.override_env(dict(DD_AGENT_HOST='172.10.0.1',
DD_DOGSTATSD_PORT='8120')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_dogstatsd.py']
)
assert out.startswith(b'Test success')
def test_dogstatsd_client_env_url_host_and_port(self):
"""
DD_DOGSTATSD_URL=<host>:<port> used to configure dogstatsd with udp in tracer
"""
with self.override_env(dict(DD_DOGSTATSD_URL='172.10.0.1:8120')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_dogstatsd.py']
)
assert out.startswith(b'Test success')
def test_dogstatsd_client_env_url_udp(self):
"""
DD_DOGSTATSD_URL=udp://<host>:<port> used to configure dogstatsd with udp in tracer
"""
with self.override_env(dict(DD_DOGSTATSD_URL='udp://172.10.0.1:8120')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_dogstatsd.py']
)
assert out.startswith(b'Test success')
def test_dogstatsd_client_env_url_unix(self):
"""
DD_DOGSTATSD_URL=unix://<path> used to configure dogstatsd with socket path in tracer
"""
with self.override_env(dict(DD_DOGSTATSD_URL='unix:///dogstatsd.sock')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_dogstatsd.py']
)
assert out.startswith(b'Test success')
def test_dogstatsd_client_env_url_path(self):
"""
DD_DOGSTATSD_URL=<path> used to configure dogstatsd with socket path in tracer
"""
with self.override_env(dict(DD_DOGSTATSD_URL='/dogstatsd.sock')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_dogstatsd.py']
)
assert out.startswith(b'Test success')
def test_priority_sampling_from_env(self):
"""
DATADOG_PRIORITY_SAMPLING enables Distributed Sampling
"""
with self.override_env(dict(DATADOG_PRIORITY_SAMPLING='True')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_priority_sampling.py']
)
assert out.startswith(b'Test success')
def test_patch_modules_from_env(self):
"""
DATADOG_PATCH_MODULES overrides the defaults for patch_all()
"""
from ddtrace.bootstrap.sitecustomize import EXTRA_PATCHED_MODULES, update_patched_modules
orig = EXTRA_PATCHED_MODULES.copy()
# empty / malformed strings are no-ops
with self.override_env(dict(DATADOG_PATCH_MODULES='')):
update_patched_modules()
assert orig == EXTRA_PATCHED_MODULES
with self.override_env(dict(DATADOG_PATCH_MODULES=':')):
update_patched_modules()
assert orig == EXTRA_PATCHED_MODULES
with self.override_env(dict(DATADOG_PATCH_MODULES=',')):
update_patched_modules()
assert orig == EXTRA_PATCHED_MODULES
with self.override_env(dict(DATADOG_PATCH_MODULES=',:')):
update_patched_modules()
assert orig == EXTRA_PATCHED_MODULES
# overrides work in either direction
with self.override_env(dict(DATADOG_PATCH_MODULES='django:false')):
update_patched_modules()
assert EXTRA_PATCHED_MODULES['django'] is False
with self.override_env(dict(DATADOG_PATCH_MODULES='boto:true')):
update_patched_modules()
assert EXTRA_PATCHED_MODULES['boto'] is True
with self.override_env(dict(DATADOG_PATCH_MODULES='django:true,boto:false')):
update_patched_modules()
assert EXTRA_PATCHED_MODULES['boto'] is False
assert EXTRA_PATCHED_MODULES['django'] is True
with self.override_env(dict(DATADOG_PATCH_MODULES='django:false,boto:true')):
update_patched_modules()
assert EXTRA_PATCHED_MODULES['boto'] is True
assert EXTRA_PATCHED_MODULES['django'] is False
def test_sitecustomize_without_ddtrace_run_command(self):
# [Regression test]: ensure `sitecustomize` path is removed only if it's
# present otherwise it will cause:
# ValueError: list.remove(x): x not in list
# as mentioned here: https://github.com/DataDog/dd-trace-py/pull/516
env = inject_sitecustomize('')
out = subprocess.check_output(
['python', 'tests/commands/ddtrace_minimal.py'],
env=env,
)
# `out` contains the `loaded` status of the module
result = out[:-1] == b'True'
self.assertTrue(result)
def test_sitecustomize_run(self):
# [Regression test]: ensure users `sitecustomize.py` is properly loaded,
# so that our `bootstrap/sitecustomize.py` doesn't override the one
# defined in users' PYTHONPATH.
env = inject_sitecustomize('tests/commands/bootstrap')
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_sitecustomize.py'],
env=env,
)
assert out.startswith(b'Test success')
def test_sitecustomize_run_suppressed(self):
# ensure `sitecustomize.py` is not loaded if `-S` is used
env = inject_sitecustomize('tests/commands/bootstrap')
out = subprocess.check_output(
['ddtrace-run', 'python', '-S', 'tests/commands/ddtrace_run_sitecustomize.py', '-S'],
env=env,
)
assert out.startswith(b'Test success')
def test_argv_passed(self):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_argv.py', 'foo', 'bar']
)
assert out.startswith(b'Test success')
def test_got_app_name(self):
"""
apps run with ddtrace-run have a proper app name
"""
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_app_name.py']
)
assert out.startswith(b'ddtrace_run_app_name.py')
def test_global_trace_tags(self):
""" Ensure global tags are passed in from environment
"""
with self.override_env(dict(DD_TRACE_GLOBAL_TAGS='a:True,b:0,c:C')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_global_tags.py']
)
assert out.startswith(b'Test success')
def test_logs_injection(self):
""" Ensure logs injection works
"""
with self.override_env(dict(DD_LOGS_INJECTION='true')):
out = subprocess.check_output(
['ddtrace-run', 'python', 'tests/commands/ddtrace_run_logs_injection.py']
)
assert out.startswith(b'Test success')
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
pkg/network/render.go
|
package network
import (
"log"
"net"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/pkg/errors"
crclient "sigs.k8s.io/controller-runtime/pkg/client"
configv1 "github.com/openshift/api/config/v1"
operv1 "github.com/openshift/api/operator/v1"
"github.com/openshift/cluster-network-operator/pkg/bootstrap"
"github.com/openshift/cluster-network-operator/pkg/platform"
"github.com/openshift/cluster-network-operator/pkg/render"
iputil "github.com/openshift/cluster-network-operator/pkg/util/ip"
uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
utilnet "k8s.io/utils/net"
)
func Render(conf *operv1.NetworkSpec, bootstrapResult *bootstrap.BootstrapResult, manifestDir string) ([]*uns.Unstructured, error) {
log.Printf("Starting render phase")
objs := []*uns.Unstructured{}
// render cloud network config controller **before** the network plugin.
// the network plugin is dependent upon having the cloud network CRD
// defined as to initialize its watcher, otherwise it will error and crash
o, err := renderCloudNetworkConfigController(conf, bootstrapResult.Infra, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render Multus
o, err = renderMultus(conf, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render MultusAdmissionController
o, err = renderMultusAdmissionController(conf, manifestDir, bootstrapResult.Infra.ExternalControlPlane)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render MultiNetworkPolicy
o, err = renderMultiNetworkpolicy(conf, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render default network
o, err = renderDefaultNetwork(conf, bootstrapResult, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render kube-proxy
// DPU_DEV_PREVIEW
// There is currently a restriction that renderStandaloneKubeProxy() is
// called after renderDefaultNetwork(). The OVN-Kubernetes code is enabling
// KubeProxy in Node Mode of "dpu". Once out of DevPreview, CNO API will be
// expanded to include Node Mode and it will be stored in conf (operv1.NetworkSpec)
// and KubeProxy can read Node Mode and be enabled in KubeProxy code, removing this
// dependency.
o, err = renderStandaloneKubeProxy(conf, bootstrapResult, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render additional networks
o, err = renderAdditionalNetworks(conf, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
// render network diagnostics
o, err = renderNetworkDiagnostics(conf, manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
o, err = renderNetworkPublic(manifestDir)
if err != nil {
return nil, err
}
objs = append(objs, o...)
log.Printf("Render phase done, rendered %d objects", len(objs))
return objs, nil
}
// deprecatedCanonicalizeIPAMConfig converts configuration to a canonical form
// for backward compatibility.
func deprecatedCanonicalizeIPAMConfig(conf *operv1.IPAMConfig) {
switch strings.ToLower(string(conf.Type)) {
case strings.ToLower(string(operv1.IPAMTypeDHCP)):
conf.Type = operv1.IPAMTypeDHCP
case strings.ToLower(string(operv1.IPAMTypeStatic)):
conf.Type = operv1.IPAMTypeStatic
}
}
// deprecatedCanonicalizeSimpleMacvlanConfig converts configuration to a canonical form
// for backward compatibility.
func deprecatedCanonicalizeSimpleMacvlanConfig(conf *operv1.SimpleMacvlanConfig) {
switch strings.ToLower(string(conf.Mode)) {
case strings.ToLower(string(operv1.MacvlanModeBridge)):
conf.Mode = operv1.MacvlanModeBridge
case strings.ToLower(string(operv1.MacvlanModePrivate)):
conf.Mode = operv1.MacvlanModePrivate
case strings.ToLower(string(operv1.MacvlanModeVEPA)):
conf.Mode = operv1.MacvlanModeVEPA
case strings.ToLower(string(operv1.MacvlanModePassthru)):
conf.Mode = operv1.MacvlanModePassthru
}
if conf.IPAMConfig != nil {
deprecatedCanonicalizeIPAMConfig(conf.IPAMConfig)
}
}
// DeprecatedCanonicalize converts configuration to a canonical form for backward
// compatibility.
//
// *** DO NOT ADD ANY NEW CANONICALIZATION TO THIS FUNCTION! ***
//
// Altering the user-provided configuration from CNO causes problems when other components
// need to look at the configuration before CNO starts. Users should just write the
// configuration in the correct form to begin with.
//
// However, we cannot remove any of the existing canonicalizations because this might
// break existing clusters.
func DeprecatedCanonicalize(conf *operv1.NetworkSpec) {
orig := conf.DeepCopy()
switch strings.ToLower(string(conf.DefaultNetwork.Type)) {
case strings.ToLower(string(operv1.NetworkTypeOpenShiftSDN)):
conf.DefaultNetwork.Type = operv1.NetworkTypeOpenShiftSDN
case strings.ToLower(string(operv1.NetworkTypeOVNKubernetes)):
conf.DefaultNetwork.Type = operv1.NetworkTypeOVNKubernetes
}
if conf.DefaultNetwork.Type == operv1.NetworkTypeOpenShiftSDN &&
conf.DefaultNetwork.OpenShiftSDNConfig != nil {
sdnc := conf.DefaultNetwork.OpenShiftSDNConfig
switch strings.ToLower(string(sdnc.Mode)) {
case strings.ToLower(string(operv1.SDNModeMultitenant)):
sdnc.Mode = operv1.SDNModeMultitenant
case strings.ToLower(string(operv1.SDNModeNetworkPolicy)):
sdnc.Mode = operv1.SDNModeNetworkPolicy
case strings.ToLower(string(operv1.SDNModeSubnet)):
sdnc.Mode = operv1.SDNModeSubnet
}
}
for idx, an := range conf.AdditionalNetworks {
switch strings.ToLower(string(an.Type)) {
case strings.ToLower(string(operv1.NetworkTypeRaw)):
conf.AdditionalNetworks[idx].Type = operv1.NetworkTypeRaw
case strings.ToLower(string(operv1.NetworkTypeSimpleMacvlan)):
conf.AdditionalNetworks[idx].Type = operv1.NetworkTypeSimpleMacvlan
}
if an.Type == operv1.NetworkTypeSimpleMacvlan && an.SimpleMacvlanConfig != nil {
deprecatedCanonicalizeSimpleMacvlanConfig(conf.AdditionalNetworks[idx].SimpleMacvlanConfig)
}
}
if !reflect.DeepEqual(orig, conf) {
log.Printf("WARNING: One or more fields of Network.operator.openshift.io was incorrectly capitalized. Although this has been fixed now, it is possible that other components previously saw the incorrect value and interpreted it incorrectly.")
log.Printf("Original spec: %#v\nModified spec: %#v\n", orig, conf)
}
}
// Validate checks that the supplied configuration is reasonable.
// This should be called after Canonicalize
func Validate(conf *operv1.NetworkSpec) error {
errs := []error{}
errs = append(errs, validateIPPools(conf)...)
errs = append(errs, validateDefaultNetwork(conf)...)
errs = append(errs, validateMultus(conf)...)
errs = append(errs, validateKubeProxy(conf)...)
if len(errs) > 0 {
return errors.Errorf("invalid configuration: %v", errs)
}
return nil
}
// FillDefaults computes any default values and applies them to the configuration
// This is a mutating operation. It should be called after Validate.
//
// Defaults are carried forward from previous if it is provided. This is so we
// can change defaults as we move forward, but won't disrupt existing clusters.
//
// We may need to know the MTU of nodes in the cluster, so we can compute the correct
// underlay MTU (for OVN-K and OSDN).
func FillDefaults(conf, previous *operv1.NetworkSpec, hostMTU int) {
// DisableMultiNetwork defaults to false
if conf.DisableMultiNetwork == nil {
disable := false
conf.DisableMultiNetwork = &disable
}
// UseMultiNetworkPolicy defaults to false
if conf.UseMultiNetworkPolicy == nil {
disable := false
conf.UseMultiNetworkPolicy = &disable
}
if len(conf.LogLevel) == 0 {
conf.LogLevel = "Normal"
}
fillDefaultNetworkDefaults(conf, previous, hostMTU)
fillKubeProxyDefaults(conf, previous)
}
// IsChangeSafe checks to see if the change between prev and next are allowed
// FillDefaults and Validate should have been called, but beware that prev may
// be from an older version.
func IsChangeSafe(prev, next *operv1.NetworkSpec, client crclient.Client) error {
if prev == nil {
return nil
}
// Easy way out: nothing changed.
if reflect.DeepEqual(prev, next) {
return nil
}
// If for whatever reason it is not possible to get the platform type, fail
infraRes, err := platform.BootstrapInfra(client)
if err != nil {
return err
}
errs := []error{}
// Most ClusterNetworks/ServiceNetwork changes are not allowed
if err := isNetworkChangeSafe(prev, next, infraRes); err != nil {
errs = append(errs, err)
}
// Check the network migration
errs = append(errs, isMigrationChangeSafe(prev, next)...)
// Check the default network
errs = append(errs, isDefaultNetworkChangeSafe(prev, next)...)
// Changing AdditionalNetworks is supported
if !reflect.DeepEqual(prev.DisableMultiNetwork, next.DisableMultiNetwork) {
errs = append(errs, errors.Errorf("cannot change DisableMultiNetwork"))
}
// Check MultiNetworkPolicy
errs = append(errs, isMultiNetworkpolicyChangeSafe(prev, next)...)
// Check kube-proxy
errs = append(errs, isKubeProxyChangeSafe(prev, next)...)
if len(errs) > 0 {
return errors.Errorf("invalid configuration: %v", errs)
}
return nil
}
// NeedMTUProbe returns true if we need to probe the cluster's MTU.
// We need this if we don't have an MTU configured, either directly, or previously
// to "carry forward". If not, we'll have to probe it.
func NeedMTUProbe(prev, next *operv1.NetworkSpec) bool {
needsMTU := func(c *operv1.NetworkSpec) bool {
if c == nil {
return true
}
d := c.DefaultNetwork
switch d.Type {
case operv1.NetworkTypeOVNKubernetes:
return d.OVNKubernetesConfig == nil || d.OVNKubernetesConfig.MTU == nil || *d.OVNKubernetesConfig.MTU == 0
case operv1.NetworkTypeOpenShiftSDN:
return d.OpenShiftSDNConfig == nil || d.OpenShiftSDNConfig.MTU == nil || *d.OpenShiftSDNConfig.MTU == 0
}
// other network types don't need MTU
return false
}
return needsMTU(prev) && needsMTU(next)
}
func isNetworkChangeSafe(prev, next *operv1.NetworkSpec, infraRes *bootstrap.InfraBootstrapResult) error {
// Forbid changing service network during a migration
if prev.Migration != nil {
if !reflect.DeepEqual(prev.ServiceNetwork, next.ServiceNetwork) {
return errors.Errorf("cannot change ServiceNetwork during migration")
}
return nil
}
if reflect.DeepEqual(prev.ClusterNetwork, next.ClusterNetwork) && reflect.DeepEqual(prev.ServiceNetwork, next.ServiceNetwork) {
return nil
}
// Currently the only change we allow is switching to/from dual-stack.
// validateIPPools() will have ensured that each config is independently either
// a valid single-stack config or a valid dual-stack config. Make sure we have
// one of each.
var singleStack, dualStack *operv1.NetworkSpec
switch {
case len(prev.ServiceNetwork) < len(next.ServiceNetwork):
// Going from single to dual
singleStack, dualStack = prev, next
case len(prev.ServiceNetwork) > len(next.ServiceNetwork):
// Going from dual to single
dualStack, singleStack = prev, next
default:
// They didn't change single-vs-dual
if reflect.DeepEqual(prev.ServiceNetwork, next.ServiceNetwork) {
return errors.Errorf("unsupported change to ClusterNetwork")
} else {
return errors.Errorf("unsupported change to ServiceNetwork")
}
}
// Validate that this is either a BareMetal or None PlatformType. For all other
// PlatformTypes, migration to DualStack is prohibited
if len(prev.ServiceNetwork) < len(next.ServiceNetwork) {
if !isSupportedDualStackPlatform(infraRes.PlatformType) {
return errors.Errorf("DualStack deployments are allowed only for the BareMetal Platform type or the None Platform type")
}
}
// Validate that the shared ServiceNetwork entry is unchanged. (validateIPPools
// already checked that dualStack.ServiceNetwork[0] and [1] are of opposite IP
// families so we don't need to check that here.)
if singleStack.ServiceNetwork[0] != dualStack.ServiceNetwork[0] {
// User changed the primary service network, or tried to swap the order of
// the primary and secondary networks.
return errors.Errorf("cannot change primary ServiceNetwork when migrating to/from dual-stack")
}
// Validate that the shared ClusterNetwork entries are unchanged, and that ALL of
// the new ones in dualStack are of the opposite IP family from the shared ones.
// (ie, you cannot go from [ipv4] to [ipv4, ipv6, ipv4], even though the latter
// would have been valid as a new install.)
EntryZeroIsIPv6 := utilnet.IsIPv6CIDRString(singleStack.ClusterNetwork[0].CIDR)
for i := range dualStack.ClusterNetwork {
if i < len(singleStack.ClusterNetwork) {
if !reflect.DeepEqual(singleStack.ClusterNetwork[i], dualStack.ClusterNetwork[i]) {
// Changed or re-ordered an existing ClusterNetwork element
return errors.Errorf("cannot change primary ClusterNetwork when migrating to/from dual-stack")
}
} else if utilnet.IsIPv6CIDRString(dualStack.ClusterNetwork[i].CIDR) == EntryZeroIsIPv6 {
// Added a new element of the existing IP family
return errors.Errorf("cannot add additional ClusterNetwork values of original IP family when migrating to dual stack")
}
}
return nil
}
// validateIPPools checks that all IP addresses are valid
// TODO: check for overlap
func validateIPPools(conf *operv1.NetworkSpec) []error {
errs := []error{}
// Check all networks for overlaps
pool := iputil.IPPool{}
var ipv4Service, ipv6Service, ipv4Cluster, ipv6Cluster bool
// Validate ServiceNetwork values
for _, snet := range conf.ServiceNetwork {
_, cidr, err := net.ParseCIDR(snet)
if err != nil {
errs = append(errs, errors.Wrapf(err, "could not parse spec.serviceNetwork %s", snet))
continue
}
if utilnet.IsIPv6CIDR(cidr) {
ipv6Service = true
} else {
ipv4Service = true
}
if err := pool.Add(*cidr); err != nil {
errs = append(errs, err)
}
}
// Validate count / dual-stack-ness
if len(conf.ServiceNetwork) == 0 {
errs = append(errs, errors.Errorf("spec.serviceNetwork must have at least 1 entry"))
} else if len(conf.ServiceNetwork) == 2 && !(ipv4Service && ipv6Service) {
errs = append(errs, errors.Errorf("spec.serviceNetwork must contain at most one IPv4 and one IPv6 network"))
} else if len(conf.ServiceNetwork) > 2 {
errs = append(errs, errors.Errorf("spec.serviceNetwork must contain at most one IPv4 and one IPv6 network"))
}
// validate clusternetwork
// - has an entry
// - it is a valid ip
// - has a reasonable cidr
// - they do not overlap and do not overlap with the service cidr
for _, cnet := range conf.ClusterNetwork {
_, cidr, err := net.ParseCIDR(cnet.CIDR)
if err != nil {
errs = append(errs, errors.Errorf("could not parse spec.clusterNetwork %s", cnet.CIDR))
continue
}
if utilnet.IsIPv6CIDR(cidr) {
ipv6Cluster = true
} else {
ipv4Cluster = true
}
// ignore hostPrefix if the plugin does not use it and has it unset
if pluginsUsingHostPrefix.Has(string(conf.DefaultNetwork.Type)) || (cnet.HostPrefix != 0) {
ones, bits := cidr.Mask.Size()
// The comparison is inverted; smaller number is larger block
if cnet.HostPrefix < uint32(ones) {
errs = append(errs, errors.Errorf("hostPrefix %d is larger than its cidr %s",
cnet.HostPrefix, cnet.CIDR))
}
if int(cnet.HostPrefix) > bits-2 {
errs = append(errs, errors.Errorf("hostPrefix %d is too small, must be a /%d or larger",
cnet.HostPrefix, bits-2))
}
}
if err := pool.Add(*cidr); err != nil {
errs = append(errs, err)
}
}
if len(conf.ClusterNetwork) < 1 {
errs = append(errs, errors.Errorf("spec.clusterNetwork must have at least 1 entry"))
}
if len(errs) == 0 && (ipv4Cluster != ipv4Service || ipv6Cluster != ipv6Service) {
errs = append(errs, errors.Errorf("spec.clusterNetwork and spec.serviceNetwork must either both be IPv4-only, both be IPv6-only, or both be dual-stack"))
}
return errs
}
// validateMultus validates the combination of DisableMultiNetwork and AddtionalNetworks
func validateMultus(conf *operv1.NetworkSpec) []error {
// DisableMultiNetwork defaults to false
deployMultus := true
if conf.DisableMultiNetwork != nil && *conf.DisableMultiNetwork {
deployMultus = false
}
// Additional Networks are useless without Multus, so don't let them
// exist without Multus and confuse things (for now)
if !deployMultus && len(conf.AdditionalNetworks) > 0 {
return []error{errors.Errorf("additional networks cannot be specified without deploying Multus")}
}
return []error{}
}
// validateDefaultNetwork validates whichever network is specified
// as the default network.
func validateDefaultNetwork(conf *operv1.NetworkSpec) []error {
switch conf.DefaultNetwork.Type {
case operv1.NetworkTypeOpenShiftSDN:
return validateOpenShiftSDN(conf)
case operv1.NetworkTypeOVNKubernetes:
return validateOVNKubernetes(conf)
case operv1.NetworkTypeKuryr:
return validateKuryr(conf)
default:
return nil
}
}
// renderDefaultNetwork generates the manifests corresponding to the requested
// default network
func renderDefaultNetwork(conf *operv1.NetworkSpec, bootstrapResult *bootstrap.BootstrapResult, manifestDir string) ([]*uns.Unstructured, error) {
dn := conf.DefaultNetwork
if errs := validateDefaultNetwork(conf); len(errs) > 0 {
return nil, errors.Errorf("invalid Default Network configuration: %v", errs)
}
switch dn.Type {
case operv1.NetworkTypeOpenShiftSDN:
return renderOpenShiftSDN(conf, bootstrapResult, manifestDir)
case operv1.NetworkTypeOVNKubernetes:
return renderOVNKubernetes(conf, bootstrapResult, manifestDir)
case operv1.NetworkTypeKuryr:
return renderKuryr(conf, bootstrapResult, manifestDir)
default:
log.Printf("NOTICE: Unknown network type %s, ignoring", dn.Type)
return nil, nil
}
}
func fillDefaultNetworkDefaults(conf, previous *operv1.NetworkSpec, hostMTU int) {
switch conf.DefaultNetwork.Type {
case operv1.NetworkTypeOpenShiftSDN:
fillOpenShiftSDNDefaults(conf, previous, hostMTU)
case operv1.NetworkTypeOVNKubernetes:
fillOVNKubernetesDefaults(conf, previous, hostMTU)
case operv1.NetworkTypeKuryr:
fillKuryrDefaults(conf, previous)
default:
}
}
func isDefaultNetworkChangeSafe(prev, next *operv1.NetworkSpec) []error {
if prev.DefaultNetwork.Type != next.DefaultNetwork.Type {
if prev.Migration == nil {
return []error{errors.Errorf("cannot change default network type when not doing migration")}
} else {
if operv1.NetworkType(prev.Migration.NetworkType) != next.DefaultNetwork.Type {
return []error{errors.Errorf("can only change default network type to the target migration network type")}
}
}
}
if prev.Migration == nil || prev.Migration.NetworkType == "" {
switch prev.DefaultNetwork.Type {
case operv1.NetworkTypeOpenShiftSDN:
return isOpenShiftSDNChangeSafe(prev, next)
case operv1.NetworkTypeOVNKubernetes:
return isOVNKubernetesChangeSafe(prev, next)
case operv1.NetworkTypeKuryr:
return isKuryrChangeSafe(prev, next)
default:
return nil
}
}
return nil
}
func isMigrationChangeSafe(prev, next *operv1.NetworkSpec) []error {
if prev.Migration != nil && next.Migration != nil && prev.Migration.NetworkType != next.Migration.NetworkType {
return []error{errors.Errorf("cannot change migration network type after migration has started")}
}
return nil
}
// ValidateAdditionalNetworks validates additional networks configs
func validateAdditionalNetworks(conf *operv1.NetworkSpec) []error {
out := []error{}
ans := conf.AdditionalNetworks
for _, an := range ans {
switch an.Type {
case operv1.NetworkTypeRaw:
if errs := validateRaw(&an); len(errs) > 0 {
out = append(out, errs...)
}
case operv1.NetworkTypeSimpleMacvlan:
if errs := validateSimpleMacvlanConfig(&an); len(errs) > 0 {
out = append(out, errs...)
}
default:
out = append(out, errors.Errorf("unknown or unsupported NetworkType: %s", an.Type))
}
}
return out
}
// renderAdditionalNetworks generates the manifests of the requested additional networks
func renderAdditionalNetworks(conf *operv1.NetworkSpec, manifestDir string) ([]*uns.Unstructured, error) {
ans := conf.AdditionalNetworks
out := []*uns.Unstructured{}
// validate additional network configuration
if errs := validateAdditionalNetworks(conf); len(errs) > 0 {
return nil, errors.Errorf("invalid Additional Network Configuration: %v", errs)
}
if len(ans) == 0 {
return nil, nil
}
// render additional network configuration
for _, an := range ans {
switch an.Type {
case operv1.NetworkTypeRaw:
objs, err := renderRawCNIConfig(&an, manifestDir)
if err != nil {
return nil, err
}
out = append(out, objs...)
case operv1.NetworkTypeSimpleMacvlan:
objs, err := renderSimpleMacvlanConfig(&an, manifestDir)
if err != nil {
return nil, err
}
out = append(out, objs...)
default:
return nil, errors.Errorf("unknown or unsupported NetworkType: %s", an.Type)
}
}
return out, nil
}
// renderMultusAdmissionController generates the manifests of Multus Admission Controller
func renderMultusAdmissionController(conf *operv1.NetworkSpec, manifestDir string, externalControlPlane bool) ([]*uns.Unstructured, error) {
if *conf.DisableMultiNetwork {
return nil, nil
}
var err error
out := []*uns.Unstructured{}
objs, err := renderMultusAdmissonControllerConfig(manifestDir, externalControlPlane)
if err != nil {
return nil, err
}
out = append(out, objs...)
return out, nil
}
// renderMultiNetworkpolicy generates the manifests of MultiNetworkPolicy
func renderMultiNetworkpolicy(conf *operv1.NetworkSpec, manifestDir string) ([]*uns.Unstructured, error) {
// disable it if DisableMultiNetwork = true
if *conf.DisableMultiNetwork {
return nil, nil
}
if conf.UseMultiNetworkPolicy == nil || !*conf.UseMultiNetworkPolicy {
return nil, nil
}
var err error
out := []*uns.Unstructured{}
objs, err := renderMultiNetworkpolicyConfig(manifestDir)
if err != nil {
return nil, err
}
out = append(out, objs...)
return out, nil
}
// renderNetworkDiagnostics renders the connectivity checks
func renderNetworkDiagnostics(conf *operv1.NetworkSpec, manifestDir string) ([]*uns.Unstructured, error) {
if conf.DisableNetworkDiagnostics {
return nil, nil
}
data := render.MakeRenderData()
data.Data["ReleaseVersion"] = os.Getenv("RELEASE_VERSION")
data.Data["NetworkCheckSourceImage"] = os.Getenv("NETWORK_CHECK_SOURCE_IMAGE")
data.Data["NetworkCheckTargetImage"] = os.Getenv("NETWORK_CHECK_TARGET_IMAGE")
manifests, err := render.RenderDir(filepath.Join(manifestDir, "network-diagnostics"), &data)
if err != nil {
return nil, errors.Wrap(err, "failed to render network-diagnostics manifests")
}
return manifests, nil
}
// renderNetworkPublic renders the common objects related to the openshift-network-features configmap
func renderNetworkPublic(manifestDir string) ([]*uns.Unstructured, error) {
data := render.MakeRenderData()
manifests, err := render.RenderDir(filepath.Join(manifestDir, "network", "public"), &data)
if err != nil {
return nil, errors.Wrap(err, "failed to render network/public manifests")
}
return manifests, nil
}
func isSupportedDualStackPlatform(platformType configv1.PlatformType) bool {
return platformType == configv1.BareMetalPlatformType || platformType == configv1.NonePlatformType
}
|
[
"\"RELEASE_VERSION\"",
"\"NETWORK_CHECK_SOURCE_IMAGE\"",
"\"NETWORK_CHECK_TARGET_IMAGE\""
] |
[] |
[
"NETWORK_CHECK_SOURCE_IMAGE",
"NETWORK_CHECK_TARGET_IMAGE",
"RELEASE_VERSION"
] |
[]
|
["NETWORK_CHECK_SOURCE_IMAGE", "NETWORK_CHECK_TARGET_IMAGE", "RELEASE_VERSION"]
|
go
| 3 | 0 | |
main.py
|
# -*- coding: utf-8 -*-
import json
import os
import api_controller
import rest
def get_api_controller():
bucket_name = os.environ.get("BUCKET_NAME")
region_name = os.environ.get("REGION_NAME")
return api_controller.ApiController(bucket_name, region_name)
def format_response(status_code, content_type, body):
is_binary = any(prefix in content_type for prefix in ["image", "video", "audio"])
return {
"statusCode": status_code,
"headers": {"Content-Type": content_type},
"isBase64Encoded": is_binary,
"body": body if is_binary else json.dumps(body)
}
def dispatch_event_to_api_controller(event):
resource = event.get("resource")
if not rest.route_is_defined(resource):
return format_response(400,
"application/json",
{"message": f"No controller function defined to handle resource '{resource}'"})
api = get_api_controller()
path_params = event.get("pathParameters") or dict()
(content_type, body) = rest.dispatch(resource, api, **path_params)
return format_response(200, content_type, body)
def handler(event, context):
return dispatch_event_to_api_controller(event)
if __name__ == "__main__":
print("This lambda function cannot be executed directly. Please use the 'lambda invoke' command to run this "
"function.")
|
[] |
[] |
[
"REGION_NAME",
"BUCKET_NAME"
] |
[]
|
["REGION_NAME", "BUCKET_NAME"]
|
python
| 2 | 0 | |
cmd/irestore/irestore.go
|
package main
import (
"encoding/binary"
"encoding/json"
"strconv"
"text/tabwriter"
"time"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"crypto/aes"
"github.com/chiefbrain/ios/backup"
"github.com/chiefbrain/ios/crypto/aeswrap"
"github.com/chiefbrain/ios/crypto/gcm"
"github.com/chiefbrain/ios/encoding/asn1"
"github.com/dunhamsteve/plist"
"golang.org/x/crypto/ssh/terminal"
)
// Quick and Dirty error handling - when I don't expect an error, but want to know if it happens
func must(err error) {
if err != nil {
log.Fatal(err)
}
}
func dumpJSON(x interface{}) {
json, err := json.MarshalIndent(x, "", " ")
must(err)
fmt.Println(string(json))
}
func getpass() string {
fmt.Fprint(os.Stderr, "Backup Password: ")
pw, err := terminal.ReadPassword(0)
must(err)
fmt.Println()
return string(pw)
}
func domains(db *backup.MobileBackup) {
for _, domain := range db.Domains() {
fmt.Println(domain)
}
}
func apps(db *backup.MobileBackup) {
for app := range db.Manifest.Applications {
fmt.Println(app)
}
}
func list(db *backup.MobileBackup, domain string) {
for _, rec := range db.Records {
// just files for now
if rec.Length > 0 {
if domain == "*" {
fmt.Println(rec.Domain, rec.Path)
} else if domain == rec.Domain {
fmt.Println(rec.Path)
}
}
}
}
type KCEntry struct {
Data []byte `plist:"v_Data"`
Ref []byte `plist:"v_PersistentRef"`
}
type Keychain struct {
Internet []KCEntry `plist:"inet"`
General []KCEntry `plist:"genp"`
Certs []KCEntry `plist:"cert"`
Keys []KCEntry `plist:"keys"`
}
var le = binary.LittleEndian
// Mostly works, but I don't think time is getting populated.
type Entry struct {
Raw asn1.RawContent
Key string
Value interface{}
}
type DateEntry struct {
Key string
Time time.Time
}
type EntrySET []Entry
func parseRecord(data []byte) map[string]interface{} {
var v EntrySET
rval := make(map[string]interface{})
_, err := asn1.Unmarshal(data, &v)
if err != nil {
fmt.Println(err)
ioutil.WriteFile("failed.bin", data, 0644)
}
// must(err)
for _, entry := range v {
// Time values come through as nil, so we try again with a "DateEntry" structure.
if entry.Value == nil {
var entry2 DateEntry
_, err := asn1.Unmarshal(entry.Raw, &entry2)
if err == nil {
entry.Value = entry2.Time
}
}
rval[entry.Key] = entry.Value
}
return rval
}
func dumpKeyGroup(db *backup.MobileBackup, group []KCEntry) []interface{} {
var rval []interface{}
for _, key := range group {
version := le.Uint32(key.Data)
class := le.Uint32(key.Data[4:])
switch version {
case 3:
l := le.Uint32(key.Data[8:])
wkey := key.Data[12 : 12+l]
edata := key.Data[12+l:]
// Find key for class
ckey := db.Keybag.GetClassKey(class)
if ckey == nil {
fmt.Println("No key for class", class, string(key.Ref)[:4], key.Ref[4:])
continue
}
key := aeswrap.Unwrap(ckey, wkey)
if key == nil {
fmt.Println("unwrap failed for class", class)
continue
}
// Create a gcm cipher
c, err := aes.NewCipher(key)
if err != nil {
log.Panic(err)
}
gcm, err := gcm.NewGCM(c)
if err != nil {
log.Panic(err)
}
plain, err := gcm.Open(nil, nil, edata, nil)
must(err)
record := parseRecord(plain)
rval = append(rval, record)
default:
panic(fmt.Sprintf("Unhandled keychain blob version %d", version))
}
}
return rval
}
func dumpkeys(db *backup.MobileBackup, outfile string) {
for _, rec := range db.Records {
if rec.Domain == "KeychainDomain" && rec.Path == "keychain-backup.plist" {
fmt.Println(rec)
data, err := db.ReadFile(rec)
must(err)
ioutil.WriteFile("kcb.plist", data, 0x644)
fmt.Println("read", len(data))
var v Keychain
err = plist.Unmarshal(bytes.NewReader(data), &v)
must(err)
dump := make(map[string][]interface{})
dump["General"] = dumpKeyGroup(db, v.General)
dump["Internet"] = dumpKeyGroup(db, v.Internet)
dump["Certs"] = dumpKeyGroup(db, v.Certs)
dump["Keys"] = dumpKeyGroup(db, v.Keys)
s, err := json.MarshalIndent(dump, "", " ")
must(err)
if outfile != "" {
err = ioutil.WriteFile(outfile, s, 0644)
must(err)
} else {
_, err = os.Stdout.Write(s)
must(err)
}
}
}
}
func restore(db *backup.MobileBackup, domain string, dest string) {
var err error
var total int64
for _, rec := range db.Records {
if rec.Length > 0 {
var outPath string
if domain == "*" {
outPath = path.Join(dest, rec.Domain, rec.Path)
} else if rec.Domain == domain {
outPath = path.Join(dest, rec.Path)
}
if outPath != "" {
fmt.Println(rec.Path)
dir := path.Dir(outPath)
err = os.MkdirAll(dir, 0755)
must(err)
r, err := db.FileReader(rec)
if err != nil {
log.Println("error reading file", rec, err)
continue
}
must(err)
w, err := os.Create(outPath)
must(err)
n, err := io.Copy(w, r)
total += n
r.Close()
w.Close()
err = os.Chtimes(outPath, time.Unix(int64(rec.Atime), 0), time.Unix(int64(rec.Mtime), 0))
if err != nil {
log.Println("error setting the last modification times for file", rec, err)
// this is a non-fatal error, so no need to `continue`
}
}
}
}
fmt.Println("Wrote", total, "bytes")
}
// exists returns whether the given file or directory exists or not
func exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
func main() {
pathToBackupsPtr := flag.String("path", path.Join(os.Getenv("HOME"), "Library/Application Support/MobileSync/Backup"), "path to dir where backups are stored")
flag.Parse()
mm, err := backup.Enumerate(*pathToBackupsPtr)
must(err)
var selected *backup.Backup
// component without flag is udid
if len(flag.Args()) >= 1 {
key := flag.Args()[0]
for _, man := range mm {
dashed := strings.Contains(man.FileName, "-")
if man.DeviceName == key && !dashed {
selected = &man
break
}
if man.FileName == key {
selected = &man
break
}
if strings.Contains(man.DeviceName, key) && !dashed {
selected = &man
break
}
if strings.Contains(man.FileName, key) && !dashed {
selected = &man
break
}
}
}
if selected == nil {
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 2, '\t', 0)
fmt.Fprintln(w, "Device Name\tFile Name\tDate\tVersion\tDevice\tEncrypted")
fmt.Fprintln(w, "===========\t=========\t====\t=======\t======\t=========")
for _, man := range mm {
fmt.Fprintln(w, man.DeviceName+
"\t"+man.FileName+
"\t"+man.Date.String()+
"\t"+man.Version+
"\t"+man.Device+
"\t"+strconv.FormatBool(man.Encrypted))
}
w.Flush()
return
}
fmt.Println("Selected", selected.DeviceName, selected.FileName)
db, err := backup.Open(*pathToBackupsPtr, selected.FileName)
must(err)
if db.Manifest.IsEncrypted {
err = db.SetPassword(getpass())
must(err)
}
must(db.Load())
if len(flag.Args()) < 2 {
for _, domain := range db.Domains() {
fmt.Println(domain)
}
return
}
name := filepath.Base(os.Args[0])
help := func() {
fmt.Printf(`Usage:
%v [-path PATH] deviceID/deviceName ls [domain]
%v [-path PATH] deviceID/deviceName restore domain dest
%v [-path PATH] deviceID/deviceName dumpkeys [outputfile]
%v [-path PATH] deviceID/deviceName apps
`, name, name, name, name)
}
var cmd string
if len(flag.Args()) > 1 {
cmd = flag.Args()[1]
}
switch cmd {
case "ls", "list":
if len(flag.Args()) > 2 {
list(db, flag.Args()[2])
} else {
domains(db)
}
case "restore":
if len(flag.Args()) > 3 {
restore(db, flag.Args()[2], flag.Args()[3])
} else {
help()
}
case "apps":
apps(db)
case "dumpkeys":
var out string
if len(flag.Args()) > 2 {
out = flag.Args()[2]
}
dumpkeys(db, out)
default:
help()
}
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
cntrl/main.go
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/google/uuid"
)
var adaptEndpoint string = fmt.Sprintf("http://%s:%s/prodcntrl", os.Getenv("ADAPT_IP"), os.Getenv("ADAPT_PORT"))
// standard production rate
const rate = 100
// update interval in milliseconds
const interval int = 100
func update(queue <-chan struct{}) {
// update the world every 100 milliseconds
ticker := time.NewTicker(time.Duration(interval) * time.Millisecond)
discarded := 0
for {
select {
case <-queue:
discarded++
case <-ticker.C:
go func() {
// send rate - discarded
curr := (rate * (interval / 1000)) - discarded
id, err := uuid.NewRandom()
if err != nil {
log.Print(err)
return
}
type ProdCntrlData struct {
ProdRate int `json:"prod_rate"`
UUID string `json:"uuid"`
}
data, err := json.Marshal(ProdCntrlData{
ProdRate: curr,
UUID: id.String(),
})
if err != nil {
return
}
log.Printf("send,prodctrl,%s,%s", id.String(), strconv.FormatInt(time.Now().UnixNano(), 10))
req, err := http.NewRequest("POST", adaptEndpoint, bytes.NewReader(data))
if err != nil {
return
}
_, err = (&http.Client{}).Do(req)
if err != nil {
log.Print(err)
}
}()
}
}
}
func main() {
discardqueue := make(chan struct{})
type Request struct {
UUID string `json:"uuid"`
}
http.HandleFunc("/discard", func(w http.ResponseWriter, r *http.Request) {
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
var data Request
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
return
}
log.Printf("recv,discard,%s,%s", data.UUID, timestamp)
discardqueue <- struct{}{}
})
go update(discardqueue)
log.Fatal(http.ListenAndServe(":"+os.Getenv("CNTRL_PORT"), nil))
}
|
[
"\"ADAPT_IP\"",
"\"ADAPT_PORT\"",
"\"CNTRL_PORT\""
] |
[] |
[
"ADAPT_PORT",
"CNTRL_PORT",
"ADAPT_IP"
] |
[]
|
["ADAPT_PORT", "CNTRL_PORT", "ADAPT_IP"]
|
go
| 3 | 0 | |
server/server_test.go
|
package server_test
import (
"bytes"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"net/mail"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
jwt "github.com/golang-jwt/jwt"
"github.com/google/go-cmp/cmp"
"github.com/influxdata/flux/fluxinit"
iclient "github.com/influxdata/influxdb/client/v2"
"github.com/influxdata/influxdb/influxql"
imodels "github.com/influxdata/influxdb/models"
"github.com/influxdata/influxdb/toml"
"github.com/influxdata/kapacitor/alert"
"github.com/influxdata/kapacitor/client/v1"
"github.com/influxdata/kapacitor/command"
"github.com/influxdata/kapacitor/command/commandtest"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/server"
"github.com/influxdata/kapacitor/services/alert/alerttest"
"github.com/influxdata/kapacitor/services/alerta/alertatest"
"github.com/influxdata/kapacitor/services/auth"
"github.com/influxdata/kapacitor/services/auth/meta"
"github.com/influxdata/kapacitor/services/bigpanda/bigpandatest"
"github.com/influxdata/kapacitor/services/discord/discordtest"
"github.com/influxdata/kapacitor/services/hipchat/hipchattest"
"github.com/influxdata/kapacitor/services/httppost"
"github.com/influxdata/kapacitor/services/httppost/httpposttest"
"github.com/influxdata/kapacitor/services/k8s"
"github.com/influxdata/kapacitor/services/kafka"
"github.com/influxdata/kapacitor/services/kafka/kafkatest"
"github.com/influxdata/kapacitor/services/mqtt"
"github.com/influxdata/kapacitor/services/mqtt/mqtttest"
"github.com/influxdata/kapacitor/services/opsgenie"
"github.com/influxdata/kapacitor/services/opsgenie/opsgenietest"
"github.com/influxdata/kapacitor/services/opsgenie2/opsgenie2test"
"github.com/influxdata/kapacitor/services/pagerduty"
"github.com/influxdata/kapacitor/services/pagerduty/pagerdutytest"
"github.com/influxdata/kapacitor/services/pagerduty2"
"github.com/influxdata/kapacitor/services/pagerduty2/pagerduty2test"
"github.com/influxdata/kapacitor/services/pushover/pushovertest"
"github.com/influxdata/kapacitor/services/sensu/sensutest"
"github.com/influxdata/kapacitor/services/servicenow"
"github.com/influxdata/kapacitor/services/servicenow/servicenowtest"
"github.com/influxdata/kapacitor/services/slack"
"github.com/influxdata/kapacitor/services/slack/slacktest"
"github.com/influxdata/kapacitor/services/smtp/smtptest"
"github.com/influxdata/kapacitor/services/snmptrap/snmptraptest"
"github.com/influxdata/kapacitor/services/swarm"
"github.com/influxdata/kapacitor/services/talk/talktest"
"github.com/influxdata/kapacitor/services/teams"
"github.com/influxdata/kapacitor/services/teams/teamstest"
"github.com/influxdata/kapacitor/services/telegram"
"github.com/influxdata/kapacitor/services/telegram/telegramtest"
"github.com/influxdata/kapacitor/services/udf"
"github.com/influxdata/kapacitor/services/victorops"
"github.com/influxdata/kapacitor/services/victorops/victoropstest"
"github.com/influxdata/kapacitor/services/zenoss"
"github.com/influxdata/kapacitor/services/zenoss/zenosstest"
"github.com/k-sone/snmpgo"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)
var udfDir string
func init() {
dir, _ := os.Getwd()
udfDir = filepath.Clean(filepath.Join(dir, "../udf"))
fluxinit.FluxInit()
}
func mustHash(hash []byte, err error) string {
if err != nil {
panic(err)
}
return string(hash)
}
func TestService_Authenticate(t *testing.T) {
type Users struct {
Users []meta.User `json:"users"`
}
newUsers := func(u ...meta.User) Users {
return Users{
Users: u,
}
}
cases := []struct {
name string
userResult Users
authorizedStatus int
shouldErr bool
userName string
password string
}{{
name: "ok",
userResult: newUsers(meta.User{
Name: "fred",
Hash: mustHash(bcrypt.GenerateFromPassword([]byte(`fred_pw`), auth.NewEnabledConfig().BcryptCost)),
Permissions: map[string][]meta.Permission{"": {meta.KapacitorAPIPermission}},
}),
authorizedStatus: http.StatusOK,
shouldErr: false,
userName: `fred`,
password: `fred_pw`,
},
{
name: "ldap badpass",
userResult: newUsers(meta.User{
Name: "fred2",
Hash: "",
Permissions: map[string][]meta.Permission{"": {meta.KapacitorAPIPermission}},
}),
authorizedStatus: http.StatusUnauthorized,
shouldErr: true,
userName: `fred2`,
password: `badpass`,
},
{
name: "ldap ok",
userResult: newUsers(meta.User{
Name: "fred3",
Hash: "",
Permissions: map[string][]meta.Permission{"": {meta.KapacitorAPIPermission}},
}),
authorizedStatus: http.StatusOK,
shouldErr: false,
userName: `fred3`,
password: `fred_pw`,
},
{
name: "user dos not exist",
userResult: newUsers(meta.User{}),
authorizedStatus: http.StatusNotFound,
shouldErr: true,
userName: `fred_not_exists`,
password: `fred_pw`,
},
}
for _, testCase := range cases {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/user":
if err := json.NewEncoder(w).Encode(testCase.userResult); err != nil {
t.Error("bad encoding for testCase.userResult")
}
//w.Write(testCase.userResult)
case "/authorized":
w.WriteHeader(testCase.authorizedStatus)
default:
t.Errorf("bad path %s", r.URL.Path)
}
}))
defer srv.Close()
c := NewConfig()
c.Auth = auth.NewEnabledConfig()
kserver := OpenServer(c)
url, err := url.Parse(srv.URL)
if err != nil {
t.Fatal(err)
}
kserver.Config.Auth.MetaAddr = url.Host
kserver.Restart()
defer kserver.Close()
_, err = kserver.AuthService.Authenticate(testCase.userName, testCase.password)
if (err != nil) != testCase.shouldErr {
if err == nil {
t.Log("expected an error but it didn't")
}
if err != nil {
t.Logf("expected no error but got %s", err.Error())
}
t.FailNow()
}
})
}
}
func TestServer_Ping(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
_, version, err := cli.Ping()
if err != nil {
t.Fatal(err)
}
if version != "testServer" {
t.Fatal("unexpected version", version)
}
}
func TestServer_Pprof_Index(t *testing.T) {
s, _ := OpenDefaultServer()
defer s.Close()
testCases := []struct {
path string
code int
contentType string
}{
{
path: "/debug/pprof/",
code: http.StatusOK,
contentType: "text/html; charset=utf-8",
},
{
path: "/debug/pprof/block",
code: http.StatusOK,
contentType: "application/octet-stream",
},
{
path: "/debug/pprof/goroutine",
code: http.StatusOK,
contentType: "application/octet-stream",
},
{
path: "/debug/pprof/heap",
code: http.StatusOK,
contentType: "application/octet-stream",
},
{
path: "/debug/pprof/threadcreate",
code: http.StatusOK,
contentType: "application/octet-stream",
},
}
for _, tc := range testCases {
t.Run(tc.path, func(t *testing.T) {
r, err := http.Get(s.URL() + tc.path)
if err != nil {
t.Fatal(err)
}
if got, exp := r.StatusCode, tc.code; got != exp {
t.Errorf("unexpected status code got %d exp %d", got, exp)
}
if got, exp := r.Header.Get("Content-Type"), tc.contentType; got != exp {
t.Errorf("unexpected content type got %s exp %s", got, exp)
}
})
}
}
func TestServer_Authenticate_Fail(t *testing.T) {
conf := NewConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
cli, err := client.New(client.Config{
URL: s.URL(),
})
if err != nil {
t.Fatal(err)
}
defer s.Close()
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "unable to parse authentication credentials", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_User(t *testing.T) {
conf := NewConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "bob",
Password: "bob's secure password",
},
})
if err != nil {
t.Fatal(err)
}
defer s.Close()
_, version, err := cli.Ping()
if err != nil {
t.Fatal(err)
}
if version != "testServer" {
t.Fatal("unexpected version", version)
}
}
func TestServer_Authenticate_Bearer_Fail(t *testing.T) {
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(10 * time.Second).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.HTTP.AuthEnabled = true
// Use a different secret so the token is invalid
conf.HTTP.SharedSecret = secret + "extra secret"
s := OpenServer(conf)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
})
if err != nil {
t.Fatal(err)
}
defer s.Close()
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "invalid token: signature is invalid", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_Bearer_Expired(t *testing.T) {
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(-10 * time.Second).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.HTTP.AuthEnabled = true
conf.HTTP.SharedSecret = secret
s := OpenServer(conf)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
})
if err != nil {
t.Fatal(err)
}
defer s.Close()
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "invalid token: Token is expired", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_Bearer(t *testing.T) {
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(10 * time.Second).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.HTTP.AuthEnabled = true
conf.HTTP.SharedSecret = secret
s := OpenServer(conf)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
})
if err != nil {
t.Fatal(err)
}
defer s.Close()
_, version, err := cli.Ping()
if err != nil {
t.Fatal(err)
}
if version != "testServer" {
t.Fatal("unexpected version", version)
}
}
func TestServer_CreateUser(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
username := "bob"
utype := client.NormalUser
permissions := []client.Permission{
client.APIPermission,
}
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: "hunter2",
Type: utype,
Permissions: permissions,
})
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
user, err = cli.User(user.Link)
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
}
func TestServer_CreateTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_CreateTask_Quiet(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
.quiet()
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_CreateTaskImplicitStream(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `dbrp "mydb"."myrp"
dbrp "otherdb"."default"
stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_CreateTaskBatch(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `dbrp "mydb"."myrp"
batch
|query('SELECT * from mydb.myrp.mymeas')
|log()
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.BatchTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.BatchTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nquery1 -> log2;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_CreateTaskImplicitAndExplicit(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `dbrp "mydb"."myrp"
dbrp "otherdb"."default"
stream
|from()
.measurement('test')
`
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
// It is expected that error should be non nil
if err == nil {
t.Fatal("expected task to fail to be created")
}
}
func TestServer_CreateTaskExplicitUpdateImplicit(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
createDBRPs := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
createTick := `stream
|from()
.measurement('test')
`
updateDBRPs := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
updateTick := `dbrp "mydb"."myrp"
stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
DBRPs: createDBRPs,
TICKscript: createTick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, createDBRPs) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, createDBRPs)
}
if ti.TICKscript != createTick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, createTick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
TICKscript: updateTick,
})
if err != nil {
t.Fatal(err)
}
ti, err = cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, updateDBRPs) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, updateDBRPs)
}
if ti.TICKscript != updateTick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, updateTick)
}
dot = "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_EnableTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Enabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Enabled)
}
if ti.Executing != true {
t.Fatalf("unexpected executing got %v exp %v", ti.Executing, true)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := `digraph testTaskID {
graph [throughput="0.00 points/s"];
stream0 [avg_exec_time_ns="0s" errors="0" working_cardinality="0" ];
stream0 -> from1 [processed="0"];
from1 [avg_exec_time_ns="0s" errors="0" working_cardinality="0" ];
}`
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_EnableTaskOnCreate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Enabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Enabled)
}
if ti.Executing != true {
t.Fatalf("unexpected executing got %v exp %v", ti.Executing, true)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := `digraph testTaskID {
graph [throughput="0.00 points/s"];
stream0 [avg_exec_time_ns="0s" errors="0" working_cardinality="0" ];
stream0 -> from1 [processed="0"];
from1 [avg_exec_time_ns="0s" errors="0" working_cardinality="0" ];
}`
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_DisableTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_DeleteTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
err = cli.DeleteTask(task.Link)
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err == nil {
t.Fatal("unexpected task:", ti)
}
}
func TestServer_TaskNums(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `stream
|from()
.measurement('test')
`
// Create a bunch of tasks with every 3rd task enabled
count := 100
enabled := 0
tasks := make([]client.Task, count)
for i := 0; i < count; i++ {
status := client.Disabled
if i%3 == 0 {
enabled++
status = client.Enabled
}
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: fmt.Sprintf("%s-%d", id, i),
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: status,
})
if err != nil {
t.Fatal(err)
}
tasks[i] = task
}
if stats, err := s.Stats(); err != nil {
t.Fatal(err)
} else {
if got, exp := stats.NumTasks, count; got != exp {
t.Errorf("unexpected num_tasks got %d exp %d", got, exp)
}
if got, exp := stats.NumEnabledTasks, enabled; got != exp {
t.Errorf("unexpected num_enabled_tasks got %d exp %d", got, exp)
}
}
// Enable a bunch of tasks
for i, task := range tasks {
if i%2 == 0 && task.Status != client.Enabled {
enabled++
tasks[i].Status = client.Enabled
if _, err := cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
}
}
if stats, err := s.Stats(); err != nil {
t.Fatal(err)
} else {
if got, exp := stats.NumTasks, count; got != exp {
t.Errorf("unexpected num_tasks got %d exp %d", got, exp)
}
if got, exp := stats.NumEnabledTasks, enabled; got != exp {
t.Errorf("unexpected num_enabled_tasks got %d exp %d", got, exp)
}
}
// Disable a bunch of tasks
for i, task := range tasks {
if i%5 == 0 && task.Status != client.Disabled {
enabled--
tasks[i].Status = client.Disabled
if _, err := cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
}); err != nil {
t.Fatal(err)
}
}
}
if stats, err := s.Stats(); err != nil {
t.Fatal(err)
} else {
if got, exp := stats.NumTasks, count; got != exp {
t.Errorf("unexpected num_tasks got %d exp %d", got, exp)
}
if got, exp := stats.NumEnabledTasks, enabled; got != exp {
t.Errorf("unexpected num_enabled_tasks got %d exp %d", got, exp)
}
}
// Delete a bunch of tasks
for i, task := range tasks {
if i%6 == 0 {
count--
if task.Status == client.Enabled {
enabled--
}
if err := cli.DeleteTask(task.Link); err != nil {
t.Fatal(err)
}
}
}
if stats, err := s.Stats(); err != nil {
t.Fatal(err)
} else {
if got, exp := stats.NumTasks, count; got != exp {
t.Errorf("unexpected num_tasks got %d exp %d", got, exp)
}
if got, exp := stats.NumEnabledTasks, enabled; got != exp {
t.Errorf("unexpected num_enabled_tasks got %d exp %d", got, exp)
}
}
}
func TestServer_ListTasks(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
count := 10
ttype := client.StreamTask
tick := `stream
|from()
.measurement('test')
`
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
for i := 0; i < count; i++ {
id := fmt.Sprintf("testTaskID%d", i)
status := client.Disabled
if i%2 == 0 {
status = client.Enabled
}
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: status,
})
if err != nil {
t.Fatal(err)
}
}
tasks, err := cli.ListTasks(nil)
if err != nil {
t.Fatal(err)
}
if exp, got := count, len(tasks); exp != got {
t.Fatalf("unexpected number of tasks: exp:%d got:%d", exp, got)
}
for i, task := range tasks {
if exp, got := fmt.Sprintf("testTaskID%d", i), task.ID; exp != got {
t.Errorf("unexpected task.ID i:%d exp:%s got:%s", i, exp, got)
}
if exp, got := client.StreamTask, task.Type; exp != got {
t.Errorf("unexpected task.Type i:%d exp:%v got:%v", i, exp, got)
}
if !reflect.DeepEqual(task.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps i:%d exp:%s got:%s", i, dbrps, task.DBRPs)
}
exp := client.Disabled
if i%2 == 0 {
exp = client.Enabled
}
if got := task.Status; exp != got {
t.Errorf("unexpected task.Status i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := i%2 == 0, task.Executing; exp != got {
t.Errorf("unexpected task.Executing i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := true, len(task.Dot) != 0; exp != got {
t.Errorf("unexpected task.Dot i:%d exp:\n%v\ngot:\n%v\n", i, exp, got)
}
if exp, got := tick, task.TICKscript; exp != got {
t.Errorf("unexpected task.TICKscript i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := "", task.Error; exp != got {
t.Errorf("unexpected task.Error i:%d exp:%v got:%v", i, exp, got)
}
}
}
func TestServer_ListTasks_Fields(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
count := 100
ttype := client.StreamTask
tick := `stream
|from()
.measurement('test')
`
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
for i := 0; i < count; i++ {
id := fmt.Sprintf("testTaskID%d", i)
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
}
tasks, err := cli.ListTasks(&client.ListTasksOptions{
Pattern: "testTaskID1*",
Fields: []string{"type", "status"},
Offset: 1,
Limit: 5,
})
if err != nil {
t.Fatal(err)
}
if exp, got := 5, len(tasks); exp != got {
t.Fatalf("unexpected number of tasks: exp:%d got:%d", exp, got)
}
for i, task := range tasks {
if exp, got := fmt.Sprintf("testTaskID1%d", i), task.ID; exp != got {
t.Errorf("unexpected task.ID i:%d exp:%s got:%s", i, exp, got)
}
if exp, got := client.StreamTask, task.Type; exp != got {
t.Errorf("unexpected task.Type i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := client.Enabled, task.Status; exp != got {
t.Errorf("unexpected task.Status i:%d exp:%v got:%v", i, exp, got)
}
// We didn't request these fields so they should be default zero values
if exp, got := 0, len(task.DBRPs); exp != got {
t.Fatalf("unexpected dbrps i:%d exp:%d got:%d", i, exp, got)
}
if exp, got := false, task.Executing; exp != got {
t.Errorf("unexpected task.Executing i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := "", task.Dot; exp != got {
t.Errorf("unexpected task.Dot i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := "", task.TICKscript; exp != got {
t.Errorf("unexpected task.TICKscript i:%d exp:%v got:%v", i, exp, got)
}
if exp, got := "", task.Error; exp != got {
t.Errorf("unexpected task.Error i:%d exp:%v got:%v", i, exp, got)
}
}
}
func TestServer_CreateTemplate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `var x = 5
stream
|from()
.measurement('test')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, tick)
}
dot := "digraph testTemplateID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
vars := client.Vars{"x": {Value: int64(5), Type: client.VarInt}}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
}
func TestServer_UpdateTemplateID(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `var x = 5
stream
|from()
.measurement('test')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, tick)
}
dot := "digraph testTemplateID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
vars := client.Vars{"x": {Value: int64(5), Type: client.VarInt}}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
newID := "newTemplateID"
template, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: newID,
})
if err != nil {
t.Fatal(err)
}
if got, exp := template.Link.Href, "/kapacitor/v1/templates/newTemplateID"; got != exp {
t.Fatalf("unexpected template link got %s exp %s", got, exp)
}
ti, err = cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != newID {
t.Fatalf("unexpected id got %s exp %s", ti.ID, newID)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, tick)
}
dot = "digraph newTemplateID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
}
func TestServer_CreateTemplateImplicitAndUpdateExplicitWithTasks(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
implicitTick := `dbrp "telegraf"."autogen"
var x = 5
stream
|from()
.measurement('test')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
TICKscript: implicitTick,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != implicitTick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, implicitTick)
}
dot := "digraph testTemplateID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
vars := client.Vars{"x": {Value: int64(5), Type: client.VarInt}}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
implicitDBRPs := []client.DBRP{
{
Database: "telegraf",
RetentionPolicy: "autogen",
},
}
count := 1
tasks := make([]client.Task, count)
for i := 0; i < count; i++ {
task, err := cli.CreateTask(client.CreateTaskOptions{
TemplateID: template.ID,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
tasks[i] = task
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ti.DBRPs, implicitDBRPs) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, implicitDBRPs)
}
}
updateTick := `var x = 5
stream
|from()
.measurement('test')
`
_, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: id,
TICKscript: updateTick,
})
// Expects error
if err == nil {
t.Fatal(err)
}
finalTick := `dbrp "telegraf"."autogen"
dbrp "telegraf"."not_autogen"
var x = 5
stream
|from()
.measurement('test')
`
finalDBRPs := []client.DBRP{
{
Database: "telegraf",
RetentionPolicy: "autogen",
},
{
Database: "telegraf",
RetentionPolicy: "not_autogen",
},
}
template, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: id,
TICKscript: finalTick,
})
if err != nil {
t.Fatal(err)
}
for _, task := range tasks {
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ti.DBRPs, finalDBRPs) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, finalDBRPs)
}
}
}
func TestServer_UpdateTemplateID_WithTasks(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `var x = 5
stream
|from()
.measurement('test')
`
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
count := 100
tasks := make([]client.Task, count)
for i := 0; i < count; i++ {
task, err := cli.CreateTask(client.CreateTaskOptions{
TemplateID: template.ID,
DBRPs: dbrps,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
tasks[i] = task
}
newID := "newTemplateID"
template, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: newID,
})
if err != nil {
t.Fatal(err)
}
for _, task := range tasks {
got, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if got.TemplateID != newID {
t.Errorf("unexpected task TemplateID got %s exp %s", got.TemplateID, newID)
}
if got.TICKscript != tick {
t.Errorf("unexpected task TICKscript got %s exp %s", got.TICKscript, tick)
}
}
}
func TestServer_UpdateTemplateID_Fail(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
newID := "anotherTemplateID"
ttype := client.StreamTask
tick := `var x = 5
stream
|from()
.measurement('test')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, tick)
}
dot := "digraph testTemplateID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
vars := client.Vars{"x": {Value: int64(5), Type: client.VarInt}}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
// Create conflicting template
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: newID,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
if _, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: newID,
}); err == nil {
t.Fatal("expected update template to fail on name conflict")
}
// Can still get old template
ti, err = cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got\n%s\nexp\n%s\n", ti.TICKscript, tick)
}
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
if !reflect.DeepEqual(vars, ti.Vars) {
t.Fatalf("unexpected vars\ngot\n%s\nexp\n%s\n", ti.Vars, vars)
}
}
func TestServer_UpdateTemplateID_WithTasks_Fail(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `var x = 5
stream
|from()
.measurement('test')
`
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
count := 100
tasks := make([]client.Task, count)
for i := 0; i < count; i++ {
task, err := cli.CreateTask(client.CreateTaskOptions{
TemplateID: template.ID,
DBRPs: dbrps,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
tasks[i] = task
}
// Create conflicting template
newID := "newTemplateID"
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: newID,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
if _, err = cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
ID: newID,
TICKscript: "stream",
}); err == nil {
t.Fatal("expected update template to fail on conflicting name")
}
for _, task := range tasks {
got, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if got.TemplateID != id {
t.Errorf("unexpected task TemplateID got %s exp %s", got.TemplateID, id)
}
if got.TICKscript != tick {
t.Errorf("unexpected task TICKscript got %s exp %s", got.TICKscript, tick)
}
}
}
func TestServer_DeleteTemplate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `stream
|from()
.measurement('test')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
err = cli.DeleteTemplate(template.Link)
if err != nil {
t.Fatal(err)
}
ti, err := cli.Template(template.Link, nil)
if err == nil {
t.Fatal("unexpected template:", ti)
}
}
func TestServer_CreateTaskFromTemplate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTemplateID"
ttype := client.StreamTask
tick := `// Configurable measurement
var measurement = 'test'
stream
|from()
.measurement(measurement)
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: id,
Type: ttype,
TICKscript: tick,
})
if err != nil {
t.Fatal(err)
}
templateInfo, err := cli.Template(template.Link, nil)
if err != nil {
t.Fatal(err)
}
if templateInfo.Error != "" {
t.Fatal(templateInfo.Error)
}
if templateInfo.ID != id {
t.Fatalf("unexpected template.id got %s exp %s", templateInfo.ID, id)
}
if templateInfo.Type != client.StreamTask {
t.Fatalf("unexpected template.type got %v exp %v", templateInfo.Type, client.StreamTask)
}
if templateInfo.TICKscript != tick {
t.Fatalf("unexpected template.TICKscript got %s exp %s", templateInfo.TICKscript, tick)
}
dot := "digraph testTemplateID {\nstream0 -> from1;\n}"
if templateInfo.Dot != dot {
t.Fatalf("unexpected template.dot\ngot\n%s\nexp\n%s\n", templateInfo.Dot, dot)
}
expVars := client.Vars{
"measurement": {
Value: "test",
Type: client.VarString,
Description: "Configurable measurement",
},
}
if got, exp := templateInfo.Vars, expVars; !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected template vars: got %v exp %v", got, exp)
}
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
vars := client.Vars{
"measurement": {
Value: "another_measurement",
Type: client.VarString,
},
}
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: "taskid",
TemplateID: id,
DBRPs: dbrps,
Vars: vars,
})
if err != nil {
t.Fatal(err)
}
taskInfo, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if taskInfo.Error != "" {
t.Fatal(taskInfo.Error)
}
if taskInfo.ID != "taskid" {
t.Fatalf("unexpected task.id got %s exp %s", taskInfo.ID, "taskid")
}
if taskInfo.Type != client.StreamTask {
t.Fatalf("unexpected task.type got %v exp %v", taskInfo.Type, client.StreamTask)
}
if taskInfo.TICKscript != tick {
t.Fatalf("unexpected task.TICKscript got %s exp %s", taskInfo.TICKscript, tick)
}
dot = "digraph taskid {\nstream0 -> from1;\n}"
if taskInfo.Dot != dot {
t.Fatalf("unexpected task.dot\ngot\n%s\nexp\n%s\n", taskInfo.Dot, dot)
}
if taskInfo.Status != client.Disabled {
t.Fatalf("unexpected task.status got %v exp %v", taskInfo.Status, client.Disabled)
}
if !reflect.DeepEqual(taskInfo.DBRPs, dbrps) {
t.Fatalf("unexpected task.dbrps got %s exp %s", taskInfo.DBRPs, dbrps)
}
if !reflect.DeepEqual(taskInfo.Vars, vars) {
t.Fatalf("unexpected task.vars got %s exp %s", taskInfo.Vars, vars)
}
}
func TestServer_DynamicStreamTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
testCases := []struct {
name string
tick string
want client.TaskType
}{
{
name: "stream",
tick: `
dbrp "db"."rp"
stream
|from()
.measurement('test')
`,
want: client.StreamTask,
},
{
name: "stream_through_var",
tick: `
dbrp "db"."rp"
var s = stream
s
|from()
.measurement('test')
`,
want: client.StreamTask,
},
{
name: "batch",
tick: `
dbrp "db"."rp"
batch
|query('select * from db.rp.m')
`,
want: client.BatchTask,
},
{
name: "batch_through_var",
tick: `
dbrp "db"."rp"
var b = batch
b
|query('select * from db.rp.m')
`,
want: client.BatchTask,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: tc.name,
TICKscript: tc.tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
if task.Type != tc.want {
t.Fatalf("unexpected task type: got: %v want: %v", task.Type, tc.want)
}
})
}
}
func TestServer_StreamTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
func TestServer_StreamTask_NoRP(t *testing.T) {
conf := NewConfig()
conf.DefaultRetentionPolicy = "myrp"
s := OpenServer(conf)
defer s.Close()
cli := Client(s)
id := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "", points, v)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
func TestServer_StreamTemplateTask(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `
var field = 'nonexistent'
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count(field)
|httpOut('count')
`
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: taskId,
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Enabled,
Vars: client.Vars{
"field": {
Value: "value",
Type: client.VarString,
},
},
}); err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
if err := s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
if err := s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
func TestServer_StreamTemplateTask_MissingVar(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `
var field string
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count(field)
|httpOut('count')
`
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: taskId,
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Enabled,
}); err == nil {
t.Error("expected error for missing task vars")
} else if exp, got := "invalid TICKscript: missing value for var \"field\".", err.Error(); got != exp {
t.Errorf("unexpected error message: got %s exp %s", got, exp)
}
}
func TestServer_StreamTemplateTask_AllTypes(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `
var bool bool
var count_threshold int
var value_threshold float
var window duration
var field string
var tagMatch regex
var match lambda
var eval lambda
var groups list
var secondGroup list
stream
|from()
.measurement('test')
.where(lambda: match AND "tag" =~ tagMatch AND bool AND "value" >= value_threshold)
.groupBy(groups)
|log().prefix('FROM')
|window()
.period(window)
.every(window)
|log().prefix('WINDOW')
|count(field)
|log().prefix('COUNT')
|groupBy(secondGroup)
|sum('count')
.as('count')
|log().prefix('SUM')
|where(lambda: "count" >= count_threshold)
|log().prefix('WHERE')
|eval(eval)
.as('count')
|httpOut('count')
`
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: taskId,
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Enabled,
Vars: client.Vars{
"bool": {
Value: true,
Type: client.VarBool,
},
"count_threshold": {
Value: int64(1),
Type: client.VarInt,
},
"value_threshold": {
Value: float64(1.0),
Type: client.VarFloat,
},
"window": {
Value: 10 * time.Second,
Type: client.VarDuration,
},
"field": {
Value: "value",
Type: client.VarString,
},
"tagMatch": {
Value: "^a.*",
Type: client.VarRegex,
},
"match": {
Value: `"value" == 1.0`,
Type: client.VarLambda,
},
"eval": {
Value: `"count" * 2`,
Type: client.VarLambda,
},
"groups": {
Value: []client.Var{client.Var{Type: client.VarStar}},
Type: client.VarList,
},
"secondGroup": {
Value: []client.Var{client.Var{Value: "tag", Type: client.VarString}},
Type: client.VarList,
},
},
}); err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
if err := s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
points := `test,tag=abc,other=a value=1 0000000000
test,tag=abc,other=b value=1 0000000000
test,tag=abc,other=a value=1 0000000001
test,tag=bbc,other=b value=1 0000000001
test,tag=abc,other=a value=1 0000000002
test,tag=abc,other=a value=0 0000000002
test,tag=abc,other=b value=1 0000000003
test,tag=abc,other=a value=1 0000000003
test,tag=abc,other=a value=1 0000000004
test,tag=abc,other=b value=1 0000000005
test,tag=abc,other=a value=1 0000000005
test,tag=bbc,other=a value=1 0000000005
test,tag=abc,other=b value=1 0000000006
test,tag=abc,other=a value=1 0000000007
test,tag=abc,other=b value=0 0000000008
test,tag=abc,other=a value=1 0000000009
test,tag=abc,other=a value=1 0000000010
test,tag=abc,other=a value=1 0000000011
test,tag=abc,other=b value=1 0000000011
test,tag=bbc,other=a value=1 0000000011
test,tag=bbc,other=b value=1 0000000011
test,tag=abc,other=a value=1 0000000021
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","tags":{"tag":"abc"},"columns":["time","count"],"values":[["1970-01-01T00:00:10Z",24]]}]}`
if err := s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
func TestServer_StreamTemplateTaskFromUpdate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `
var field = 'nonexistent'
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count(field)
|httpOut('count')
`
if _, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tick,
}); err != nil {
t.Fatal(err)
}
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: taskId,
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Disabled,
Vars: client.Vars{
"field": {
Value: "value",
Type: client.VarString,
},
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
if err := s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
if err := s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
func TestServer_StreamTemplateTask_UpdateTemplate(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tickWrong := `
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count('wrong')
|httpOut('count')
`
tickCorrect := `
var field string
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count(field)
|httpOut('count')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tickWrong,
})
if err != nil {
t.Fatal(err)
}
if _, err = cli.CreateTask(client.CreateTaskOptions{
ID: taskId,
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Enabled,
Vars: client.Vars{
"field": {
Value: "value",
Type: client.VarString,
},
},
}); err != nil {
t.Fatal(err)
}
if _, err := cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
TICKscript: tickCorrect,
}); err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
if err := s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
if err := s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
func TestServer_StreamTemplateTask_UpdateTemplate_Rollback(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
templateId := "testStreamTemplate"
taskId := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tickCorrect := `
var field string
stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count(field)
|httpOut('count')
`
tickNewVar := `
var field string
var period duration
stream
|from()
.measurement('test')
|window()
.period(period)
.every(period)
|count(field)
|httpOut('count')
`
template, err := cli.CreateTemplate(client.CreateTemplateOptions{
ID: templateId,
Type: ttype,
TICKscript: tickCorrect,
})
if err != nil {
t.Fatal(err)
}
// Create several tasks
count := 5
tasks := make([]client.Task, count)
for i := 0; i < count; i++ {
if task, err := cli.CreateTask(client.CreateTaskOptions{
ID: fmt.Sprintf("%s-%d", taskId, i),
TemplateID: templateId,
DBRPs: dbrps,
Status: client.Enabled,
Vars: client.Vars{
"field": {
Value: "value",
Type: client.VarString,
},
},
}); err != nil {
t.Fatal(err)
} else {
tasks[i] = task
}
}
if _, err := cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
TICKscript: tickNewVar,
}); err == nil {
t.Error("expected error for breaking template update, got nil")
} else if got, exp := err.Error(), `error reloading associated task testStreamTask-0: missing value for var "period".`; exp != got {
t.Errorf("unexpected error for breaking template update, got %s exp %s", got, exp)
}
// Get all tasks and make sure their TICKscript has the original value
for _, task := range tasks {
if gotTask, err := cli.Task(task.Link, &client.TaskOptions{ScriptFormat: "raw"}); err != nil {
t.Fatal(err)
} else if got, exp := gotTask.TICKscript, tickCorrect; got != exp {
t.Errorf("unexpected task TICKscript:\ngot\n%s\nexp\n%s\n", got, exp)
}
}
// Update all tasks with new var
for _, task := range tasks {
if _, err := cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Vars: client.Vars{
"field": {
Value: "value",
Type: client.VarString,
},
"period": {
Value: 10 * time.Second,
Type: client.VarDuration,
},
},
}); err != nil {
t.Fatal(err)
}
}
// Now update template should succeed since the tasks are updated too.
if _, err := cli.UpdateTemplate(template.Link, client.UpdateTemplateOptions{
TICKscript: tickNewVar,
}); err != nil {
t.Fatal(err)
}
for _, task := range tasks {
taskId := task.ID
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
if err := s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
for _, task := range tasks {
taskId := task.ID
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), taskId)
exp := `{"series":[{"name":"test","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
if err := s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5); err != nil {
t.Error(err)
}
}
}
func TestServer_UpdateTaskID(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
newID := "newTaskID"
task, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
ID: newID,
})
if err != nil {
t.Fatal(err)
}
if got, exp := task.Link.Href, "/kapacitor/v1/tasks/newTaskID"; got != exp {
t.Fatalf("unexpected task link got %s exp %s", got, exp)
}
ti, err = cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != newID {
t.Fatalf("unexpected id got %s exp %s", ti.ID, newID)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot = "digraph newTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_UpdateTaskID_Fail(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
newID := "anotherTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
// Create conflicting task
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: newID,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
}); err != nil {
t.Fatal(err)
}
if _, err := cli.UpdateTask(task.Link, client.UpdateTaskOptions{
ID: newID,
}); err == nil {
t.Fatal("expected error on name conflict")
}
// Can still get old task
ti, err = cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_UpdateTaskID_Enabled(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Enabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Enabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
if !ti.Executing {
t.Fatal("expected task to be executing")
}
newID := "newTaskID"
task, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
ID: newID,
})
if err != nil {
t.Fatal(err)
}
if got, exp := task.Link.Href, "/kapacitor/v1/tasks/newTaskID"; got != exp {
t.Fatalf("unexpected task link got %s exp %s", got, exp)
}
ti, err = cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != newID {
t.Fatalf("unexpected id got %s exp %s", ti.ID, newID)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Enabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Enabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
if !ti.Executing {
t.Fatal("expected task to be executing")
}
}
func TestServer_StreamTask_AllMeasurements(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `stream
|from()
|window()
.period(10s)
.every(10s)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test0 value=1 0000000000
test1 value=1 0000000001
test0 value=1 0000000001
test1 value=1 0000000002
test0 value=1 0000000002
test1 value=1 0000000003
test0 value=1 0000000003
test1 value=1 0000000004
test0 value=1 0000000005
test1 value=1 0000000005
test0 value=1 0000000005
test1 value=1 0000000006
test0 value=1 0000000007
test1 value=1 0000000008
test0 value=1 0000000009
test1 value=1 0000000010
test0 value=1 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test0","columns":["time","count"],"values":[["1970-01-01T00:00:10Z",15]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
func TestServer_BatchTask(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
count := 0
stopTimeC := make(chan time.Time, 1)
db := NewInfluxDB(func(q string) *iclient.Response {
stmt, err := influxql.ParseStatement(q)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
slct, ok := stmt.(*influxql.SelectStatement)
if !ok {
return nil
}
cond, ok := slct.Condition.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition to be binary expression"}
}
stopTimeExpr, ok := cond.RHS.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be binary expression"}
}
stopTL, ok := stopTimeExpr.RHS.(*influxql.StringLiteral)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be string literal"}
}
count++
switch count {
case 1:
stopTime, err := time.Parse(time.RFC3339Nano, stopTL.Val)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
stopTimeC <- stopTime
return &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
stopTime.Add(-2 * time.Millisecond).Format(time.RFC3339Nano),
1.0,
},
{
stopTime.Add(-1 * time.Millisecond).Format(time.RFC3339Nano),
1.0,
},
},
}},
}},
}
default:
return &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{},
}},
}},
}
}
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(5ms)
.every(5ms)
.align()
|count('value')
|where(lambda: "count" == 2)
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
timeout := time.NewTicker(100 * time.Millisecond)
defer timeout.Stop()
select {
case <-timeout.C:
t.Fatal("timedout waiting for query")
case stopTime := <-stopTimeC:
exp := fmt.Sprintf(`{"series":[{"name":"cpu","columns":["time","count"],"values":[["%s",2]]}]}`, stopTime.Local().Format(time.RFC3339Nano))
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
}
}
func TestServer_BatchTask_InfluxDBConfigUpdate(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
count := 0
stopTimeC := make(chan time.Time, 1)
badCount := 0
dbBad := NewInfluxDB(func(q string) *iclient.Response {
badCount++
// Return empty results
return &iclient.Response{
Results: []iclient.Result{},
}
})
defer dbBad.Close()
db := NewInfluxDB(func(q string) *iclient.Response {
stmt, err := influxql.ParseStatement(q)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
slct, ok := stmt.(*influxql.SelectStatement)
if !ok {
return nil
}
cond, ok := slct.Condition.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition to be binary expression"}
}
stopTimeExpr, ok := cond.RHS.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be binary expression"}
}
stopTL, ok := stopTimeExpr.RHS.(*influxql.StringLiteral)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be string literal"}
}
count++
switch count {
case 1:
stopTime, err := time.Parse(time.RFC3339Nano, stopTL.Val)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
stopTimeC <- stopTime
return &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
stopTime.Add(-2 * time.Millisecond).Format(time.RFC3339Nano),
1.0,
},
{
stopTime.Add(-1 * time.Millisecond).Format(time.RFC3339Nano),
1.0,
},
},
}},
}},
}
default:
return &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{},
}},
}},
}
}
})
defer db.Close()
// Set bad URL first
c.InfluxDB[0].URLs = []string{dbBad.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(5ms)
.every(5ms)
.align()
|count('value')
|where(lambda: "count" == 2)
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
// Update InfluxDB config, while task is running
influxdbDefault := cli.ConfigElementLink("influxdb", "default")
if err := cli.ConfigUpdate(influxdbDefault, client.ConfigUpdateAction{
Set: map[string]interface{}{
"urls": []string{db.URL()},
},
}); err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
timeout := time.NewTicker(100 * time.Millisecond)
defer timeout.Stop()
select {
case <-timeout.C:
t.Fatal("timedout waiting for query")
case stopTime := <-stopTimeC:
exp := fmt.Sprintf(`{"series":[{"name":"cpu","columns":["time","count"],"values":[["%s",2]]}]}`, stopTime.Local().Format(time.RFC3339Nano))
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
}
if badCount == 0 {
t.Error("expected bad influxdb to be queried at least once")
}
}
func TestServer_InvalidBatchTask(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
db := NewInfluxDB(func(q string) *iclient.Response {
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testInvalidBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `batch
|query(' SELECT value from unknowndb.unknownrp.cpu ')
.period(5ms)
.every(5ms)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
expErr := `batch query is not allowed to request data from "unknowndb"."unknownrp"`
if err != nil && err.Error() != expErr {
t.Fatalf("unexpected err: got %v exp %s", err, expErr)
}
err = cli.DeleteTask(task.Link)
if err != nil {
t.Fatal(err)
}
}
func TestServer_RecordReplayStream(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testStreamTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count('value')
|alert()
.id('test-count')
.message('{{ .ID }} got: {{ index .Fields "count" }}')
.crit(lambda: TRUE)
.log('` + tmpDir + `/alert.log')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
recording, err := cli.RecordStream(client.RecordStreamOptions{
ID: "recordingid",
Task: task.ID,
Stop: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/recordings/recordingid", recording.Link.Href; exp != got {
t.Errorf("unexpected recording.Link.Href got %s exp %s", got, exp)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
test value=1 0000000012
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
retry := 0
for recording.Status == client.Running {
time.Sleep(100 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 100 {
t.Fatal("failed to finish recording")
}
}
if recording.Status != client.Finished || recording.Error != "" {
t.Errorf("recording failed: %s", recording.Error)
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
ID: "replayid",
Task: id,
Recording: recording.ID,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/replays/replayid", replay.Link.Href; exp != got {
t.Errorf("unexpected replay.Link.Href got %s exp %s", got, exp)
}
if exp, got := id, replay.Task; exp != got {
t.Errorf("unexpected replay.Task got %s exp %s", got, exp)
}
retry = 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to finish replay")
}
}
if replay.Status != client.Finished || replay.Error != "" {
t.Errorf("replay failed: %s", replay.Error)
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := response{
ID: "test-count",
Message: "test-count got: 15",
Time: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "test",
Columns: []string{"time", "count"},
Values: [][]interface{}{
{
time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC).Format(time.RFC3339Nano),
15.0,
},
},
},
},
},
}
got := response{}
d := json.NewDecoder(f)
d.Decode(&got)
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
}
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v\nrecordings %v", got, exp, recordings)
}
err = cli.DeleteRecording(recordings[0].Link)
if err != nil {
t.Error(err)
}
recordings, err = cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Errorf("unexpected recordings list after delete:\ngot %v\nexp %v\nrecordings %v", got, exp, recordings)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v\nreplays %v", got, exp, replays)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list after delete:\ngot %v\nexp %v\nreplays %v", got, exp, replays)
}
}
func TestServer_RecordReplayStreamWithPost(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
id := "testStreamTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testStreamTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `stream
|from()
.measurement('test')
|window()
.period(10s)
.every(10s)
|count('value')
|alert()
.id('test-count')
.message('{{ .ID }} got: {{ index .Fields "count" }}')
.crit(lambda: TRUE)
.post('http://localhost:8080')
.log('` + tmpDir + `/alert.log')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
recording, err := cli.RecordStream(client.RecordStreamOptions{
ID: "recordingid",
Task: task.ID,
Stop: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/recordings/recordingid", recording.Link.Href; exp != got {
t.Errorf("unexpected recording.Link.Href got %s exp %s", got, exp)
}
points := `test value=1 0000000000
test value=1 0000000001
test value=1 0000000001
test value=1 0000000002
test value=1 0000000002
test value=1 0000000003
test value=1 0000000003
test value=1 0000000004
test value=1 0000000005
test value=1 0000000005
test value=1 0000000005
test value=1 0000000006
test value=1 0000000007
test value=1 0000000008
test value=1 0000000009
test value=1 0000000010
test value=1 0000000011
test value=1 0000000012
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
retry := 0
for recording.Status == client.Running {
time.Sleep(100 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 100 {
t.Fatal("failed to finish recording")
}
}
if recording.Status != client.Finished || recording.Error != "" {
t.Errorf("recording failed: %s", recording.Error)
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
ID: "replayid",
Task: id,
Recording: recording.ID,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/replays/replayid", replay.Link.Href; exp != got {
t.Errorf("unexpected replay.Link.Href got %s exp %s", got, exp)
}
if exp, got := id, replay.Task; exp != got {
t.Errorf("unexpected replay.Task got %s exp %s", got, exp)
}
retry = 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to finish replay")
}
}
if replay.Status != client.Finished || replay.Error != "" {
t.Errorf("replay failed: %s", replay.Error)
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := response{
ID: "test-count",
Message: "test-count got: 15",
Time: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "test",
Columns: []string{"time", "count"},
Values: [][]interface{}{
{
time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC).Format(time.RFC3339Nano),
15.0,
},
},
},
},
},
}
got := response{}
d := json.NewDecoder(f)
d.Decode(&got)
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
}
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v\nrecordings %v", got, exp, recordings)
}
err = cli.DeleteRecording(recordings[0].Link)
if err != nil {
t.Error(err)
}
recordings, err = cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Errorf("unexpected recordings list after delete:\ngot %v\nexp %v\nrecordings %v", got, exp, recordings)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v\nreplays %v", got, exp, replays)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list after delete:\ngot %v\nexp %v\nreplays %v", got, exp, replays)
}
}
func TestServer_RecordReplayBatch(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
value := 0
db := NewInfluxDB(func(q string) *iclient.Response {
if len(q) > 6 && q[:6] == "SELECT" {
r := &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, value, 0, time.UTC).Format(time.RFC3339Nano),
float64(value),
},
{
time.Date(1971, 1, 1, 0, 0, value+1, 0, time.UTC).Format(time.RFC3339Nano),
float64(value + 1),
},
},
}},
}},
}
value += 2
return r
}
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testBatchTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(2s)
.every(2s)
|alert()
.id('test-batch')
.message('{{ .ID }} got: {{ index .Fields "value" }}')
.crit(lambda: "value" > 2.0)
.log('` + tmpDir + `/alert.log')
`
_, err = cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
recording, err := cli.RecordBatch(client.RecordBatchOptions{
ID: "recordingid",
Task: id,
Start: time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC),
Stop: time.Date(1971, 1, 1, 0, 0, 6, 0, time.UTC),
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/recordings/recordingid", recording.Link.Href; exp != got {
t.Errorf("unexpected recording.Link.Href got %s exp %s", got, exp)
}
// Wait for recording to finish.
retry := 0
for recording.Status == client.Running {
time.Sleep(100 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom recording")
}
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
Task: id,
Recording: recording.ID,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := id, replay.Task; exp != got {
t.Errorf("unexpected replay.Task got %s exp %s", got, exp)
}
// Wait for replay to finish.
retry = 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perform replay")
}
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := []response{
{
ID: "test-batch",
Message: "test-batch got: 3",
Time: time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
},
},
},
{
ID: "test-batch",
Message: "test-batch got: 4",
Time: time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
},
},
}
dec := json.NewDecoder(f)
got := make([]response, 0)
for dec.More() {
g := response{}
dec.Decode(&g)
got = append(got, g)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[0].Data.Series[0], exp[0].Data.Series[0])
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[1].Data.Series[0], exp[1].Data.Series[0])
}
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
err = cli.DeleteRecording(recordings[0].Link)
if err != nil {
t.Error(err)
}
recordings, err = cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Errorf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
}
func TestServer_ReplayBatch(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
value := 0
db := NewInfluxDB(func(q string) *iclient.Response {
if len(q) > 6 && q[:6] == "SELECT" {
r := &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, value, 0, time.UTC).Format(time.RFC3339Nano),
float64(value),
},
{
time.Date(1971, 1, 1, 0, 0, value+1, 0, time.UTC).Format(time.RFC3339Nano),
float64(value + 1),
},
},
}},
}},
}
value += 2
return r
}
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testBatchTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(2s)
.every(2s)
|alert()
.id('test-batch')
.message('{{ .ID }} got: {{ index .Fields "value" }}')
.crit(lambda: "value" > 2.0)
.log('` + tmpDir + `/alert.log')
`
_, err = cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
replay, err := cli.ReplayBatch(client.ReplayBatchOptions{
ID: "replayid",
Task: id,
Start: time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC),
Stop: time.Date(1971, 1, 1, 0, 0, 6, 0, time.UTC),
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/replays/replayid", replay.Link.Href; exp != got {
t.Errorf("unexpected replay.Link.Href got %s exp %s", got, exp)
}
// Wait for replay to finish.
retry := 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom replay")
}
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := []response{
{
ID: "test-batch",
Message: "test-batch got: 3",
Time: time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
},
},
},
{
ID: "test-batch",
Message: "test-batch got: 4",
Time: time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
},
},
}
dec := json.NewDecoder(f)
got := make([]response, 0)
for dec.More() {
g := response{}
dec.Decode(&g)
got = append(got, g)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[0].Data.Series[0], exp[0].Data.Series[0])
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[1].Data.Series[0], exp[1].Data.Series[0])
}
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
}
func TestServer_RecordReplayQuery(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
db := NewInfluxDB(func(q string) *iclient.Response {
if len(q) > 6 && q[:6] == "SELECT" {
r := &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339Nano),
0.0,
},
{
time.Date(1971, 1, 1, 0, 0, 1, 0, time.UTC).Format(time.RFC3339Nano),
1.0,
},
},
},
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
}},
}
return r
}
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testBatchTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(2s)
.every(2s)
|alert()
.id('test-batch')
.message('{{ .ID }} got: {{ index .Fields "value" }}')
.crit(lambda: "value" > 2.0)
.log('` + tmpDir + `/alert.log')
`
_, err = cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
recording, err := cli.RecordQuery(client.RecordQueryOptions{
ID: "recordingid",
Query: "SELECT value from mydb.myrp.cpu",
Type: client.BatchTask,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/recordings/recordingid", recording.Link.Href; exp != got {
t.Errorf("unexpected recording.Link.Href got %s exp %s", got, exp)
}
// Wait for recording to finish.
retry := 0
for recording.Status == client.Running {
time.Sleep(100 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom recording")
}
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
Task: id,
Recording: recording.ID,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := id, replay.Task; exp != got {
t.Errorf("unexpected replay.Task got %s exp %s", got, exp)
}
// Wait for replay to finish.
retry = 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom replay")
}
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := []response{
{
ID: "test-batch",
Message: "test-batch got: 3",
Time: time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
},
},
},
{
ID: "test-batch",
Message: "test-batch got: 4",
Time: time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
},
},
}
dec := json.NewDecoder(f)
got := make([]response, 0)
for dec.More() {
g := response{}
dec.Decode(&g)
got = append(got, g)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[0].Data.Series[0], exp[0].Data.Series[0])
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[1].Data.Series[0], exp[1].Data.Series[0])
}
// ------------
// Test List/Delete Recordings/Replays
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
// Test List Recordings via direct default URL
resp, err := http.Get(s.URL() + "/recordings")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if exp, got := http.StatusOK, resp.StatusCode; exp != got {
t.Errorf("unexpected status code, got %d exp %d", got, exp)
}
// Response type
type recResponse struct {
Recordings []client.Recording `json:"recordings"`
}
dec = json.NewDecoder(resp.Body)
recR := recResponse{}
dec.Decode(&recR)
if exp, got := 1, len(recR.Recordings); exp != got {
t.Fatalf("unexpected recordings count, got %d exp %d", got, exp)
}
err = cli.DeleteRecording(recordings[0].Link)
if err != nil {
t.Error(err)
}
recordings, err = cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Errorf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
// Test List Replays via direct default URL
resp, err = http.Get(s.URL() + "/replays")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if exp, got := http.StatusOK, resp.StatusCode; exp != got {
t.Errorf("unexpected status code, got %d exp %d", got, exp)
}
// Response type
type repResponse struct {
Replays []client.Replay `json:"replays"`
}
dec = json.NewDecoder(resp.Body)
repR := repResponse{}
dec.Decode(&repR)
if exp, got := 1, len(repR.Replays); exp != got {
t.Fatalf("unexpected replays count, got %d exp %d", got, exp)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
}
func TestServer_ReplayQuery(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
db := NewInfluxDB(func(q string) *iclient.Response {
if len(q) > 6 && q[:6] == "SELECT" {
r := &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339Nano),
0.0,
},
{
time.Date(1971, 1, 1, 0, 0, 1, 0, time.UTC).Format(time.RFC3339Nano),
1.0,
},
},
},
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
}},
}
return r
}
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testBatchTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tmpDir, err := ioutil.TempDir("", "testBatchTaskRecording")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tick := `batch
|query('SELECT value from mydb.myrp.cpu')
.period(2s)
.every(2s)
|alert()
.id('test-batch')
.message('{{ .ID }} got: {{ index .Fields "value" }}')
.crit(lambda: "value" > 2.0)
.log('` + tmpDir + `/alert.log')
`
_, err = cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
replay, err := cli.ReplayQuery(client.ReplayQueryOptions{
ID: "replayid",
Query: "SELECT value from mydb.myrp.cpu",
Task: id,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/replays/replayid", replay.Link.Href; exp != got {
t.Errorf("unexpected replay.Link.Href got %s exp %s", got, exp)
}
// Wait for replay to finish.
retry := 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom replay")
}
}
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
type response struct {
ID string `json:"id"`
Message string `json:"message"`
Time time.Time `json:"time"`
Level string `json:"level"`
Data influxql.Result `json:"data"`
}
exp := []response{
{
ID: "test-batch",
Message: "test-batch got: 3",
Time: time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
},
},
},
},
},
},
{
ID: "test-batch",
Message: "test-batch got: 4",
Time: time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
Level: "CRITICAL",
Data: influxql.Result{
Series: imodels.Rows{
{
Name: "cpu",
Columns: []string{"time", "value"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
},
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
},
},
},
},
},
},
}
dec := json.NewDecoder(f)
got := make([]response, 0)
for dec.More() {
g := response{}
if err := dec.Decode(&g); err != nil {
t.Error(err)
}
got = append(got, g)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got, exp)
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[0].Data.Series[0], exp[0].Data.Series[0])
t.Errorf("unexpected alert log:\ngot %v\nexp %v", got[1].Data.Series[0], exp[1].Data.Series[0])
}
recordings, err := cli.ListRecordings(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(recordings); exp != got {
t.Fatalf("unexpected recordings list:\ngot %v\nexp %v", got, exp)
}
replays, err := cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 1, len(replays); exp != got {
t.Fatalf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
err = cli.DeleteReplay(replays[0].Link)
if err != nil {
t.Error(err)
}
replays, err = cli.ListReplays(nil)
if err != nil {
t.Error(err)
}
if exp, got := 0, len(replays); exp != got {
t.Errorf("unexpected replays list:\ngot %v\nexp %v", got, exp)
}
}
// Test for recording and replaying a stream query where data has missing fields and tags.
func TestServer_RecordReplayQuery_Missing(t *testing.T) {
c := NewConfig()
c.InfluxDB[0].Enabled = true
db := NewInfluxDB(func(q string) *iclient.Response {
if len(q) > 6 && q[:6] == "SELECT" {
r := &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{
{
Name: "m",
Tags: map[string]string{"t1": "", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 1, 0, time.UTC).Format(time.RFC3339Nano),
1.0,
nil,
},
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC).Format(time.RFC3339Nano),
nil,
2.0,
},
{
time.Date(1971, 1, 1, 0, 0, 10, 0, time.UTC).Format(time.RFC3339Nano),
nil,
10.0,
},
{
time.Date(1971, 1, 1, 0, 0, 11, 0, time.UTC).Format(time.RFC3339Nano),
11.0,
nil,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "", "t2": "4"},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC).Format(time.RFC3339Nano),
4.0,
4.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "", "t2": "7"},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 7, 0, time.UTC).Format(time.RFC3339Nano),
nil,
7.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "3", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC).Format(time.RFC3339Nano),
3.0,
3.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "5", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC).Format(time.RFC3339Nano),
5.0,
5.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "6", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 6, 0, time.UTC).Format(time.RFC3339Nano),
nil,
6.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "8", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 8, 0, time.UTC).Format(time.RFC3339Nano),
nil,
8.0,
},
},
},
{
Name: "m",
Tags: map[string]string{"t1": "9", "t2": ""},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 9, 0, time.UTC).Format(time.RFC3339Nano),
nil,
9.0,
},
},
},
},
}},
}
return r
}
return nil
})
c.InfluxDB[0].URLs = []string{db.URL()}
s := OpenServer(c)
defer s.Close()
cli := Client(s)
id := "testStreamQueryRecordReplay"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
// setup temp dir for alert.log
tmpDir, err := ioutil.TempDir("", "testStreamTaskRecordingReplay")
if err != nil {
t.Fatal(err)
}
//defer os.RemoveAll(tmpDir)
tick := `stream
|from()
.measurement('m')
|log()
|alert()
.id('test-stream-query')
.crit(lambda: TRUE)
.details('')
.log('` + tmpDir + `/alert.log')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
}); err != nil {
t.Fatal(err)
}
recording, err := cli.RecordQuery(client.RecordQueryOptions{
ID: "recordingid",
Query: "SELECT * FROM mydb.myrp.m",
Type: client.StreamTask,
})
if err != nil {
t.Fatal(err)
}
if exp, got := "/kapacitor/v1/recordings/recordingid", recording.Link.Href; exp != got {
t.Errorf("unexpected recording.Link.Href got %s exp %s", got, exp)
}
// Wait for recording to finish.
retry := 0
for recording.Status == client.Running {
time.Sleep(100 * time.Millisecond)
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom recording")
}
}
replay, err := cli.CreateReplay(client.CreateReplayOptions{
Task: id,
Recording: recording.ID,
Clock: client.Fast,
RecordingTime: true,
})
if err != nil {
t.Fatal(err)
}
if exp, got := id, replay.Task; exp != got {
t.Errorf("unexpected replay.Task got %s exp %s", got, exp)
}
// Wait for replay to finish.
retry = 0
for replay.Status == client.Running {
time.Sleep(100 * time.Millisecond)
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
retry++
if retry > 10 {
t.Fatal("failed to perfom replay")
}
}
// Validate we got the data in the alert.log
f, err := os.Open(filepath.Join(tmpDir, "alert.log"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
exp := []alert.Data{
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 1, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Columns: []string{"time", "a"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 1, 0, time.UTC),
1.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 1 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 2, 0, time.UTC),
2.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t1": "3"},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 3, 0, time.UTC),
3.0,
3.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 3 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t2": "4"},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 4, 0, time.UTC),
4.0,
4.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 4 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t1": "5"},
Columns: []string{"time", "a", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 5, 0, time.UTC),
5.0,
5.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 6, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 5 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t1": "6"},
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 6, 0, time.UTC),
6.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 7, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 6 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t2": "7"},
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 7, 0, time.UTC),
7.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 8, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 7 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t1": "8"},
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 8, 0, time.UTC),
8.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 8 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Tags: map[string]string{"t1": "9"},
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 9, 0, time.UTC),
9.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 10, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 9 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Columns: []string{"time", "b"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 10, 0, time.UTC),
10.0,
},
},
},
},
},
},
{
ID: "test-stream-query",
Message: "test-stream-query is CRITICAL",
Time: time.Date(1971, 1, 1, 0, 0, 11, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 10 * time.Second,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "m",
Columns: []string{"time", "a"},
Values: [][]interface{}{
{
time.Date(1971, 1, 1, 0, 0, 11, 0, time.UTC),
11.0,
},
},
},
},
},
},
}
dec := json.NewDecoder(f)
var got []alert.Data
for dec.More() {
g := alert.Data{}
dec.Decode(&g)
got = append(got, g)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected alert log:\ngot %+v\nexp %+v", got, exp)
}
}
// If this test fails due to missing python dependencies, run 'INSTALL_PREFIX=/usr/local ./install-deps.sh' from the root directory of the
// kapacitor project.
func TestServer_UDFStreamAgents(t *testing.T) {
tdir, err := ioutil.TempDir("", "kapacitor_server_test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tdir)
agents := []struct {
buildFunc func() error
config udf.FunctionConfig
}{
// Go
{
buildFunc: func() error {
// Explicitly compile the binary.
// We could just use 'go run' but I ran into race conditions
// where 'go run' was not handing off to the compiled process in time
// and I didn't care to dig into 'go run's specific behavior.
cmd := exec.Command(
"go",
"build",
"-o",
filepath.Join(tdir, "movavg"+ExecutableSuffix),
filepath.Join(udfDir, "agent/examples/moving_avg/moving_avg.go"),
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Log(string(out))
return err
}
return nil
},
config: udf.FunctionConfig{
Prog: filepath.Join(tdir, "movavg"),
Timeout: toml.Duration(time.Minute),
},
},
// Python
{
buildFunc: func() error { return nil },
config: udf.FunctionConfig{
Prog: PythonExecutable,
Args: []string{"-u", filepath.Join(udfDir, "agent/examples/moving_avg/moving_avg.py")},
Timeout: toml.Duration(time.Minute),
Env: map[string]string{
"PYTHONPATH": strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
},
},
},
// Python 2
{
buildFunc: func() error { return nil },
config: udf.FunctionConfig{
Prog: Python2Executable,
Args: []string{"-u", filepath.Join(udfDir, "agent/examples/moving_avg/moving_avg.py")},
Timeout: toml.Duration(time.Minute),
Env: map[string]string{
"PYTHONPATH": strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
},
},
},
}
for _, agent := range agents {
err := agent.buildFunc()
if err != nil {
t.Fatal(err)
}
c := NewConfig()
c.UDF.Functions = map[string]udf.FunctionConfig{
"movingAvg": agent.config,
}
testStreamAgent(t, c)
}
}
func testStreamAgent(t *testing.T, c *server.Config) {
s := NewServer(c, nil)
err := s.Open()
if err != nil {
t.Fatal(err)
}
defer s.Close()
cli := Client(s)
id := "testUDFTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `stream
|from()
.measurement('test')
.groupBy('group')
@movingAvg()
.field('value')
.size(10)
.as('mean')
|window()
.period(11s)
.every(11s)
|last('mean').as('mean')
|httpOut('moving_avg')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/moving_avg", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test,group=a value=1 0000000000
test,group=b value=2 0000000000
test,group=a value=1 0000000001
test,group=b value=2 0000000001
test,group=a value=1 0000000002
test,group=b value=2 0000000002
test,group=a value=1 0000000003
test,group=b value=2 0000000003
test,group=a value=1 0000000004
test,group=b value=2 0000000004
test,group=a value=1 0000000005
test,group=b value=2 0000000005
test,group=a value=1 0000000006
test,group=b value=2 0000000006
test,group=a value=1 0000000007
test,group=b value=2 0000000007
test,group=a value=1 0000000008
test,group=b value=2 0000000008
test,group=a value=1 0000000009
test,group=b value=2 0000000009
test,group=a value=0 0000000010
test,group=b value=1 0000000010
test,group=a value=0 0000000011
test,group=b value=0 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","tags":{"group":"a"},"columns":["time","mean"],"values":[["1970-01-01T00:00:11Z",0.9]]},{"name":"test","tags":{"group":"b"},"columns":["time","mean"],"values":[["1970-01-01T00:00:11Z",1.9]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
// If this test fails due to missing python dependencies, run 'INSTALL_PREFIX=/usr/local ./install-deps.sh' from the root directory of the
// kapacitor project.
func TestServer_UDFStreamAgentsSocket(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping on windows as unix sockets are not available")
}
tdir, err := ioutil.TempDir("", "kapacitor_server_test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tdir)
agents := []struct {
startFunc func() *exec.Cmd
config udf.FunctionConfig
}{
// Go
{
startFunc: func() *exec.Cmd {
cmd := exec.Command(
"go",
"build",
"-o",
filepath.Join(tdir, "mirror"+ExecutableSuffix),
filepath.Join(udfDir, "agent/examples/mirror/mirror.go"),
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatal(string(out))
}
cmd = exec.Command(
filepath.Join(tdir, "mirror"),
"-socket",
filepath.Join(tdir, "mirror.go.sock"),
)
cmd.Stderr = os.Stderr
return cmd
},
config: udf.FunctionConfig{
Socket: filepath.Join(tdir, "mirror.go.sock"),
Timeout: toml.Duration(time.Minute),
},
},
// Python
{
startFunc: func() *exec.Cmd {
cmd := exec.Command(
PythonExecutable,
"-u",
filepath.Join(udfDir, "agent/examples/mirror/mirror.py"),
filepath.Join(tdir, "mirror.py.sock"),
)
cmd.Stderr = os.Stderr
env := os.Environ()
env = append(env, fmt.Sprintf(
"%s=%s",
"PYTHONPATH",
strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
))
cmd.Env = env
return cmd
},
config: udf.FunctionConfig{
Socket: filepath.Join(tdir, "mirror.py.sock"),
Timeout: toml.Duration(time.Minute),
},
},
// Python 2
{
startFunc: func() *exec.Cmd {
cmd := exec.Command(
Python2Executable,
"-u",
filepath.Join(udfDir, "agent/examples/mirror/mirror.py"),
filepath.Join(tdir, "mirror.py.sock"),
)
cmd.Stderr = os.Stderr
env := os.Environ()
env = append(env, fmt.Sprintf(
"%s=%s",
"PYTHONPATH",
strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
))
cmd.Env = env
return cmd
},
config: udf.FunctionConfig{
Socket: filepath.Join(tdir, "mirror.py.sock"),
Timeout: toml.Duration(time.Minute),
},
},
}
for _, agent := range agents {
cmd := agent.startFunc()
cmd.Start()
defer cmd.Process.Signal(os.Interrupt)
if err != nil {
t.Fatal(err)
}
c := NewConfig()
c.UDF.Functions = map[string]udf.FunctionConfig{
"mirror": agent.config,
}
testStreamAgentSocket(t, c)
}
}
func testStreamAgentSocket(t *testing.T, c *server.Config) {
s := NewServer(c, nil)
err := s.Open()
if err != nil {
t.Fatal(err)
}
defer s.Close()
cli := Client(s)
id := "testUDFTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `stream
|from()
.measurement('test')
.groupBy('group')
@mirror()
|window()
.period(10s)
.every(10s)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test,group=a value=1 0000000000
test,group=a value=1 0000000001
test,group=a value=1 0000000002
test,group=a value=1 0000000003
test,group=a value=1 0000000004
test,group=a value=1 0000000005
test,group=a value=1 0000000006
test,group=a value=1 0000000007
test,group=a value=1 0000000008
test,group=a value=1 0000000009
test,group=a value=0 0000000010
test,group=a value=0 0000000011
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","tags":{"group":"a"},"columns":["time","count"],"values":[["1970-01-01T00:00:10Z",10]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
// If this test fails due to missing python dependencies, run 'INSTALL_PREFIX=/usr/local ./install-deps.sh' from the root directory of the
// kapacitor project.
func TestServer_UDFBatchAgents(t *testing.T) {
tdir, err := ioutil.TempDir("", "kapacitor_server_test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tdir)
agents := []struct {
buildFunc func() error
config udf.FunctionConfig
}{
// Go
{
buildFunc: func() error {
// Explicitly compile the binary.
// We could just use 'go run' but I ran into race conditions
// where 'go run' was not handing off to the compiled process in time
// and I didn't care to dig into 'go run's specific behavior.
cmd := exec.Command(
"go",
"build",
"-o",
filepath.Join(tdir, "outliers"+ExecutableSuffix),
filepath.Join(udfDir, "agent/examples/outliers/outliers.go"),
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Log(string(out))
return err
}
return nil
},
config: udf.FunctionConfig{
Prog: filepath.Join(tdir, "outliers"),
Timeout: toml.Duration(time.Minute),
},
},
// Python
{
buildFunc: func() error { return nil },
config: udf.FunctionConfig{
Prog: PythonExecutable,
Args: []string{"-u", filepath.Join(udfDir, "agent/examples/outliers/outliers.py")},
Timeout: toml.Duration(time.Minute),
Env: map[string]string{
"PYTHONPATH": strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
},
},
},
// Python 2
{
buildFunc: func() error { return nil },
config: udf.FunctionConfig{
Prog: Python2Executable,
Args: []string{"-u", filepath.Join(udfDir, "agent/examples/outliers/outliers.py")},
Timeout: toml.Duration(time.Minute),
Env: map[string]string{
"PYTHONPATH": strings.Join(
[]string{filepath.Join(udfDir, "agent/py"), os.Getenv("PYTHONPATH")},
string(filepath.ListSeparator),
),
},
},
},
}
for _, agent := range agents {
err := agent.buildFunc()
if err != nil {
t.Fatal(err)
}
c := NewConfig()
c.UDF.Functions = map[string]udf.FunctionConfig{
"outliers": agent.config,
}
testBatchAgent(t, c)
}
}
func testBatchAgent(t *testing.T, c *server.Config) {
count := 0
stopTimeC := make(chan time.Time, 2)
db := NewInfluxDB(func(q string) *iclient.Response {
stmt, err := influxql.ParseStatement(q)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
slct, ok := stmt.(*influxql.SelectStatement)
if !ok {
return nil
}
cond, ok := slct.Condition.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition to be binary expression"}
}
stopTimeExpr, ok := cond.RHS.(*influxql.BinaryExpr)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be binary expression"}
}
stopTL, ok := stopTimeExpr.RHS.(*influxql.StringLiteral)
if !ok {
return &iclient.Response{Err: "expected select condition rhs to be string literal"}
}
count++
switch count {
case 1, 2:
stopTime, err := time.Parse(time.RFC3339Nano, stopTL.Val)
if err != nil {
return &iclient.Response{Err: err.Error()}
}
stopTimeC <- stopTime
data := []float64{
5,
6,
7,
13,
33,
35,
36,
45,
46,
47,
48,
50,
51,
52,
53,
54,
80,
85,
90,
100,
}
// Shuffle data using count as seed.
// Data order should not effect the result.
r := rand.New(rand.NewSource(int64(count)))
for i := range data {
j := r.Intn(i + 1)
data[i], data[j] = data[j], data[i]
}
// Create set values with time from shuffled data.
values := make([][]interface{}, len(data))
for i, value := range data {
values[i] = []interface{}{
stopTime.Add(time.Duration(i-len(data)) * time.Millisecond).Format(time.RFC3339Nano),
value,
}
}
return &iclient.Response{
Results: []iclient.Result{{
Series: []imodels.Row{{
Name: "cpu",
Columns: []string{"time", "value"},
Tags: map[string]string{
"count": strconv.FormatInt(int64(count%2), 10),
},
Values: values,
}},
}},
}
default:
return nil
}
})
c.InfluxDB[0].URLs = []string{db.URL()}
c.InfluxDB[0].Enabled = true
s := NewServer(c, nil)
err := s.Open()
if err != nil {
t.Fatal(err)
}
defer s.Close()
cli := Client(s)
id := "testUDFTask"
ttype := client.BatchTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := `batch
|query(' SELECT value from mydb.myrp.cpu ')
.period(5ms)
.every(5ms)
.groupBy('count')
@outliers()
.field('value')
.scale(1.5)
|count('value')
|httpOut('count')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
stopTimes := make([]time.Time, 2)
for i := range stopTimes {
timeout := time.NewTicker(100 * time.Millisecond)
defer timeout.Stop()
select {
case <-timeout.C:
t.Fatal("timedout waiting for query")
case stopTime := <-stopTimeC:
stopTimes[i] = stopTime
}
}
endpoint := fmt.Sprintf("%s/tasks/%s/count", s.URL(), id)
exp := fmt.Sprintf(
`{"series":[{"name":"cpu","tags":{"count":"1"},"columns":["time","count"],"values":[["%s",5]]},{"name":"cpu","tags":{"count":"0"},"columns":["time","count"],"values":[["%s",5]]}]}`,
stopTimes[0].Format(time.RFC3339Nano),
stopTimes[1].Format(time.RFC3339Nano),
)
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*50)
if err != nil {
t.Error(err)
}
_, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
}
func TestServer_CreateTask_Defaults(t *testing.T) {
s, cli := OpenDefaultServer()
baseURL := s.URL()
body := `
{
"id" : "TASK_ID",
"type" : "stream",
"dbrps": [{"db": "DATABASE_NAME", "rp" : "RP_NAME"}],
"script": "stream\n |from()\n .measurement('cpu')\n"
}`
resp, err := http.Post(baseURL+"/tasks", "application/json", strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if exp, got := http.StatusOK, resp.StatusCode; exp != got {
t.Errorf("unexpected status code, got %d exp %d", got, exp)
}
id := "TASK_ID"
tick := "stream\n |from()\n .measurement('cpu')\n"
dbrps := []client.DBRP{
{
Database: "DATABASE_NAME",
RetentionPolicy: "RP_NAME",
},
}
ti, err := cli.Task(cli.TaskLink(id), nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph TASK_ID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestServer_ListTask_Defaults(t *testing.T) {
s, cli := OpenDefaultServer()
baseURL := s.URL()
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
id := "task_id"
tick := "stream\n |from()\n"
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: client.StreamTask,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
resp, err := http.Get(baseURL + "/tasks")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if exp, got := http.StatusOK, resp.StatusCode; exp != got {
t.Errorf("unexpected status code, got %d exp %d", got, exp)
}
// Response type
type response struct {
Tasks []client.Task `json:"tasks"`
}
dec := json.NewDecoder(resp.Body)
tasks := response{}
dec.Decode(&tasks)
if exp, got := 1, len(tasks.Tasks); exp != got {
t.Fatalf("unexpected tasks count, got %d exp %d", got, exp)
}
task = tasks.Tasks[0]
if task.ID != id {
t.Fatalf("unexpected id got %s exp %s", task.ID, id)
}
if task.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", task.Type, client.StreamTask)
}
if task.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", task.Status, client.Disabled)
}
if !reflect.DeepEqual(task.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", task.DBRPs, dbrps)
}
if task.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", task.TICKscript, tick)
}
dot := "digraph task_id {\nstream0 -> from1;\n}"
if task.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", task.Dot, dot)
}
}
func TestServer_CreateTask_ValidIDs(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
testCases := []struct {
id string
valid bool
}{
{
id: "task_id",
valid: true,
},
{
id: "task_id7",
valid: true,
},
{
id: "task.id7",
valid: true,
},
{
id: "task-id7",
valid: true,
},
{
id: "tásk7",
valid: true,
},
{
id: "invalid id",
valid: false,
},
{
id: "invalid*id",
valid: false,
},
{
id: "task/id7",
valid: false,
},
}
for _, tc := range testCases {
id := tc.id
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if !tc.valid {
exp := fmt.Sprintf("task ID must contain only letters, numbers, '-', '.' and '_'. %q", id)
if err.Error() != exp {
t.Errorf("unexpected error: got %s exp %s", err.Error(), exp)
}
continue
}
if err != nil {
t.Fatal(err)
}
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph " + id + " {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
}
func TestServer_CreateRecording_ValidIDs(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `stream
|from()
.measurement('test')
`
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: "task_id",
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
testCases := []struct {
id string
valid bool
}{
{
id: "recording_id",
valid: true,
},
{
id: "recording_id7",
valid: true,
},
{
id: "recording.id7",
valid: true,
},
{
id: "recording-id7",
valid: true,
},
{
id: "récording7",
valid: true,
},
{
id: "invalid id",
valid: false,
},
{
id: "invalid*id",
valid: false,
},
{
id: "recording/id7",
valid: false,
},
}
for _, tc := range testCases {
id := tc.id
recording, err := cli.RecordStream(client.RecordStreamOptions{
ID: id,
Task: "task_id",
Stop: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
})
if !tc.valid {
exp := fmt.Sprintf("recording ID must contain only letters, numbers, '-', '.' and '_'. %q", id)
if err.Error() != exp {
t.Errorf("unexpected error: got %s exp %s", err.Error(), exp)
}
continue
}
if err != nil {
t.Fatal(err)
}
recording, err = cli.Recording(recording.Link)
if err != nil {
t.Fatal(err)
}
if exp, got := id, recording.ID; got != exp {
t.Errorf("unexpected recording ID got %s exp %s", got, exp)
}
}
}
func TestServer_CreateReplay_ValidIDs(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
}
tick := `stream
|from()
.measurement('test')
`
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: "task_id",
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
_, err = cli.RecordStream(client.RecordStreamOptions{
ID: "recording_id",
Task: "task_id",
Stop: time.Date(1970, 1, 1, 0, 0, 10, 0, time.UTC),
})
if err != nil {
t.Fatal(err)
}
testCases := []struct {
id string
valid bool
}{
{
id: "replay_id",
valid: true,
},
{
id: "replay_id7",
valid: true,
},
{
id: "replay.id7",
valid: true,
},
{
id: "replay-id7",
valid: true,
},
{
id: "réplay7",
valid: true,
},
{
id: "invalid id",
valid: false,
},
{
id: "invalid*id",
valid: false,
},
{
id: "replay/id7",
valid: false,
},
}
for _, tc := range testCases {
id := tc.id
replay, err := cli.CreateReplay(client.CreateReplayOptions{
ID: id,
Task: "task_id",
Recording: "recording_id",
Clock: client.Fast,
RecordingTime: true,
})
if !tc.valid {
exp := fmt.Sprintf("replay ID must contain only letters, numbers, '-', '.' and '_'. %q", id)
if err.Error() != exp {
t.Errorf("unexpected error: got %s exp %s", err.Error(), exp)
}
continue
}
if err != nil {
t.Fatal(err)
}
replay, err = cli.Replay(replay.Link)
if err != nil {
t.Fatal(err)
}
if exp, got := id, replay.ID; got != exp {
t.Errorf("unexpected replay ID got %s exp %s", got, exp)
}
}
}
func TestServer_UpdateConfig(t *testing.T) {
type updateAction struct {
name string
element string
updateAction client.ConfigUpdateAction
expSection client.ConfigSection
expElement client.ConfigElement
}
db := NewInfluxDB(func(q string) *iclient.Response {
return &iclient.Response{}
})
defMap := map[string]interface{}{
"default": false,
"disable-subscriptions": false,
"enabled": true,
"excluded-subscriptions": map[string]interface{}{"_kapacitor": []interface{}{"autogen"}},
"http-port": float64(0),
"insecure-skip-verify": false,
"kapacitor-hostname": "",
"http-shared-secret": false,
"name": "default",
"password": true,
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"startup-timeout": "1h0m0s",
"subscription-protocol": "http",
"subscription-mode": "cluster",
"subscription-path": "",
"subscriptions": nil,
"subscriptions-sync-interval": "1m0s",
"timeout": "0s",
"token": false,
"udp-bind": "",
"udp-buffer": float64(1e3),
"udp-read-buffer": float64(0),
"urls": []interface{}{db.URL()},
"username": "bob",
"compression": "gzip",
}
deepCopyMapWithReplace := func(m map[string]interface{}) func(replacements ...map[string]interface{}) map[string]interface{} {
var a interface{} = "" // we have to do this to prevent gob.Register from panicing
gob.Register([]string{})
gob.Register(map[string]interface{}{})
gob.Register([]interface{}{})
gob.Register(a)
return func(replacements ...map[string]interface{}) map[string]interface{} {
// we can't just use json here because json(foo) doesn't always equal decodedJson(foo)
var buf bytes.Buffer // Stand-in for a network connection
enc := gob.NewEncoder(&buf) // Will write to network.
dec := gob.NewDecoder(&buf) // Will read from network.
if err := enc.Encode(m); err != nil {
t.Fatal(err)
}
mCopy := map[string]interface{}{}
if err := dec.Decode(&mCopy); err != nil {
t.Fatal(err)
}
for i := range replacements {
for k, v := range replacements[i] {
v := v
if err := enc.Encode(v); err != nil {
t.Fatal(err)
}
vCopy := reflect.Indirect(reflect.New(reflect.TypeOf(v)))
if err := dec.DecodeValue(vCopy); err != nil {
t.Fatal(err)
}
mCopy[k] = vCopy.Interface()
}
}
return mCopy
}
}
if !cmp.Equal(deepCopyMapWithReplace(defMap)(), defMap) {
t.Fatalf("deepCopyMapWithReplace is broken expected %v, got %v", defMap, deepCopyMapWithReplace(defMap)())
}
{ // new block to keep vars clean
mapReplaceRes := deepCopyMapWithReplace(map[string]interface{}{"1": []string{"ok"}, "2": 3})(map[string]interface{}{"1": []string{"oks"}})
if !cmp.Equal(mapReplaceRes, map[string]interface{}{"1": []string{"oks"}, "2": 3}) {
t.Fatal(cmp.Diff(mapReplaceRes, map[string]interface{}{"1": []string{"oks"}, "2": 3}))
}
}
testCases := []struct {
section string
element string
setDefaults func(*server.Config)
expDefaultSection client.ConfigSection
expDefaultElement client.ConfigElement
updates []updateAction
}{
{
section: "influxdb",
element: "default",
setDefaults: func(c *server.Config) {
c.InfluxDB[0].Enabled = true
c.InfluxDB[0].Username = "bob"
c.InfluxDB[0].Password = "secret"
c.InfluxDB[0].URLs = []string{db.URL()}
// Set really long timeout since we shouldn't hit it
c.InfluxDB[0].StartUpTimeout = toml.Duration(time.Hour)
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(),
Redacted: []string{
"password",
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(),
Redacted: []string{
"password",
"token",
},
},
updates: []updateAction{
{
name: "update url",
// Set Invalid URL to make sure we can fix it without waiting for connection timeouts
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"urls": []interface{}{"http://192.0.2.0:8086"},
},
},
element: "default",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(map[string]interface{}{"urls": []interface{}{"http://192.0.2.0:8086"}}),
Redacted: []string{
"password",
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(map[string]interface{}{"urls": []interface{}{"http://192.0.2.0:8086"}}),
Redacted: []string{
"password",
"token",
},
},
},
{
name: "update default, subscription-protocol, subscriptions",
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
},
},
element: "default",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{"urls": []interface{}{"http://192.0.2.0:8086"}},
map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
}),
Redacted: []string{
"password",
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{"urls": []interface{}{"http://192.0.2.0:8086"}},
map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
}),
Redacted: []string{
"password",
"token",
},
},
},
{
name: "delete urls",
updateAction: client.ConfigUpdateAction{
Delete: []string{"urls"},
},
element: "default",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
}),
Redacted: []string{
"password",
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
}),
Redacted: []string{
"password",
"token",
},
},
},
{
name: "new",
updateAction: client.ConfigUpdateAction{
Add: map[string]interface{}{
"name": "new",
"urls": []string{db.URL()},
},
},
element: "new",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb"},
Elements: []client.ConfigElement{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/default"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{
"default": true,
"subscription-protocol": "https",
"subscriptions": map[string]interface{}{"_internal": []interface{}{"monitor"}},
}),
Redacted: []string{
"password",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/new"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{
"name": "new",
"enabled": false,
"password": false,
"startup-timeout": "5m0s",
"username": "",
}),
Redacted: []string{
"password",
"token",
},
},
},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/influxdb/new"},
Options: deepCopyMapWithReplace(defMap)(
map[string]interface{}{
"name": "new",
"enabled": false,
"password": false,
"startup-timeout": "5m0s",
"username": "",
}),
Redacted: []string{
"password",
"token",
},
},
},
},
},
{
section: "alerta",
setDefaults: func(c *server.Config) {
c.Alerta.URL = "http://alerta.example.com"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta/"},
Options: map[string]interface{}{
"enabled": false,
"environment": "",
"origin": "",
"token": false,
"token-prefix": "",
"url": "http://alerta.example.com",
"insecure-skip-verify": false,
"timeout": "0s",
},
Redacted: []string{
"token",
}},
},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta/"},
Options: map[string]interface{}{
"enabled": false,
"environment": "",
"origin": "",
"token": false,
"token-prefix": "",
"url": "http://alerta.example.com",
"insecure-skip-verify": false,
"timeout": "0s",
},
Redacted: []string{
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"token": "token",
"origin": "kapacitor",
"timeout": "3h",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta/"},
Options: map[string]interface{}{
"enabled": false,
"environment": "",
"origin": "kapacitor",
"token": true,
"token-prefix": "",
"url": "http://alerta.example.com",
"insecure-skip-verify": false,
"timeout": "3h0m0s",
},
Redacted: []string{
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/alerta/"},
Options: map[string]interface{}{
"enabled": false,
"environment": "",
"origin": "kapacitor",
"token": true,
"token-prefix": "",
"url": "http://alerta.example.com",
"insecure-skip-verify": false,
"timeout": "3h0m0s",
},
Redacted: []string{
"token",
},
},
},
},
},
{
section: "httppost",
element: "test",
setDefaults: func(c *server.Config) {
apc := httppost.Config{
Endpoint: "test",
URLTemplate: "http://httppost.example.com",
Headers: map[string]string{
"testing": "works",
},
}
c.HTTPPost = httppost.Configs{apc}
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost"},
Elements: []client.ConfigElement{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost/test"},
Options: map[string]interface{}{
"endpoint": "test",
"url": "http://httppost.example.com",
"headers": map[string]interface{}{
"testing": "works",
},
"basic-auth": false,
"alert-template": "",
"alert-template-file": "",
"row-template": "",
"row-template-file": "",
},
Redacted: []string{
"basic-auth",
}},
},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost/test"},
Options: map[string]interface{}{
"endpoint": "test",
"url": "http://httppost.example.com",
"headers": map[string]interface{}{
"testing": "works",
},
"basic-auth": false,
"alert-template": "",
"alert-template-file": "",
"row-template": "",
"row-template-file": "",
},
Redacted: []string{
"basic-auth",
},
},
updates: []updateAction{
{
element: "test",
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"headers": map[string]string{
"testing": "more",
},
"basic-auth": httppost.BasicAuth{
Username: "usr",
Password: "pass",
},
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost/test"},
Options: map[string]interface{}{
"endpoint": "test",
"url": "http://httppost.example.com",
"headers": map[string]interface{}{
"testing": "more",
},
"basic-auth": true,
"alert-template": "",
"alert-template-file": "",
"row-template": "",
"row-template-file": "",
},
Redacted: []string{
"basic-auth",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/httppost/test"},
Options: map[string]interface{}{
"endpoint": "test",
"url": "http://httppost.example.com",
"headers": map[string]interface{}{
"testing": "more",
},
"basic-auth": true,
"alert-template": "",
"alert-template-file": "",
"row-template": "",
"row-template-file": "",
},
Redacted: []string{
"basic-auth",
},
},
},
},
},
{
section: "pushover",
setDefaults: func(c *server.Config) {
c.Pushover.URL = "http://pushover.example.com"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover/"},
Options: map[string]interface{}{
"enabled": false,
"token": false,
"user-key": false,
"url": "http://pushover.example.com",
},
Redacted: []string{
"token",
"user-key",
}},
},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover/"},
Options: map[string]interface{}{
"enabled": false,
"token": false,
"user-key": false,
"url": "http://pushover.example.com",
},
Redacted: []string{
"token",
"user-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"token": "token",
"user-key": "kapacitor",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover/"},
Options: map[string]interface{}{
"enabled": false,
"user-key": true,
"token": true,
"url": "http://pushover.example.com",
},
Redacted: []string{
"token",
"user-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pushover/"},
Options: map[string]interface{}{
"enabled": false,
"user-key": true,
"token": true,
"url": "http://pushover.example.com",
},
Redacted: []string{
"token",
"user-key",
},
},
},
},
},
{
section: "kubernetes",
setDefaults: func(c *server.Config) {
c.Kubernetes = k8s.Configs{k8s.NewConfig()}
c.Kubernetes[0].APIServers = []string{"http://localhost:80001"}
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes/"},
Options: map[string]interface{}{
"id": "",
"api-servers": []interface{}{"http://localhost:80001"},
"ca-path": "",
"enabled": false,
"in-cluster": false,
"namespace": "",
"token": false,
"resource": "",
},
Redacted: []string{
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes/"},
Options: map[string]interface{}{
"id": "",
"api-servers": []interface{}{"http://localhost:80001"},
"ca-path": "",
"enabled": false,
"in-cluster": false,
"namespace": "",
"token": false,
"resource": "",
},
Redacted: []string{
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"token": "secret",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes/"},
Options: map[string]interface{}{
"id": "",
"api-servers": []interface{}{"http://localhost:80001"},
"ca-path": "",
"enabled": false,
"in-cluster": false,
"namespace": "",
"token": true,
"resource": "",
},
Redacted: []string{
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/kubernetes/"},
Options: map[string]interface{}{
"id": "",
"api-servers": []interface{}{"http://localhost:80001"},
"ca-path": "",
"enabled": false,
"in-cluster": false,
"namespace": "",
"token": true,
"resource": "",
},
Redacted: []string{
"token",
},
},
},
},
},
{
section: "hipchat",
setDefaults: func(c *server.Config) {
c.HipChat.URL = "http://hipchat.example.com"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"room": "",
"state-changes-only": false,
"token": false,
"url": "http://hipchat.example.com",
},
Redacted: []string{
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"room": "",
"state-changes-only": false,
"token": false,
"url": "http://hipchat.example.com",
},
Redacted: []string{
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"token": "token",
"room": "kapacitor",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"room": "kapacitor",
"state-changes-only": false,
"token": true,
"url": "http://hipchat.example.com",
},
Redacted: []string{
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/hipchat/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"room": "kapacitor",
"state-changes-only": false,
"token": true,
"url": "http://hipchat.example.com",
},
Redacted: []string{
"token",
},
},
},
},
},
{
section: "mqtt",
setDefaults: func(c *server.Config) {
cfg := &mqtt.Config{
Name: "default",
URL: "tcp://mqtt.example.com:1883",
}
cfg.SetNewClientF(mqtttest.NewClient)
c.MQTT = mqtt.Configs{
*cfg,
}
},
element: "default",
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt/default"},
Options: map[string]interface{}{
"enabled": false,
"name": "default",
"default": false,
"url": "tcp://mqtt.example.com:1883",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
"client-id": "",
"username": "",
"password": false,
},
Redacted: []string{
"password",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt/default"},
Options: map[string]interface{}{
"enabled": false,
"name": "default",
"default": false,
"url": "tcp://mqtt.example.com:1883",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
"client-id": "",
"username": "",
"password": false,
},
Redacted: []string{
"password",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"client-id": "kapacitor-default",
"password": "super secret",
},
},
element: "default",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt/default"},
Options: map[string]interface{}{
"enabled": false,
"name": "default",
"default": false,
"url": "tcp://mqtt.example.com:1883",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
"client-id": "kapacitor-default",
"username": "",
"password": true,
},
Redacted: []string{
"password",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/mqtt/default"},
Options: map[string]interface{}{
"enabled": false,
"name": "default",
"default": false,
"url": "tcp://mqtt.example.com:1883",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
"client-id": "kapacitor-default",
"username": "",
"password": true,
},
Redacted: []string{
"password",
},
},
},
},
},
{
section: "opsgenie",
setDefaults: func(c *server.Config) {
c.OpsGenie.URL = "http://opsgenie.example.com"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": false,
"recipients": nil,
"recovery_url": opsgenie.DefaultOpsGenieRecoveryURL,
"teams": nil,
"url": "http://opsgenie.example.com",
},
Redacted: []string{
"api-key",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": false,
"recipients": nil,
"recovery_url": opsgenie.DefaultOpsGenieRecoveryURL,
"teams": nil,
"url": "http://opsgenie.example.com",
},
Redacted: []string{
"api-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"api-key": "token",
"global": true,
"teams": []string{"teamA", "teamB"},
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": true,
"recipients": nil,
"recovery_url": opsgenie.DefaultOpsGenieRecoveryURL,
"teams": []interface{}{"teamA", "teamB"},
"url": "http://opsgenie.example.com",
},
Redacted: []string{
"api-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": true,
"recipients": nil,
"recovery_url": opsgenie.DefaultOpsGenieRecoveryURL,
"teams": []interface{}{"teamA", "teamB"},
"url": "http://opsgenie.example.com",
},
Redacted: []string{
"api-key",
},
},
},
},
},
{
section: "opsgenie2",
setDefaults: func(c *server.Config) {
c.OpsGenie2.URL = "http://opsgenie2.example.com"
c.OpsGenie2.RecoveryAction = "notes"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": false,
"details": false,
"recipients": nil,
"teams": nil,
"url": "http://opsgenie2.example.com",
"recovery_action": "notes",
},
Redacted: []string{
"api-key",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": false,
"details": false,
"recipients": nil,
"teams": nil,
"url": "http://opsgenie2.example.com",
"recovery_action": "notes",
},
Redacted: []string{
"api-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"api-key": "token",
"global": true,
"teams": []string{"teamA", "teamB"},
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": true,
"details": false,
"recipients": nil,
"teams": []interface{}{"teamA", "teamB"},
"url": "http://opsgenie2.example.com",
"recovery_action": "notes",
},
Redacted: []string{
"api-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/opsgenie2/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": true,
"details": false,
"recipients": nil,
"teams": []interface{}{"teamA", "teamB"},
"url": "http://opsgenie2.example.com",
"recovery_action": "notes",
},
Redacted: []string{
"api-key",
},
},
},
},
},
{
section: "pagerduty",
setDefaults: func(c *server.Config) {
c.PagerDuty.ServiceKey = "secret"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"service-key": true,
"url": pagerduty.DefaultPagerDutyAPIURL,
},
Redacted: []string{
"service-key",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"service-key": true,
"url": pagerduty.DefaultPagerDutyAPIURL,
},
Redacted: []string{
"service-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"service-key": "",
"enabled": true,
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"service-key": false,
"url": pagerduty.DefaultPagerDutyAPIURL,
},
Redacted: []string{
"service-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"service-key": false,
"url": pagerduty.DefaultPagerDutyAPIURL,
},
Redacted: []string{
"service-key",
},
},
},
},
},
{
section: "pagerduty2",
setDefaults: func(c *server.Config) {
c.PagerDuty2.RoutingKey = "secret"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"routing-key": true,
"url": pagerduty2.DefaultPagerDuty2APIURL,
},
Redacted: []string{
"routing-key",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"routing-key": true,
"url": pagerduty2.DefaultPagerDuty2APIURL,
},
Redacted: []string{
"routing-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"routing-key": "",
"enabled": true,
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"routing-key": false,
"url": pagerduty2.DefaultPagerDuty2APIURL,
},
Redacted: []string{
"routing-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/pagerduty2/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"routing-key": false,
"url": pagerduty2.DefaultPagerDuty2APIURL,
},
Redacted: []string{
"routing-key",
},
},
},
},
},
{
section: "smtp",
setDefaults: func(c *server.Config) {
c.SMTP.Host = "smtp.example.com"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp/"},
Options: map[string]interface{}{
"enabled": false,
"from": "",
"global": false,
"host": "smtp.example.com",
"idle-timeout": "30s",
"no-verify": false,
"password": false,
"port": float64(25),
"state-changes-only": false,
"to": nil,
"username": "",
},
Redacted: []string{
"password",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp/"},
Options: map[string]interface{}{
"enabled": false,
"from": "",
"global": false,
"host": "smtp.example.com",
"idle-timeout": "30s",
"no-verify": false,
"password": false,
"port": float64(25),
"state-changes-only": false,
"to": nil,
"username": "",
},
Redacted: []string{
"password",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"idle-timeout": "1m0s",
"global": true,
"password": "secret",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp/"},
Options: map[string]interface{}{
"enabled": false,
"from": "",
"global": true,
"host": "smtp.example.com",
"idle-timeout": "1m0s",
"no-verify": false,
"password": true,
"port": float64(25),
"state-changes-only": false,
"to": nil,
"username": "",
},
Redacted: []string{
"password",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/smtp/"},
Options: map[string]interface{}{
"enabled": false,
"from": "",
"global": true,
"host": "smtp.example.com",
"idle-timeout": "1m0s",
"no-verify": false,
"password": true,
"port": float64(25),
"state-changes-only": false,
"to": nil,
"username": "",
},
Redacted: []string{
"password",
},
},
},
},
},
{
section: "sensu",
setDefaults: func(c *server.Config) {
c.Sensu.Addr = "sensu.example.com:3000"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu/"},
Options: map[string]interface{}{
"addr": "sensu.example.com:3000",
"enabled": false,
"source": "Kapacitor",
"handlers": nil,
},
Redacted: nil,
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu/"},
Options: map[string]interface{}{
"addr": "sensu.example.com:3000",
"enabled": false,
"source": "Kapacitor",
"handlers": nil,
},
Redacted: nil,
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"addr": "sensu.local:3000",
"enabled": true,
"source": "Kapacitor",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu/"},
Options: map[string]interface{}{
"addr": "sensu.local:3000",
"enabled": true,
"source": "Kapacitor",
"handlers": nil,
},
Redacted: nil,
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/sensu/"},
Options: map[string]interface{}{
"addr": "sensu.local:3000",
"enabled": true,
"source": "Kapacitor",
"handlers": nil,
},
Redacted: nil,
},
},
},
},
{
section: "servicenow",
setDefaults: func(c *server.Config) {
c.ServiceNow.URL = "https://instance.service-now.com/api/global/em/jsonv2"
c.ServiceNow.Source = "Kapacitor"
c.ServiceNow.Username = ""
c.ServiceNow.Password = ""
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://instance.service-now.com/api/global/em/jsonv2",
"source": "Kapacitor",
"username": "",
"password": false,
},
Redacted: []string{
"password",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://instance.service-now.com/api/global/em/jsonv2",
"source": "Kapacitor",
"username": "",
"password": false,
},
Redacted: []string{
"password",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"url": "https://dev12345.service-now.com/api/global/em/jsonv2",
"username": "dev",
"password": "12345",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev12345.service-now.com/api/global/em/jsonv2",
"source": "Kapacitor",
"username": "dev",
"password": true,
},
Redacted: []string{
"password",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/servicenow/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev12345.service-now.com/api/global/em/jsonv2",
"source": "Kapacitor",
"username": "dev",
"password": true,
},
Redacted: []string{
"password",
},
},
},
},
},
{
section: "bigpanda",
setDefaults: func(c *server.Config) {
c.BigPanda.URL = "https://api.bigpanda.io/data/v2/alerts"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://api.bigpanda.io/data/v2/alerts",
"insecure-skip-verify": false,
"token": false,
"app-key": "",
},
Redacted: []string{
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://api.bigpanda.io/data/v2/alerts",
"insecure-skip-verify": false,
"token": false,
"app-key": "",
},
Redacted: []string{
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"url": "https://dev123456.bigpanda.io/data/v2/alerts",
"app-key": "appkey-123",
"token": "token-123",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev123456.bigpanda.io/data/v2/alerts",
"token": true,
"app-key": "appkey-123",
"insecure-skip-verify": false,
},
Redacted: []string{
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/bigpanda/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev123456.bigpanda.io/data/v2/alerts",
"app-key": "appkey-123",
"token": true,
"insecure-skip-verify": false,
},
Redacted: []string{
"token",
},
},
},
},
},
{
section: "slack",
setDefaults: func(c *server.Config) {
cfg := &slack.Config{
Global: true,
Default: true,
Username: slack.DefaultUsername,
}
c.Slack = slack.Configs{
*cfg,
}
},
element: "",
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"token": false,
"url": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"url": false,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Add: map[string]interface{}{
"workspace": "company_private",
"enabled": true,
"global": false,
"channel": "#general",
"username": slack.DefaultUsername,
"url": "http://slack.example.com/secret-token",
"token": "my_other_secret",
},
},
element: "company_private",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"url": false,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_private"},
Options: map[string]interface{}{
"workspace": "company_private",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": true,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_private"},
Options: map[string]interface{}{
"workspace": "company_private",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": true,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
{
updateAction: client.ConfigUpdateAction{
Add: map[string]interface{}{
"workspace": "company_public",
"enabled": true,
"global": false,
"channel": "#general",
"username": slack.DefaultUsername,
"url": "http://slack.example.com/secret-token",
},
},
element: "company_public",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack"},
Elements: []client.ConfigElement{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"url": false,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_private"},
Options: map[string]interface{}{
"workspace": "company_private",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": true,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": false,
"username": "testbot",
},
},
element: "company_public",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack"},
Elements: []client.ConfigElement{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"url": false,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_private"},
Options: map[string]interface{}{
"workspace": "company_private",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": true,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": false,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "testbot",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": false,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "testbot",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
{
updateAction: client.ConfigUpdateAction{
Delete: []string{"username"},
},
element: "company_public",
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack"},
Elements: []client.ConfigElement{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/"},
Options: map[string]interface{}{
"workspace": "",
"default": true,
"channel": "",
"enabled": false,
"global": true,
"icon-emoji": "",
"state-changes-only": false,
"url": false,
"token": false,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_private"},
Options: map[string]interface{}{
"workspace": "company_private",
"channel": "#general",
"default": false,
"enabled": true,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": true,
"username": "kapacitor",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": false,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/slack/company_public"},
Options: map[string]interface{}{
"workspace": "company_public",
"channel": "#general",
"default": false,
"enabled": false,
"global": false,
"icon-emoji": "",
"state-changes-only": false,
"url": true,
"token": false,
"username": "",
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: []string{
"url",
"token",
},
},
},
},
},
{
section: "snmptrap",
setDefaults: func(c *server.Config) {
c.SNMPTrap.Community = "test"
c.SNMPTrap.Retries = 2.0
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap/"},
Options: map[string]interface{}{
"addr": "localhost:162",
"enabled": false,
"community": true,
"retries": 2.0,
},
Redacted: []string{
"community",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap/"},
Options: map[string]interface{}{
"addr": "localhost:162",
"enabled": false,
"community": true,
"retries": 2.0,
},
Redacted: []string{
"community",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"addr": "snmptrap.example.com:162",
"community": "public",
"retries": 1.0,
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap/"},
Options: map[string]interface{}{
"addr": "snmptrap.example.com:162",
"enabled": true,
"community": true,
"retries": 1.0,
},
Redacted: []string{
"community",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/snmptrap/"},
Options: map[string]interface{}{
"addr": "snmptrap.example.com:162",
"enabled": true,
"community": true,
"retries": 1.0,
},
Redacted: []string{
"community",
},
},
},
},
},
{
section: "swarm",
setDefaults: func(c *server.Config) {
c.Swarm = swarm.Configs{swarm.Config{
Servers: []string{"http://localhost:80001"},
}}
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm/"},
Options: map[string]interface{}{
"id": "",
"enabled": false,
"servers": []interface{}{"http://localhost:80001"},
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: nil,
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm/"},
Options: map[string]interface{}{
"id": "",
"enabled": false,
"servers": []interface{}{"http://localhost:80001"},
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: nil,
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm/"},
Options: map[string]interface{}{
"id": "",
"enabled": true,
"servers": []interface{}{"http://localhost:80001"},
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: nil,
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/swarm/"},
Options: map[string]interface{}{
"id": "",
"enabled": true,
"servers": []interface{}{"http://localhost:80001"},
"ssl-ca": "",
"ssl-cert": "",
"ssl-key": "",
"insecure-skip-verify": false,
},
Redacted: nil,
},
},
},
},
{
section: "talk",
setDefaults: func(c *server.Config) {
c.Talk.AuthorName = "Kapacitor"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk/"},
Options: map[string]interface{}{
"enabled": false,
"url": false,
"author_name": "Kapacitor",
},
Redacted: []string{
"url",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk/"},
Options: map[string]interface{}{
"enabled": false,
"url": false,
"author_name": "Kapacitor",
},
Redacted: []string{
"url",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"url": "http://talk.example.com/secret-token",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk/"},
Options: map[string]interface{}{
"enabled": true,
"url": true,
"author_name": "Kapacitor",
},
Redacted: []string{
"url",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/talk/"},
Options: map[string]interface{}{
"enabled": true,
"url": true,
"author_name": "Kapacitor",
},
Redacted: []string{
"url",
},
},
},
},
},
{
section: "teams",
setDefaults: func(c *server.Config) {
c.Teams.ChannelURL = "http://teams.example.com/abcde"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"channel-url": "http://teams.example.com/abcde",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"channel-url": "http://teams.example.com/abcde",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"global": true,
"state-changes-only": true,
"channel-url": "http://teams.example.com/12345",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams/"},
Options: map[string]interface{}{
"enabled": false,
"global": true,
"state-changes-only": true,
"channel-url": "http://teams.example.com/12345",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/teams/"},
Options: map[string]interface{}{
"enabled": false,
"global": true,
"state-changes-only": true,
"channel-url": "http://teams.example.com/12345",
},
},
},
},
},
{
section: "telegram",
setDefaults: func(c *server.Config) {
c.Telegram.ChatId = "kapacitor"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram/"},
Options: map[string]interface{}{
"chat-id": "kapacitor",
"disable-notification": false,
"disable-web-page-preview": false,
"enabled": false,
"global": false,
"parse-mode": "",
"state-changes-only": false,
"token": false,
"url": telegram.DefaultTelegramURL,
},
Redacted: []string{
"token",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram/"},
Options: map[string]interface{}{
"chat-id": "kapacitor",
"disable-notification": false,
"disable-web-page-preview": false,
"enabled": false,
"global": false,
"parse-mode": "",
"state-changes-only": false,
"token": false,
"url": telegram.DefaultTelegramURL,
},
Redacted: []string{
"token",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"token": "token",
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram/"},
Options: map[string]interface{}{
"chat-id": "kapacitor",
"disable-notification": false,
"disable-web-page-preview": false,
"enabled": true,
"global": false,
"parse-mode": "",
"state-changes-only": false,
"token": true,
"url": telegram.DefaultTelegramURL,
},
Redacted: []string{
"token",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/telegram/"},
Options: map[string]interface{}{
"chat-id": "kapacitor",
"disable-notification": false,
"disable-web-page-preview": false,
"enabled": true,
"global": false,
"parse-mode": "",
"state-changes-only": false,
"token": true,
"url": telegram.DefaultTelegramURL,
},
Redacted: []string{
"token",
},
},
},
},
},
{
section: "victorops",
setDefaults: func(c *server.Config) {
c.VictorOps.RoutingKey = "test"
c.VictorOps.APIKey = "secret"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": false,
"routing-key": "test",
"url": victorops.DefaultVictorOpsAPIURL,
"json-data": false,
},
Redacted: []string{
"api-key",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops/"},
Options: map[string]interface{}{
"api-key": true,
"enabled": false,
"global": false,
"routing-key": "test",
"url": victorops.DefaultVictorOpsAPIURL,
"json-data": false,
},
Redacted: []string{
"api-key",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"api-key": "",
"global": true,
"json-data": true,
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": true,
"routing-key": "test",
"url": victorops.DefaultVictorOpsAPIURL,
"json-data": true,
},
Redacted: []string{
"api-key",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/victorops/"},
Options: map[string]interface{}{
"api-key": false,
"enabled": false,
"global": true,
"routing-key": "test",
"url": victorops.DefaultVictorOpsAPIURL,
"json-data": true,
},
Redacted: []string{
"api-key",
},
},
},
},
},
{
section: "zenoss",
setDefaults: func(c *server.Config) {
c.Zenoss.URL = "https://tenant.zenoss.io:8080/zport/dmd/evconsole_router"
c.Zenoss.Collector = "Kapacitor"
},
expDefaultSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://tenant.zenoss.io:8080/zport/dmd/evconsole_router",
"username": "",
"password": false,
"action": "EventsRouter",
"method": "add_event",
"type": "rpc",
"tid": float64(1),
"collector": "Kapacitor",
"severity-map": map[string]interface{}{
"ok": "Clear", "info": "Info", "warning": "Warning", "critical": "Critical",
},
},
Redacted: []string{
"password",
},
}},
},
expDefaultElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss/"},
Options: map[string]interface{}{
"enabled": false,
"global": false,
"state-changes-only": false,
"url": "https://tenant.zenoss.io:8080/zport/dmd/evconsole_router",
"username": "",
"password": false,
"action": "EventsRouter",
"method": "add_event",
"type": "rpc",
"tid": float64(1),
"collector": "Kapacitor",
"severity-map": map[string]interface{}{
"ok": "Clear", "info": "Info", "warning": "Warning", "critical": "Critical",
},
},
Redacted: []string{
"password",
},
},
updates: []updateAction{
{
updateAction: client.ConfigUpdateAction{
Set: map[string]interface{}{
"enabled": true,
"url": "https://dev12345.zenoss.io:8080/zport/dmd/evconsole_router",
"username": "dev",
"password": "12345",
"action": "ScriptsRouter",
"method": "kapa_handler",
"severity-map": zenoss.SeverityMap{
OK: 0, Info: 2, Warning: 3, Critical: 5,
},
},
},
expSection: client.ConfigSection{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss"},
Elements: []client.ConfigElement{{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev12345.zenoss.io:8080/zport/dmd/evconsole_router",
"username": "dev",
"password": true,
"action": "ScriptsRouter",
"method": "kapa_handler",
"type": "rpc",
"tid": float64(1),
"collector": "Kapacitor",
"severity-map": map[string]interface{}{
"ok": float64(0), "info": float64(2), "warning": float64(3), "critical": float64(5),
},
},
Redacted: []string{
"password",
},
}},
},
expElement: client.ConfigElement{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/config/zenoss/"},
Options: map[string]interface{}{
"enabled": true,
"global": false,
"state-changes-only": false,
"url": "https://dev12345.zenoss.io:8080/zport/dmd/evconsole_router",
"username": "dev",
"password": true,
"action": "ScriptsRouter",
"method": "kapa_handler",
"type": "rpc",
"tid": float64(1),
"collector": "Kapacitor",
"severity-map": map[string]interface{}{
"ok": float64(0), "info": float64(2), "warning": float64(3), "critical": float64(5),
},
},
Redacted: []string{
"password",
},
},
},
},
},
}
compareElements := func(got, exp client.ConfigElement) error {
if got.Link != exp.Link {
return fmt.Errorf("elements have different links, got %v exp %v", got.Link, exp.Link)
}
if !cmp.Equal(exp.Options, got.Options) {
return fmt.Errorf("unexpected config option difference \n %s", cmp.Diff(exp.Options, got.Options))
}
if len(got.Redacted) != len(exp.Redacted) {
return fmt.Errorf("unexpected element redacted lists: %s, \n%s", got.Redacted, cmp.Diff(got.Redacted, exp.Redacted))
}
sort.Strings(got.Redacted)
sort.Strings(exp.Redacted)
for i := range exp.Redacted {
if got.Redacted[i] != exp.Redacted[i] {
return fmt.Errorf("unexpected element redacted lists: %s, \n%s", got.Redacted, cmp.Diff(got.Redacted, exp.Redacted))
}
}
return nil
}
compareSections := func(got, exp client.ConfigSection) error {
if got.Link != exp.Link {
return fmt.Errorf("sections have different links, got %v exp %v", got.Link, exp.Link)
}
if len(got.Elements) != len(exp.Elements) {
return fmt.Errorf("sections are different lengths, got %d exp %d", len(got.Elements), len(exp.Elements))
}
for i := range exp.Elements {
if err := compareElements(got.Elements[i], exp.Elements[i]); err != nil {
return errors.Wrapf(err, "section element %d are not equal", i)
}
}
return nil
}
validate := func(
cli *client.Client,
section,
element string,
expSection client.ConfigSection,
expElement client.ConfigElement,
) error {
// Get all sections
if config, err := cli.ConfigSections(); err != nil {
return errors.Wrap(err, "failed to get sections")
} else {
if err := compareSections(config.Sections[section], expSection); err != nil {
return fmt.Errorf("%s: %v", section, err)
}
}
// Get the specific section
sectionLink := cli.ConfigSectionLink(section)
if got, err := cli.ConfigSection(sectionLink); err != nil {
return err
} else {
if err := compareSections(got, expSection); err != nil {
return fmt.Errorf("%s: %v", section, err)
}
}
elementLink := cli.ConfigElementLink(section, element)
// Get the specific element
if got, err := cli.ConfigElement(elementLink); err != nil {
return err
} else {
if err := compareElements(got, expElement); err != nil {
return fmt.Errorf("%s/%s: %v", section, element, err)
}
}
return nil
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%s/%s-%d", tc.section, tc.element, i), func(t *testing.T) {
// Create default config
c := NewConfig()
if tc.setDefaults != nil {
tc.setDefaults(c)
}
s := OpenServer(c)
cli := Client(s)
defer s.Close()
if err := validate(cli, tc.section, tc.element, tc.expDefaultSection, tc.expDefaultElement); err != nil {
t.Errorf("unexpected defaults for %s/%s: %v", tc.section, tc.element, err)
}
for i, ua := range tc.updates {
t.Run(ua.name, func(t *testing.T) {
link := cli.ConfigElementLink(tc.section, ua.element)
if len(ua.updateAction.Add) > 0 ||
len(ua.updateAction.Remove) > 0 {
link = cli.ConfigSectionLink(tc.section)
}
if err := cli.ConfigUpdate(link, ua.updateAction); err != nil {
t.Fatal(err)
}
if err := validate(cli, tc.section, ua.element, ua.expSection, ua.expElement); err != nil {
t.Errorf("unexpected update result %d for %s/%s: %v", i, tc.section, ua.element, err)
}
})
}
})
}
}
func TestServer_ListServiceTests(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
serviceTests, err := cli.ListServiceTests(nil)
if err != nil {
t.Fatal(err)
}
expServiceTests := client.ServiceTests{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests"},
Services: []client.ServiceTest{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/alerta"},
Name: "alerta",
Options: client.ServiceTestOptions{
"resource": "testResource",
"event": "testEvent",
"environment": "",
"severity": "critical",
"group": "testGroup",
"value": "testValue",
"message": "test alerta message",
"origin": "",
"service": []interface{}{
"testServiceA",
"testServiceB",
},
"correlate": []interface{}{
"testServiceX",
"testServiceY",
},
"attributes": map[string]interface{}{
"testAttributeA": "A",
"testAttributeB": true,
"testAttributeC": float64(9001.0),
},
"timeout": "24h0m0s",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/azure"},
Name: "azure",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/bigpanda"},
Name: "bigpanda",
Options: client.ServiceTestOptions{
"app_key": "",
"level": "CRITICAL",
"message": "test bigpanda message",
"timestamp": "1970-01-01T00:00:01Z",
"primary_property": "",
"secondary_property": "",
"event_data": map[string]interface{}{
"Fields": map[string]interface{}{},
"Result": map[string]interface{}{
"series": interface{}(nil),
},
"Name": "testBigPanda",
"TaskName": "",
"Group": "",
"Tags": map[string]interface{}{},
"Recoverable": false,
"Category": "",
},
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/consul"},
Name: "consul",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/discord"},
Name: "discord",
Options: client.ServiceTestOptions{
"workspace": "",
"avatar-url": "https://influxdata.github.io/branding/img/downloads/influxdata-logo--symbol--pool-alpha.png",
"level": "INFO",
"message": "test discord message",
"username": "Kapacitor",
"embed-title": "Kapacitor Alert",
"time-val": "1970-01-01T00:00:01Z",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/dns"},
Name: "dns",
Options: client.ServiceTestOptions{
"id": ""},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/ec2"},
Name: "ec2",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/file-discovery"},
Name: "file-discovery",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/gce"},
Name: "gce",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/hipchat"},
Name: "hipchat",
Options: client.ServiceTestOptions{
"room": "",
"message": "test hipchat message",
"level": "CRITICAL",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/httppost"},
Name: "httppost",
Options: client.ServiceTestOptions{
"endpoint": "example",
"url": "http://localhost:3000/",
"headers": map[string]interface{}{"Auth": "secret"},
"timeout": float64(0),
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/influxdb"},
Name: "influxdb",
Options: client.ServiceTestOptions{
"cluster": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/kafka"},
Name: "kafka",
Options: client.ServiceTestOptions{
"cluster": "example",
"topic": "test",
"key": "key",
"message": "test kafka message",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/kubernetes"},
Name: "kubernetes",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/marathon"},
Name: "marathon",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/mqtt"},
Name: "mqtt",
Options: client.ServiceTestOptions{
"broker-name": "",
"topic": "",
"message": "test MQTT message",
"qos": "at-most-once",
"retained": false,
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/nerve"},
Name: "nerve",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/opsgenie"},
Name: "opsgenie",
Options: client.ServiceTestOptions{
"teams": nil,
"recipients": nil,
"message-type": "CRITICAL",
"message": "test opsgenie message",
"entity-id": "testEntityID",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/opsgenie2"},
Name: "opsgenie2",
Options: client.ServiceTestOptions{
"teams": nil,
"recipients": nil,
"message-type": "CRITICAL",
"message": "test opsgenie message",
"entity-id": "testEntityID",
"recovery_action": "notes",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/pagerduty"},
Name: "pagerduty",
Options: client.ServiceTestOptions{
"incident-key": "testIncidentKey",
"description": "test pagerduty message",
"level": "CRITICAL",
"details": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/pagerduty2"},
Name: "pagerduty2",
Options: client.ServiceTestOptions{
"alert_id": "testAlertID",
"description": "test pagerduty2 message",
"level": "CRITICAL",
"event_data": map[string]interface{}{
"Fields": map[string]interface{}{},
"Result": map[string]interface{}{
"series": interface{}(nil),
},
"Name": "testPagerDuty2",
"TaskName": "",
"Group": "",
"Tags": map[string]interface{}{},
"Recoverable": false,
"Category": "",
},
"timestamp": "2014-11-12T11:45:26.371Z",
"links": []interface{}{
map[string]interface{}{
"href": "https://example.com/a",
"text": "a",
},
map[string]interface{}{
"href": "https://example.com/b",
"text": "b",
},
},
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/pushover"},
Name: "pushover",
Options: client.ServiceTestOptions{
"user-key": "", //gohere
"message": "test pushover message",
"device": "",
"title": "",
"url": "",
"url-title": "",
"sound": "",
"level": "CRITICAL",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/scraper"},
Name: "scraper",
Options: client.ServiceTestOptions{
"name": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/sensu"},
Name: "sensu",
Options: client.ServiceTestOptions{
"name": "testName",
"output": "testOutput",
"source": "Kapacitor",
"handlers": []interface{}{},
"metadata": map[string]interface{}{},
"level": "CRITICAL",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/serverset"},
Name: "serverset",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/servicenow"},
Name: "servicenow",
Options: client.ServiceTestOptions{
"alert_id": "1001",
"message": "test servicenow message",
"level": "CRITICAL",
"source": "Kapacitor",
"node": "",
"type": "",
"resource": "",
"metric_name": "",
"message_key": "",
"additional_info": map[string]interface{}{},
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/slack"},
Name: "slack",
Options: client.ServiceTestOptions{
"workspace": "",
"channel": "",
"icon-emoji": "",
"level": "CRITICAL",
"message": "test slack message",
"username": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/smtp"},
Name: "smtp",
Options: client.ServiceTestOptions{
"to": nil,
"subject": "test subject",
"body": "test body",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/snmptrap"},
Name: "snmptrap",
Options: client.ServiceTestOptions{
"trap-oid": "1.1.1.1",
"data-list": []interface{}{
map[string]interface{}{
"oid": "1.1.1.1.2",
"type": "s",
"value": "test snmptrap message",
},
},
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/static-discovery"},
Name: "static-discovery",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/swarm"},
Name: "swarm",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/talk"},
Name: "talk",
Options: client.ServiceTestOptions{
"title": "testTitle",
"text": "test talk text",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/teams"},
Name: "teams",
Options: client.ServiceTestOptions{
"channel_url": "",
"alert_topic": "test kapacitor alert topic",
"alert_id": "foo/bar/bat",
"message": "test teams message",
"level": "CRITICAL",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/telegram"},
Name: "telegram",
Options: client.ServiceTestOptions{
"chat-id": "",
"parse-mode": "",
"message": "test telegram message",
"disable-web-page-preview": false,
"disable-notification": false,
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/triton"},
Name: "triton",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/victorops"},
Name: "victorops",
Options: client.ServiceTestOptions{
"routingKey": "",
"messageType": "CRITICAL",
"message": "test victorops message",
"entityID": "testEntityID",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/zenoss"},
Name: "zenoss",
Options: client.ServiceTestOptions{
"alert_id": "1001",
"level": "CRITICAL",
"message": "test zenoss message",
"action": "EventsRouter",
"method": "add_event",
"type": "rpc",
"tid": float64(1),
"summary": "",
"device": "",
"component": "",
"eventclasskey": "",
"eventclass": "",
"collector": "Kapacitor",
"custom_fields": map[string]interface{}{},
},
},
},
}
if got, exp := serviceTests.Link.Href, expServiceTests.Link.Href; got != exp {
t.Errorf("unexpected service tests link.href: got %s exp %s", got, exp)
}
if got, exp := len(serviceTests.Services), len(expServiceTests.Services); got != exp {
t.Fatalf("unexpected length of services: got %d exp %d", got, exp)
}
for i := range expServiceTests.Services {
exp := expServiceTests.Services[i]
got := serviceTests.Services[i]
if _, expHasTimestamp := exp.Options["timestamp"]; expHasTimestamp {
if _, gotHasTimestamp := got.Options["timestamp"]; !gotHasTimestamp {
t.Errorf("timestamp not found in server test %s:\n%s", exp.Name, cmp.Diff(exp, got))
}
exp.Options["timestamp"] = ""
got.Options["timestamp"] = ""
}
if !reflect.DeepEqual(got, exp) {
t.Errorf("unexpected server test %s:\n%s", exp.Name, cmp.Diff(exp, got))
}
}
}
func TestServer_ListServiceTests_WithPattern(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
serviceTests, err := cli.ListServiceTests(&client.ListServiceTestsOptions{
Pattern: "s*",
})
if err != nil {
t.Fatal(err)
}
expServiceTests := client.ServiceTests{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests"},
Services: []client.ServiceTest{
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/scraper"},
Name: "scraper",
Options: client.ServiceTestOptions{
"name": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/sensu"},
Name: "sensu",
Options: client.ServiceTestOptions{
"name": "testName",
"output": "testOutput",
"source": "Kapacitor",
"handlers": []interface{}{},
"metadata": map[string]interface{}{},
"level": "CRITICAL",
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/serverset"},
Name: "serverset",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/servicenow"},
Name: "servicenow",
Options: client.ServiceTestOptions{
"alert_id": "1001",
"message": "test servicenow message",
"level": "CRITICAL",
"source": "Kapacitor",
"node": "",
"type": "",
"resource": "",
"metric_name": "",
"message_key": "",
"additional_info": map[string]interface{}{},
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/slack"},
Name: "slack",
Options: client.ServiceTestOptions{
"workspace": "",
"channel": "",
"icon-emoji": "",
"level": "CRITICAL",
"message": "test slack message",
"username": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/smtp"},
Name: "smtp",
Options: client.ServiceTestOptions{
"to": nil,
"subject": "test subject",
"body": "test body",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/snmptrap"},
Name: "snmptrap",
Options: client.ServiceTestOptions{
"trap-oid": "1.1.1.1",
"data-list": []interface{}{
map[string]interface{}{
"oid": "1.1.1.1.2",
"type": "s",
"value": "test snmptrap message",
},
},
},
},
{
Link: client.Link{Relation: "self", Href: "/kapacitor/v1/service-tests/static-discovery"},
Name: "static-discovery",
Options: client.ServiceTestOptions{
"id": "",
},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/service-tests/swarm"},
Name: "swarm",
Options: client.ServiceTestOptions{
"id": "",
},
},
},
}
if got, exp := serviceTests.Link.Href, expServiceTests.Link.Href; got != exp {
t.Errorf("unexpected service tests link.href: got %s exp %s", got, exp)
}
if got, exp := len(serviceTests.Services), len(expServiceTests.Services); got != exp {
t.Fatalf("unexpected length of services: got %d exp %d", got, exp)
}
for i := range expServiceTests.Services {
exp := expServiceTests.Services[i]
got := serviceTests.Services[i]
if !reflect.DeepEqual(got, exp) {
t.Errorf("unexpected server test %s:\ngot\n%#v\nexp\n%#v\n", exp.Name, got, exp)
}
}
}
func TestServer_DoServiceTest(t *testing.T) {
db := NewInfluxDB(func(q string) *iclient.Response {
return &iclient.Response{}
})
testCases := []struct {
service string
setDefaults func(*server.Config)
options client.ServiceTestOptions
exp client.ServiceTestResult
}{
{
service: "alerta",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "bigpanda",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "hipchat",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "influxdb",
setDefaults: func(c *server.Config) {
c.InfluxDB[0].Enabled = true
c.InfluxDB[0].Name = "default"
c.InfluxDB[0].URLs = []string{db.URL()}
},
options: client.ServiceTestOptions{
"cluster": "default",
},
exp: client.ServiceTestResult{
Success: true,
Message: "",
},
},
{
service: "influxdb",
options: client.ServiceTestOptions{
"cluster": "default",
},
exp: client.ServiceTestResult{
Success: false,
Message: "cluster \"default\" is not enabled or does not exist",
},
},
{
service: "kubernetes",
options: client.ServiceTestOptions{
"id": "default",
},
exp: client.ServiceTestResult{
Success: false,
Message: "unknown kubernetes cluster \"default\"",
},
},
{
service: "mqtt",
options: client.ServiceTestOptions{
"broker-name": "default",
"topic": "test",
},
exp: client.ServiceTestResult{
Success: false,
Message: "unknown MQTT broker \"default\"",
},
},
{
service: "opsgenie",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "opsgenie2",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "failed to prepare API request: service is not enabled",
},
},
{
service: "pagerduty",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "pagerduty2",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "pushover",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "sensu",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "servicenow",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "slack",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "smtp",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "snmptrap",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "swarm",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "unknown swarm cluster \"\"",
},
},
{
service: "talk",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "teams",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "telegram",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "victorops",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
{
service: "zenoss",
options: client.ServiceTestOptions{},
exp: client.ServiceTestResult{
Success: false,
Message: "service is not enabled",
},
},
}
for _, tc := range testCases {
// Create default config
c := NewConfig()
if tc.setDefaults != nil {
tc.setDefaults(c)
}
s := OpenServer(c)
cli := Client(s)
defer s.Close()
tr, err := cli.DoServiceTest(cli.ServiceTestLink(tc.service), tc.options)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tr, tc.exp) {
t.Log("Options", tc.options)
t.Errorf("unexpected service test result for %s:\ngot\n%#v\nexp\n%#v\n", tc.service, tr, tc.exp)
}
}
}
func TestServer_AlertHandlers_CRUD(t *testing.T) {
testCases := []struct {
topic string
create client.TopicHandlerOptions
expCreate client.TopicHandler
patch client.JSONPatch
expPatch client.TopicHandler
put client.TopicHandlerOptions
expPut client.TopicHandler
}{
{
topic: "system",
create: client.TopicHandlerOptions{
ID: "myhandler",
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
},
expCreate: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/system/handlers/myhandler"},
ID: "myhandler",
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
},
patch: client.JSONPatch{
{
Path: "/kind",
Operation: "replace",
Value: "log",
},
{
Path: "/options/channel",
Operation: "remove",
},
{
Path: "/options/path",
Operation: "add",
Value: AlertLogPath,
},
},
expPatch: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/system/handlers/myhandler"},
ID: "myhandler",
Kind: "log",
Options: map[string]interface{}{
"path": AlertLogPath,
},
},
put: client.TopicHandlerOptions{
ID: "newid",
Kind: "smtp",
Options: map[string]interface{}{
"to": []string{"[email protected]"},
},
},
expPut: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/system/handlers/newid"},
ID: "newid",
Kind: "smtp",
Options: map[string]interface{}{
"to": []interface{}{"[email protected]"},
},
},
},
{
// Topic and handler have same name
topic: "slack",
create: client.TopicHandlerOptions{
ID: "slack",
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
},
expCreate: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/slack/handlers/slack"},
ID: "slack",
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
},
patch: client.JSONPatch{
{
Path: "/kind",
Operation: "replace",
Value: "log",
},
{
Path: "/options/channel",
Operation: "remove",
},
{
Path: "/options/path",
Operation: "add",
Value: AlertLogPath,
},
},
expPatch: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/slack/handlers/slack"},
ID: "slack",
Kind: "log",
Options: map[string]interface{}{
"path": AlertLogPath,
},
},
put: client.TopicHandlerOptions{
ID: "slack",
Kind: "smtp",
Options: map[string]interface{}{
"to": []string{"[email protected]"},
},
},
expPut: client.TopicHandler{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/slack/handlers/slack"},
ID: "slack",
Kind: "smtp",
Options: map[string]interface{}{
"to": []interface{}{"[email protected]"},
},
},
},
}
for _, tc := range testCases {
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
h, err := cli.CreateTopicHandler(cli.TopicHandlersLink(tc.topic), tc.create)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(h, tc.expCreate) {
t.Errorf("unexpected handler created:\ngot\n%#v\nexp\n%#v\n", h, tc.expCreate)
}
h, err = cli.PatchTopicHandler(h.Link, tc.patch)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(h, tc.expPatch) {
t.Errorf("unexpected handler patched:\ngot\n%#v\nexp\n%#v\n", h, tc.expPatch)
}
h, err = cli.ReplaceTopicHandler(h.Link, tc.put)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(h, tc.expPut) {
t.Errorf("unexpected handler put:\ngot\n%#v\nexp\n%#v\n", h, tc.expPut)
}
// Restart server
s.Restart()
rh, err := cli.TopicHandler(h.Link)
if err != nil {
t.Fatalf("could not find handler after restart: %v", err)
}
if got, exp := rh, h; !reflect.DeepEqual(got, exp) {
t.Errorf("unexpected handler after restart:\ngot\n%#v\nexp\n%#v\n", got, exp)
}
err = cli.DeleteTopicHandler(h.Link)
if err != nil {
t.Fatal(err)
}
_, err = cli.TopicHandler(h.Link)
if err == nil {
t.Errorf("expected handler to be deleted")
}
handlers, err := cli.ListTopicHandlers(cli.TopicHandlersLink(tc.topic), nil)
if err != nil {
t.Fatal(err)
}
for _, h := range handlers.Handlers {
if h.ID == tc.expPut.ID {
t.Errorf("expected handler to be deleted")
break
}
}
}
}
func TestServer_AlertHandlers_disable(t *testing.T) {
testCases := []struct {
handler client.TopicHandler
setup func(*server.Config, *client.TopicHandler) (context.Context, error)
result func(context.Context) error
disable map[string]struct{}
}{{
disable: map[string]struct{}{"alerta": struct{}{}},
handler: client.TopicHandler{
Kind: "alerta",
Options: map[string]interface{}{
"token": "testtoken1234567",
"token-prefix": "Bearer",
"origin": "kapacitor",
"group": "test",
"environment": "env",
"timeout": time.Duration(24 * time.Hour),
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := alertatest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Alerta.Enabled = true
c.Alerta.URL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*alertatest.Server)
ts.Close()
got := ts.Requests()
exp := []alertatest.Request(nil)
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected alerta request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
}}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%s-%d", tc.handler.Kind, i), func(t *testing.T) {
kind := tc.handler.Kind
// Create default config
c := NewConfig()
var ctxt context.Context
if tc.setup != nil {
var err error
ctxt, err = tc.setup(c, &tc.handler)
if err != nil {
t.Fatal(err)
}
}
s := OpenServerWithDisabledHandlers(c, tc.disable)
cli := Client(s)
closed := false
defer func() {
if !closed {
s.Close()
}
}()
ctxt = context.WithValue(ctxt, "kapacitorURL", s.URL())
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testAlertHandlers",
Kind: tc.handler.Kind,
Options: tc.handler.Options,
}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
tick := `
stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Close the entire server to ensure all data is processed
s.Close()
closed = true
if err := tc.result(ctxt); err != nil {
t.Errorf("%s: %v", kind, err)
}
})
}
}
func TestServer_AlertJSON(t *testing.T) {
postServer := func(t *testing.T, expected string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
if (string(data)) != expected {
t.Error(
"Unexpected httppost request",
cmp.Diff(string(data), expected))
}
}))
}
testCases := []struct {
name string
setup func(*testing.T, *server.Config, string) (*httptest.Server, map[string]interface{}, error)
expected string
tick string
}{
{
name: "normal_json",
setup: func(t *testing.T, c *server.Config, expected string) (*httptest.Server, map[string]interface{}, error) {
ts := postServer(t, expected)
ha := &client.TopicHandler{
Kind: "post",
}
ha.Options = map[string]interface{}{
"url": ts.URL,
"endpoint": "test",
}
c.HTTPPost = httppost.Configs{{
Endpoint: "test",
URLTemplate: ts.URL,
Headers: nil,
AlertTemplate: "{{ json . }}",
}}
return ts, ha.Options, nil
},
expected: `{"id":"id","message":"message","details":"details","time":"1970-01-01T00:00:00Z",` +
`"duration":0,"level":"CRITICAL","data":{"series":[{"name":"alert","columns":["time","value"],` +
`"values":[["1970-01-01T00:00:00Z",1]]}]},"previousLevel":"OK","recoverable":true}` +
"\n",
tick: `stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)`,
},
{
name: "compact-json",
setup: func(t *testing.T, c *server.Config, expected string) (*httptest.Server, map[string]interface{}, error) {
ts := postServer(t, expected)
ha := &client.TopicHandler{
Kind: "post",
}
ha.Options = map[string]interface{}{
"url": ts.URL,
"endpoint": "test",
}
c.HTTPPost = httppost.Configs{{
Endpoint: "test",
URLTemplate: ts.URL,
Headers: nil,
AlertTemplate: "{{ jsonCompact . }}", // note this gets ignored by the testing framework
}}
return ts, ha.Options, nil
},
expected: `{"id":"id","message":"message","details":"details","time":"1970-01-01T00:00:00Z","duration":0,"level":"CRITICAL","data":{"series":[{"name":"alert","columns":["time","value"],"values":[["1970-01-01T00:00:00Z",1]]}]},"previousLevel":"OK","recoverable":true}`,
tick: `stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)`,
},
{
name: "details_normal_json",
setup: func(t *testing.T, c *server.Config, expected string) (*httptest.Server, map[string]interface{}, error) {
ts := postServer(t, expected)
ha := &client.TopicHandler{
Kind: "post",
}
ha.Options = map[string]interface{}{
"url": ts.URL,
"endpoint": "test",
}
c.HTTPPost = httppost.Configs{{
Endpoint: "test",
URLTemplate: ts.URL,
Headers: nil,
AlertTemplate: "{{ json . }}",
}}
return ts, ha.Options, nil
},
expected: `{"id":"id","message":"message","details":` +
`"{\u0026#34;Name\u0026#34;:\u0026#34;alert\u0026#34;,\u0026#34;Ta` +
`skName\u0026#34;:\u0026#34;testAlertHandlers\u0026#34;,\u0026#34` +
`;Group\u0026#34;:\u0026#34;nil\u0026#34;,\u0026#34;Tags\u0026#34` +
`;:{},\u0026#34;ServerInfo\u0026#34;:{\u0026#34;Hostname\u0026#34` +
`;:\u0026#34;localhost\u0026#34;,\u0026#34;ClusterID\u0026#34;:\u` +
`0026#34;4c77777-a43d-439a-ba56-b08cbb0993fe\u0026#34;,\u0026#34` +
`;ServerID\u0026#34;:\u0026#34;af80a060-3226-41e2-b1cd-548a1467b491` +
`91\u0026#34;},\u0026#34;ID\u0026#34;:\u0026#34;id\u0026#34;,\u00` +
`26#34;Fields\u0026#34;:{\u0026#34;value\u0026#34;:1},\u0026#34;L` +
`evel\u0026#34;:\u0026#34;CRITICAL\u0026#34;,\u0026#34;Time\u0026` +
`#34;:\u0026#34;1970-01-01T00:00:00Z\u0026#34;,\u0026#34;Duration` +
`\u0026#34;:0,\u0026#34;Message\u0026#34;:\u0026#34;message\u0026` +
`#34;}\n",` +
`"time":"1970-01-01T00:00:00Z","duration":0,"level":"CRITICAL",` +
`"data":{"series":[{"name":"alert","columns":["time","value"],` +
`"values":[["1970-01-01T00:00:00Z",1]]}]},"previousLevel":"OK","recoverable":true}`,
tick: `stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('{{ json .data }}')
.crit(lambda: TRUE)`,
},
{
name: "details_compact_json",
setup: func(t *testing.T, c *server.Config, expected string) (*httptest.Server, map[string]interface{}, error) {
ts := postServer(t, expected)
ha := &client.TopicHandler{
Kind: "post",
}
ha.Options = map[string]interface{}{
"url": ts.URL,
"endpoint": "test",
}
c.HTTPPost = httppost.Configs{{
Endpoint: "test",
URLTemplate: ts.URL,
Headers: nil,
AlertTemplate: "{{ json . }}",
}}
return ts, ha.Options, nil
},
expected: `{"id":"id","message":"message","details":` +
`"{\u0026#34;Name\u0026#34;:\u0026#34;alert\u0026#34;,\u0026#34;Ta` +
`skName\u0026#34;:\u0026#34;testAlertHandlers\u0026#34;,\u0026#34` +
`;Group\u0026#34;:\u0026#34;nil\u0026#34;,\u0026#34;Tags\u0026#34` +
`;:{},\u0026#34;ServerInfo\u0026#34;:{\u0026#34;Hostname\u0026#34` +
`;:\u0026#34;localhost\u0026#34;,\u0026#34;ClusterID\u0026#34;:\u` +
`0026#34;f4c77777-a43d-439a-ba56-b08cbb0993fe\u0026#34;,\u0026#34` +
`;ServerID\u0026#34;:\u0026#34;af80a060-3226-41e2-b1cd-548a1467b4` +
`91\u0026#34;},\u0026#34;ID\u0026#34;:\u0026#34;id\u0026#34;,\u00` +
`26#34;Fields\u0026#34;:{\u0026#34;value\u0026#34;:1},\u0026#34;L` +
`evel\u0026#34;:\u0026#34;CRITICAL\u0026#34;,\u0026#34;Time\u0026` +
`#34;:\u0026#34;1970-01-01T00:00:00Z\u0026#34;,\u0026#34;Duration` +
`\u0026#34;:0,\u0026#34;Message\u0026#34;:\u0026#34;message\u0026` +
`#34;},` +
`"time":"1970-01-01T00:00:00Z","duration":0,"level":"CRITICAL",` +
`"data":{"series":[{"name":"alert","columns":["time","value"],` +
`"values":[["1970-01-01T00:00:00Z",1]]}]},"previousLevel":"OK","recoverable":true}` +
"\n",
tick: `stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('{{ jsonCompact .data }}')
.crit(lambda: TRUE)`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create default config
c := NewConfig()
var options map[string]interface{}
ctxt := context.Background()
var ts *httptest.Server
var err error
ts, options, err = tc.setup(t, c, tc.expected)
if err != nil {
t.Fatal(err)
}
defer ts.Close()
s := OpenServer(c)
cli := Client(s)
defer func() {
s.Close()
}()
ctxt = context.WithValue(ctxt, "kapacitorURL", s.URL())
_, err = cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testJSONHandlers",
Kind: "post",
Options: options,
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tc.tick,
Status: client.Enabled,
}); err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
})
}
}
func TestServer_AlertHandlers(t *testing.T) {
resultJSON := `{"series":[{"name":"alert","columns":["time","value"],"values":[["1970-01-01T00:00:00Z",1]]}]}`
alertData := alert.Data{
ID: "id",
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Level: alert.Critical,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "alert",
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
1.0,
}},
},
},
},
}
adJSON, err := json.Marshal(alertData)
if err != nil {
t.Fatal(err)
}
testCases := []struct {
handler client.TopicHandler
setup func(*server.Config, *client.TopicHandler) (context.Context, error)
result func(context.Context) error
}{
{
handler: client.TopicHandler{
Kind: "alerta",
Options: map[string]interface{}{
"token": "testtoken1234567",
"token-prefix": "Bearer",
"origin": "kapacitor",
"group": "test",
"environment": "env",
"timeout": time.Duration(24 * time.Hour),
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := alertatest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Alerta.Enabled = true
c.Alerta.URL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*alertatest.Server)
ts.Close()
got := ts.Requests()
exp := []alertatest.Request{{
URL: "/alert",
Authorization: "Bearer testtoken1234567",
PostData: alertatest.PostData{
Resource: "alert",
Event: "id",
Group: "test",
Environment: "env",
Text: "message",
Origin: "kapacitor",
Service: []string{"alert"},
Correlate: []string{"alert"},
Timeout: 86400,
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected alerta request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "bigpanda",
Options: map[string]interface{}{
"app-key": "my-app-key-123456",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := bigpandatest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.BigPanda.Enabled = true
c.BigPanda.Token = "my-token-123"
c.BigPanda.AppKey = "my-app-key"
c.BigPanda.URL = ts.URL + "/test/bigpanda/alert"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*bigpandatest.Server)
ts.Close()
got := ts.Requests()
exp := []bigpandatest.Request{{
URL: "/test/bigpanda/alert",
PostData: bigpandatest.PostData{
AppKey: "my-app-key-123456",
Check: "id",
Status: "critical",
Timestamp: 0,
Task: "testAlertHandlers:alert",
Description: "message",
Details: "details",
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected bigpanda request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "discord",
Options: map[string]interface{}{
"username": "Kapacitor",
"avatar-url": "https://influxdata.github.io/branding/img/downloads/influxdata-logo--symbol--pool-alpha.png",
"embed-title": "Kapacitor Alert",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := discordtest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Discord[0].Enabled = true
c.Discord[0].URL = ts.URL + "/test/discord/url"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*discordtest.Server)
ts.Close()
got := ts.Requests()
exp := []discordtest.Request{{
URL: "/test/discord/url",
PostData: discordtest.PostData{
Username: "Kapacitor",
AvatarURL: "https://influxdata.github.io/branding/img/downloads/influxdata-logo--symbol--pool-alpha.png",
Embeds: []discordtest.Embed{
{
Color: 0xF95F53,
Title: "Kapacitor Alert",
Timestamp: "",
Description: "message",
},
},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected discord request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "exec",
Options: map[string]interface{}{
"prog": "/bin/alert-handler.sh",
"args": []string{"arg1", "arg2", "arg3"},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
te := alerttest.NewExec()
ctxt := context.WithValue(context.Background(), "exec", te)
c.Commander = te.Commander
return ctxt, nil
},
result: func(ctxt context.Context) error {
te := ctxt.Value("exec").(*alerttest.Exec)
expData := []*commandtest.Command{{
Spec: command.Spec{
Prog: "/bin/alert-handler.sh",
Args: []string{"arg1", "arg2", "arg3"},
},
Started: true,
Waited: true,
Killed: false,
StdinData: append(adJSON, '\n'),
}}
cmds := te.Commands()
if got, exp := len(cmds), len(expData); got != exp {
return fmt.Errorf("unexpected commands length: got %d exp %d", got, exp)
}
for i := range expData {
if err := expData[i].Compare(cmds[i]); err != nil {
return fmt.Errorf("unexpected command %d: %v", i, err)
}
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "hipchat",
Options: map[string]interface{}{
"token": "testtoken1234567",
"room": "1234567",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := hipchattest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.HipChat.Enabled = true
c.HipChat.URL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*hipchattest.Server)
ts.Close()
got := ts.Requests()
exp := []hipchattest.Request{{
URL: "/1234567/notification?auth_token=testtoken1234567",
PostData: hipchattest.PostData{
From: "kapacitor",
Message: "message",
Color: "red",
Notify: true,
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected hipchat request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "kafka",
Options: map[string]interface{}{
"cluster": "default",
"topic": "test",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts, err := kafkatest.NewServer()
if err != nil {
return nil, err
}
ctxt := context.WithValue(context.Background(), "server", ts)
c.Kafka = kafka.Configs{{
Enabled: true,
ID: "default",
Brokers: []string{ts.Addr.String()},
}}
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*kafkatest.Server)
time.Sleep(2 * time.Second)
ts.Close()
got, err := ts.Messages()
if err != nil {
return err
}
exp := []kafkatest.Message{{
Topic: "test",
Partition: 3,
Offset: 0,
Key: "id",
Message: string(adJSON) + "\n",
Time: time.Now().UTC(),
}}
cmpopts := []cmp.Option{
cmp.Comparer(func(a, b time.Time) bool {
diff := a.Sub(b)
if diff < 0 {
diff = -diff
}
// It is ok as long as the timestamp is within
// 5 seconds of the current time. If we are that close,
// then it likely means the timestamp was correctly
// written.
return diff < 5*time.Second
}),
}
if !cmp.Equal(exp, got, cmpopts...) {
return fmt.Errorf("unexpected kafka messages -exp/+got:\n%s", cmp.Diff(exp, got))
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "log",
Options: map[string]interface{}{
"mode": 0604,
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
tdir := MustTempDir()
p := filepath.Join(tdir, "alert.log")
ha.Options["path"] = p
l := alerttest.NewLog(p)
ctxt := context.WithValue(context.Background(), "tdir", tdir)
ctxt = context.WithValue(ctxt, "log", l)
return ctxt, nil
},
result: func(ctxt context.Context) error {
tdir := ctxt.Value("tdir").(string)
defer os.RemoveAll(tdir)
l := ctxt.Value("log").(*alerttest.Log)
expData := []alert.Data{alertData}
expMode := os.FileMode(LogFileExpectedMode)
m, err := l.Mode()
if err != nil {
return err
}
if got, exp := m, expMode; exp != got {
return fmt.Errorf("unexpected file mode: got %v exp %v", got, exp)
}
data, err := l.Data()
if err != nil {
return err
}
if got, exp := data, expData; !reflect.DeepEqual(got, exp) {
return fmt.Errorf("unexpected alert data written to log:\ngot\n%+v\nexp\n%+v\n", got, exp)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "mqtt",
Options: map[string]interface{}{
"topic": "test",
"qos": "at-least-once",
"retained": true,
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
cc := new(mqtttest.ClientCreator)
ctxt := context.WithValue(context.Background(), "clientCreator", cc)
cfg := &mqtt.Config{
Enabled: true,
Name: "test",
URL: "tcp://mqtt.example.com:1883",
}
cfg.SetNewClientF(cc.NewClient)
c.MQTT = mqtt.Configs{*cfg}
return ctxt, nil
},
result: func(ctxt context.Context) error {
s := ctxt.Value("clientCreator").(*mqtttest.ClientCreator)
if got, exp := len(s.Clients), 1; got != exp {
return fmt.Errorf("unexpected number of clients created : exp %d got: %d", exp, got)
}
if got, exp := len(s.Configs), 1; got != exp {
return fmt.Errorf("unexpected number of configs received: exp %d got: %d", exp, got)
}
if got, exp := s.Configs[0].URL, "tcp://mqtt.example.com:1883"; exp != got {
return fmt.Errorf("unexpected config URL: exp %q got %q", exp, got)
}
got := s.Clients[0].PublishData
exp := []mqtttest.PublishData{{
Topic: "test",
QoS: mqtt.AtLeastOnce,
Retained: true,
Message: []byte("message"),
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected mqtt publish data:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "mqtt",
Options: map[string]interface{}{
"topic": "test/{{.TaskName}}",
"qos": "at-least-once",
"retained": true,
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
cc := new(mqtttest.ClientCreator)
ctxt := context.WithValue(context.Background(), "clientCreator", cc)
cfg := &mqtt.Config{
Enabled: true,
Name: "test",
URL: "tcp://mqtt.example.com:1883",
}
cfg.SetNewClientF(cc.NewClient)
c.MQTT = mqtt.Configs{*cfg}
return ctxt, nil
},
result: func(ctxt context.Context) error {
s := ctxt.Value("clientCreator").(*mqtttest.ClientCreator)
if got, exp := len(s.Clients), 1; got != exp {
return fmt.Errorf("unexpected number of clients created : exp %d got: %d", exp, got)
}
if got, exp := len(s.Configs), 1; got != exp {
return fmt.Errorf("unexpected number of configs received: exp %d got: %d", exp, got)
}
if got, exp := s.Configs[0].URL, "tcp://mqtt.example.com:1883"; exp != got {
return fmt.Errorf("unexpected config URL: exp %q got %q", exp, got)
}
got := s.Clients[0].PublishData
exp := []mqtttest.PublishData{{
Topic: "test/testAlertHandlers",
QoS: mqtt.AtLeastOnce,
Retained: true,
Message: []byte("message"),
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected mqtt publish data:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "opsgenie",
Options: map[string]interface{}{
"teams-list": []string{"A team", "B team"},
"recipients-list": []string{"test_recipient1", "test_recipient2"},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := opsgenietest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.OpsGenie.Enabled = true
c.OpsGenie.URL = ts.URL
c.OpsGenie.APIKey = "api_key"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*opsgenietest.Server)
ts.Close()
got := ts.Requests()
exp := []opsgenietest.Request{{
URL: "/",
PostData: opsgenietest.PostData{
ApiKey: "api_key",
Message: "message",
Entity: "id",
Alias: "id",
Note: "",
Details: map[string]interface{}{
"Level": "CRITICAL",
"Monitoring Tool": "Kapacitor",
},
Description: resultJSON,
Teams: []string{"A team", "B team"},
Recipients: []string{"test_recipient1", "test_recipient2"},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected opsgenie request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "opsgenie2",
Options: map[string]interface{}{
"teams-list": []string{"A team", "B team"},
"recipients-list": []string{"test_recipient1", "test_recipient2"},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := opsgenie2test.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.OpsGenie2.Enabled = true
c.OpsGenie2.Details = false
c.OpsGenie2.URL = ts.URL
c.OpsGenie2.RecoveryAction = "notes"
c.OpsGenie2.APIKey = "api_key"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*opsgenie2test.Server)
ts.Close()
got := ts.Requests()
exp := []opsgenie2test.Request{{
URL: "/",
Authorization: "GenieKey api_key",
PostData: opsgenie2test.PostData{
Message: "message",
Entity: "id",
Alias: "aWQ=",
Note: "",
Priority: "P1",
Details: map[string]string{
"Level": "CRITICAL",
"Monitoring Tool": "Kapacitor",
"Kapacitor Task Name": "alert",
},
Description: resultJSON,
Responders: []map[string]string{
{"name": "A team", "type": "team"},
{"name": "B team", "type": "team"},
{"username": "test_recipient1", "type": "user"},
{"username": "test_recipient2", "type": "user"},
},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected opsgenie2 request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "pagerduty",
Options: map[string]interface{}{
"service-key": "service_key",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := pagerdutytest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.PagerDuty.Enabled = true
c.PagerDuty.URL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*pagerdutytest.Server)
kapacitorURL := ctxt.Value("kapacitorURL").(string)
ts.Close()
got := ts.Requests()
exp := []pagerdutytest.Request{{
URL: "/",
PostData: pagerdutytest.PostData{
ServiceKey: "service_key",
EventType: "trigger",
Description: "message",
Client: "kapacitor",
ClientURL: kapacitorURL,
Details: "details",
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected pagerduty request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "pagerduty2",
Options: map[string]interface{}{
"routing-key": "rkey",
"links": []interface{}{
map[string]string{
"href": "http://example.com",
"text": "t1",
},
map[string]string{
"href": "http://example.com/{{.TaskName}}",
"text": "t2",
},
},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := pagerduty2test.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.PagerDuty2.Enabled = true
c.PagerDuty2.URL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*pagerduty2test.Server)
kapacitorURL := ctxt.Value("kapacitorURL").(string)
ts.Close()
got := ts.Requests()
exp := []pagerduty2test.Request{{
URL: "/",
PostData: pagerduty2test.PostData{
Client: "kapacitor",
ClientURL: kapacitorURL,
EventAction: "trigger",
DedupKey: "id",
Payload: &pagerduty2test.PDCEF{
Summary: "message",
Source: "unknown",
Severity: "critical",
Class: "testAlertHandlers",
CustomDetails: map[string]interface{}{
"result": map[string]interface{}{
"series": []interface{}{
map[string]interface{}{
"name": "alert",
"columns": []interface{}{"time", "value"},
"values": []interface{}{
[]interface{}{"1970-01-01T00:00:00Z", float64(1)},
},
},
},
},
},
Timestamp: "1970-01-01T00:00:00.000000000Z",
},
RoutingKey: "rkey",
Links: []pagerduty2test.Link{
{Href: "http://example.com", Text: "t1"},
{Href: "http://example.com/testAlertHandlers", Text: "t2"},
},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected pagerduty2 request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "post",
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := alerttest.NewPostServer()
ha.Options = map[string]interface{}{"url": ts.URL}
ctxt := context.WithValue(context.Background(), "server", ts)
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*alerttest.PostServer)
ts.Close()
exp := []alert.Data{alertData}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected post request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "post",
Options: map[string]interface{}{
"endpoint": "test",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := httpposttest.NewAlertServer(nil, true)
ctxt := context.WithValue(context.Background(), "server", ts)
c.HTTPPost = httppost.Configs{{
Endpoint: "test",
URLTemplate: ts.URL,
AlertTemplate: `{{.Message}}`,
}}
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*httpposttest.AlertServer)
exp := []httpposttest.AlertRequest{{
MatchingHeaders: true,
Raw: []byte("message"),
}}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected httppost alert request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "pushover",
Options: map[string]interface{}{},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := pushovertest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Pushover.Enabled = true
c.Pushover.URL = ts.URL
c.Pushover.Token = "api_key"
c.Pushover.UserKey = "user"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*pushovertest.Server)
ts.Close()
got := ts.Requests()
exp := []pushovertest.Request{{
PostData: pushovertest.PostData{
Token: "api_key",
UserKey: "user",
Message: "message",
Priority: 1,
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected pushover request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "sensu",
Options: map[string]interface{}{
"source": "Kapacitor",
"metadata": map[string]interface{}{
"k1": "v1",
"k2": 5,
},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts, err := sensutest.NewServer()
if err != nil {
return nil, err
}
ctxt := context.WithValue(context.Background(), "server", ts)
c.Sensu.Enabled = true
c.Sensu.Addr = ts.Addr
c.Sensu.Source = "Kapacitor"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*sensutest.Server)
ts.Close()
exp := []sensutest.Request{{
Source: "Kapacitor",
Output: "message",
Name: "id",
Status: 2,
Metadata: map[string]interface{}{
"k1": "v1",
"k2": float64(5),
},
}}
got := ts.Requests()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected sensu request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "servicenow",
Options: map[string]interface{}{
"source": "Kapacitor",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := servicenowtest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.ServiceNow.Enabled = true
c.ServiceNow.URL = ts.URL + "/api/global/em/jsonv2"
c.ServiceNow.Source = "Kapacitor"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*servicenowtest.Server)
ts.Close()
exp := []servicenowtest.Request{{
URL: "/api/global/em/jsonv2",
Alerts: servicenow.Events{
Records: []servicenow.Event{
{
Source: "Kapacitor",
Severity: "1",
Description: "message",
MessageKey: "id",
},
},
},
}}
got := ts.Requests()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected servicenow request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := slacktest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Slack[0].Enabled = true
c.Slack[0].URL = ts.URL + "/test/slack/url"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*slacktest.Server)
ts.Close()
got := ts.Requests()
exp := []slacktest.Request{{
URL: "/test/slack/url",
PostData: slacktest.PostData{
Channel: "#test",
Username: "kapacitor",
Text: "",
Attachments: []slacktest.Attachment{
{
Fallback: "message",
Color: "danger",
Text: "message",
Mrkdwn_in: []string{"text"},
},
},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected slack request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "smtp",
Options: map[string]interface{}{
"to": []string{"[email protected]", "[email protected]"},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts, err := smtptest.NewServer()
if err != nil {
return nil, err
}
ctxt := context.WithValue(context.Background(), "server", ts)
c.SMTP.Enabled = true
c.SMTP.Host = ts.Host
c.SMTP.Port = ts.Port
c.SMTP.From = "[email protected]"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*smtptest.Server)
ts.Close()
errors := ts.Errors()
if len(errors) != 0 {
return fmt.Errorf("multiple errors %d: %v", len(errors), errors)
}
expMail := []*smtptest.Message{{
Header: mail.Header{
"Mime-Version": []string{"1.0"},
"Content-Type": []string{"text/html; charset=UTF-8"},
"Content-Transfer-Encoding": []string{"quoted-printable"},
"To": []string{"[email protected], [email protected]"},
"From": []string{"[email protected]"},
"Subject": []string{"message"},
},
Body: "details\n",
}}
msgs := ts.SentMessages()
if got, exp := len(msgs), len(expMail); got != exp {
return fmt.Errorf("unexpected number of messages sent: got %d exp %d", got, exp)
}
for i, exp := range expMail {
got := msgs[i]
if err := exp.Compare(got); err != nil {
return fmt.Errorf("unexpected message %d: %v", i, err)
}
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "snmptrap",
Options: map[string]interface{}{
"trap-oid": "1.1.2",
"data-list": []map[string]string{
{
"oid": "1.1.2.1",
"type": "s",
"value": "{{.Message}}",
},
{
"oid": "1.1.2.2",
"type": "s",
"value": "{{.Level}}",
},
},
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts, err := snmptraptest.NewServer()
if err != nil {
return nil, err
}
ctxt := context.WithValue(context.Background(), "server", ts)
c.SNMPTrap.Enabled = true
c.SNMPTrap.Addr = ts.Addr
c.SNMPTrap.Community = ts.Community
c.SNMPTrap.Retries = 3
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*snmptraptest.Server)
ts.Close()
got := ts.Traps()
exp := []snmptraptest.Trap{{
Pdu: snmptraptest.Pdu{
Type: snmpgo.SNMPTrapV2,
ErrorStatus: snmpgo.NoError,
VarBinds: snmptraptest.VarBinds{
{
Oid: "1.3.6.1.2.1.1.3.0",
Value: "1000",
Type: "TimeTicks",
},
{
Oid: "1.3.6.1.6.3.1.1.4.1.0",
Value: "1.1.2",
Type: "Oid",
},
{
Oid: "1.1.2.1",
Value: "message",
Type: "OctetString",
},
{
Oid: "1.1.2.2",
Value: "CRITICAL",
Type: "OctetString",
},
},
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected snmptrap request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "talk",
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := talktest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Talk.Enabled = true
c.Talk.URL = ts.URL
c.Talk.AuthorName = "Kapacitor"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*talktest.Server)
ts.Close()
got := ts.Requests()
exp := []talktest.Request{{
URL: "/",
PostData: talktest.PostData{
AuthorName: "Kapacitor",
Text: "message",
Title: "id",
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected talk request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "tcp",
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts, err := alerttest.NewTCPServer()
if err != nil {
return nil, err
}
ha.Options = map[string]interface{}{"address": ts.Addr}
ctxt := context.WithValue(context.Background(), "server", ts)
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*alerttest.TCPServer)
ts.Close()
exp := []alert.Data{alertData}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected tcp request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "teams",
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := teamstest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Teams.Enabled = true
c.Teams.ChannelURL = ts.URL
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*teamstest.Server)
ts.Close()
got := ts.Requests()
exp := []teamstest.Request{{
URL: "/",
Card: teams.Card{
CardType: "MessageCard",
Context: "http://schema.org/extensions",
Title: "CRITICAL: [id]",
Text: "message",
Summary: "CRITICAL: [id] - message...",
ThemeColor: "CC4A31",
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected teams request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "telegram",
Options: map[string]interface{}{
"chat-id": "chat id",
"disable-web-page-preview": true,
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := telegramtest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Telegram.Enabled = true
c.Telegram.URL = ts.URL + "/bot"
c.Telegram.Token = "TOKEN:AUTH"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*telegramtest.Server)
ts.Close()
got := ts.Requests()
exp := []telegramtest.Request{{
URL: "/botTOKEN:AUTH/sendMessage",
PostData: telegramtest.PostData{
ChatId: "chat id",
Text: "message",
ParseMode: "",
DisableWebPagePreview: true,
DisableNotification: false,
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected telegram request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "victorops",
Options: map[string]interface{}{
"routing-key": "key",
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := victoropstest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.VictorOps.Enabled = true
c.VictorOps.URL = ts.URL
c.VictorOps.APIKey = "api_key"
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*victoropstest.Server)
ts.Close()
got := ts.Requests()
exp := []victoropstest.Request{{
URL: "/api_key/key",
PostData: victoropstest.PostData{
MessageType: "CRITICAL",
EntityID: "id",
StateMessage: "message",
Timestamp: 0,
MonitoringTool: "kapacitor",
Data: resultJSON,
},
}}
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected victorops request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
{
handler: client.TopicHandler{
Kind: "zenoss",
Options: map[string]interface{}{
"action": "EventsRouter",
"method": "add_event",
"type": "rpc",
"TID": 1,
},
},
setup: func(c *server.Config, ha *client.TopicHandler) (context.Context, error) {
ts := zenosstest.NewServer()
ctxt := context.WithValue(context.Background(), "server", ts)
c.Zenoss.Enabled = true
c.Zenoss.URL = ts.URL + "/zport/dmd/evconsole_router"
c.Zenoss.Collector = ""
return ctxt, nil
},
result: func(ctxt context.Context) error {
ts := ctxt.Value("server").(*zenosstest.Server)
ts.Close()
exp := []zenosstest.Request{{
URL: "/zport/dmd/evconsole_router",
Event: zenoss.Event{
Action: "EventsRouter",
Method: "add_event",
Data: []map[string]interface{}{
{
"component": "",
"device": "",
"evclass": "",
"evclasskey": "",
"severity": "Critical",
"summary": "message",
},
},
Type: "rpc",
TID: 1,
},
}}
got := ts.Requests()
if !reflect.DeepEqual(exp, got) {
return fmt.Errorf("unexpected zenoss request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
return nil
},
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%s-%d", tc.handler.Kind, i), func(t *testing.T) {
kind := tc.handler.Kind
// Create default config
c := NewConfig()
var ctxt context.Context
if tc.setup != nil {
var err error
ctxt, err = tc.setup(c, &tc.handler)
if err != nil {
t.Fatal(err)
}
}
s := OpenServer(c)
cli := Client(s)
closed := false
defer func() {
if !closed {
s.Close()
}
}()
ctxt = context.WithValue(ctxt, "kapacitorURL", s.URL())
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testAlertHandlers",
Kind: tc.handler.Kind,
Options: tc.handler.Options,
}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
tick := `
stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatalf("%s: %v", kind, err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Close the entire server to ensure all data is processed
s.Close()
closed = true
if err := tc.result(ctxt); err != nil {
t.Errorf("%s: %v", kind, err)
}
})
}
}
func TestServer_Alert_Duration(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
tick := `
stream
|from()
.measurement('alert')
|alert()
.id('id')
.message('message')
.details('details')
.crit(lambda: "value" > 1.0)
.tcp('` + ts.Addr + `')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
// Write point
point := "alert value=2 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Restart the server
s.Restart()
topic := "main:testAlertHandlers:alert2"
l := cli.TopicEventsLink(topic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: topic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", topic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Duration: 0,
Level: "CRITICAL",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for anonymous topic:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
event, err := cli.TopicEvent(expTopicEvents.Events[0].Link)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(event, expTopicEvents.Events[0]) {
t.Errorf("unexpected topic event for anonymous topic:\ngot\n%+v\nexp\n%+v\n", event, expTopicEvents.Events[0])
}
// Write point
point = "alert value=3 0000000001"
v = url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Restart the server
s.Restart()
expTopicEvents = client.TopicEvents{
Link: l,
Topic: topic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", topic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC),
Duration: client.Duration(time.Second),
Level: "CRITICAL",
},
}},
}
te, err = cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for anonymous topic after second point:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
}
func TestServer_Alert_Aggregate(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
aggTopic := "agg"
// Create task for alert
tick := `
stream
|from()
.measurement('alert')
|alert()
.id('id')
.message('message')
.details('details')
.crit(lambda: "value" > 1.0)
.topic('` + aggTopic + `')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "agg_task",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
// Create tpc handler on tcp topic
tcpTopic := "tcp"
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(tcpTopic), client.TopicHandlerOptions{
ID: "tcp_handler",
Kind: "tcp",
Options: map[string]interface{}{
"address": ts.Addr,
},
}); err != nil {
t.Fatal(err)
}
// Create aggregate handler on agg topic
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(aggTopic), client.TopicHandlerOptions{
ID: "aggregate_handler",
Kind: "aggregate",
Options: map[string]interface{}{
"id": "id-agg",
"interval": 100 * time.Millisecond,
"topic": "tcp",
},
}); err != nil {
t.Fatal(err)
}
// Write points
point := `alert value=3 0000000000000
alert value=4 0000000000001
alert value=2 0000000000002
`
v := url.Values{}
v.Add("precision", "ms")
s.MustWrite("mydb", "myrp", point, v)
time.Sleep(110 * time.Millisecond)
// Check TCP handler got event
alertData := alert.Data{
ID: "id-agg",
Message: "Received 3 events in the last 100ms.",
Details: "message\nmessage\nmessage",
Time: time.Date(1970, 1, 1, 0, 0, 0, 2000000, time.UTC),
Level: alert.Critical,
Duration: 2 * time.Millisecond,
Recoverable: false,
Data: models.Result{
Series: models.Rows{
{
Name: "alert",
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
3.0,
}},
},
{
Name: "alert",
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 0, 1000000, time.UTC),
4.0,
}},
},
{
Name: "alert",
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 0, 2000000, time.UTC),
2.0,
}},
},
},
},
}
ts.Close()
exp := []alert.Data{alertData}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected tcp request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
// Check event on topic
l := cli.TopicEventsLink(tcpTopic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: tcpTopic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id-agg", tcpTopic)},
ID: "id-agg",
State: client.EventState{
Message: "Received 3 events in the last 100ms.",
Details: "message\nmessage\nmessage",
Time: time.Date(1970, 1, 1, 0, 0, 0, 2000000, time.UTC),
Duration: client.Duration(2 * time.Millisecond),
Level: "CRITICAL",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for aggregate topic:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
}
func TestServer_Alert_Publish(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
publishTopic := "publish"
// Create task for alert
tick := `
stream
|from()
.measurement('alert')
|alert()
.id('id')
.message('message')
.details('details')
.crit(lambda: "value" > 1.0)
.topic('` + publishTopic + `')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "publish_task",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
// Create tpc handler on tcp topic
tcpTopic := "tcp"
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(tcpTopic), client.TopicHandlerOptions{
ID: "tcp_handler",
Kind: "tcp",
Options: map[string]interface{}{
"address": ts.Addr,
},
}); err != nil {
t.Fatal(err)
}
// Create publish handler on publish topic
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(publishTopic), client.TopicHandlerOptions{
ID: "publish_handler",
Kind: "publish",
Options: map[string]interface{}{
// Publish to tcpTopic
"topics": []string{tcpTopic},
},
}); err != nil {
t.Fatal(err)
}
// Write points
point := `alert value=2 0000000000`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
s.Restart()
// Check TCP handler got event
alertData := alert.Data{
ID: "id",
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Level: alert.Critical,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "alert",
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
2.0,
}},
},
},
},
}
ts.Close()
exp := []alert.Data{alertData}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected tcp request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
// Check event on topic
l := cli.TopicEventsLink(tcpTopic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: tcpTopic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", tcpTopic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Duration: 0,
Level: "CRITICAL",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for publish topic:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
}
func TestServer_Alert_Match(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
topic := "test"
// Create task for alert
tick := `
stream
|from()
.measurement('alert')
|alert()
.id('id')
.message('message')
.details('details')
.crit(lambda: "value" > 1.0)
.topic('` + topic + `')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "alert_task",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
// Create tpc handler with match condition
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(topic), client.TopicHandlerOptions{
ID: "tcp_handler",
Kind: "tcp",
Options: map[string]interface{}{
"address": ts.Addr,
},
Match: `"host" == 'serverA' AND level() == CRITICAL`,
}); err != nil {
t.Fatal(err)
}
// Write points
point := `alert,host=serverA value=0 0000000000
alert,host=serverB value=2 0000000001
alert,host=serverB value=0 0000000002
alert,host=serverA value=2 0000000003
alert,host=serverB value=0 0000000004
`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
s.Restart()
alertData := alert.Data{
ID: "id",
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 3, 0, time.UTC),
Level: alert.Critical,
Recoverable: true,
Data: models.Result{
Series: models.Rows{
{
Name: "alert",
Tags: map[string]string{"host": "serverA"},
Columns: []string{"time", "value"},
Values: [][]interface{}{[]interface{}{
time.Date(1970, 1, 1, 0, 0, 3, 0, time.UTC),
2.0,
}},
},
},
},
}
ts.Close()
exp := []alert.Data{alertData}
got := ts.Data()
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected tcp request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
// Topic should have must recent event
l := cli.TopicEventsLink(topic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: topic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", topic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 4, 0, time.UTC),
Duration: client.Duration(time.Second),
Level: "OK",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for publish topic:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
}
func TestServer_AlertAnonTopic(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
tick := `
stream
|from()
.measurement('alert')
|alert()
.id('id')
.message('message')
.details('details')
.warn(lambda: "value" <= 1.0)
.crit(lambda: "value" > 1.0)
.tcp('` + ts.Addr + `')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
// Write warning point
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Restart the server
s.Restart()
topic := "main:testAlertHandlers:alert2"
l := cli.TopicEventsLink(topic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: topic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", topic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Duration: 0,
Level: "WARNING",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for anonymous topic:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
event, err := cli.TopicEvent(expTopicEvents.Events[0].Link)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(event, expTopicEvents.Events[0]) {
t.Errorf("unexpected topic event for anonymous topic:\ngot\n%+v\nexp\n%+v\n", event, expTopicEvents.Events[0])
}
// Disable task
task, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.ListTopicEvents(l, nil); err == nil {
t.Fatal("expected error listing anonymous topic for disabled task")
} else if got, exp := err.Error(), fmt.Sprintf("failed to get topic events: unknown topic %q", topic); got != exp {
t.Errorf("unexpected error message for nonexistent anonymous topic: got %q exp %q", got, exp)
}
// Enable task
task, err = cli.UpdateTask(task.Link, client.UpdateTaskOptions{
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
te, err = cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for anonymous topic after re-enable:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
// Restart the server, again and ensure that the anonymous topic state is restored
s.Restart()
te, err = cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for anonymous topic after re-enable and restart:\ngot\n%+v\nexp\n%+v\n", te, expTopicEvents)
}
// Delete task
if err := cli.DeleteTask(task.Link); err != nil {
t.Fatal(err)
}
if _, err := cli.ListTopicEvents(l, nil); err == nil {
t.Fatal("expected error listing anonymous topic for deleted task")
} else if got, exp := err.Error(), fmt.Sprintf("failed to get topic events: unknown topic %q", topic); got != exp {
t.Errorf("unexpected error message for nonexistent anonymous topic: got %q exp %q", got, exp)
}
}
func TestServer_AlertTopic_PersistedState(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
tmpDir := MustTempDir()
defer os.RemoveAll(tmpDir)
tmpPath := filepath.Join(tmpDir, "alert.log")
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testAlertHandler",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
}); err != nil {
t.Fatal(err)
}
tick := `
stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.warn(lambda: TRUE)
.log('` + tmpPath + `')
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Restart the server
s.Restart()
topics := []string{
"test",
"main:testAlertHandlers:alert2",
}
for _, topic := range topics {
l := cli.TopicEventsLink(topic)
expTopicEvents := client.TopicEvents{
Link: l,
Topic: topic,
Events: []client.TopicEvent{{
Link: client.Link{Relation: client.Self, Href: fmt.Sprintf("/kapacitor/v1/alerts/topics/%s/events/id", topic)},
ID: "id",
State: client.EventState{
Message: "message",
Details: "details",
Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
Duration: 0,
Level: "WARNING",
},
}},
}
te, err := cli.ListTopicEvents(l, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events for topic %q:\ngot\n%+v\nexp\n%+v\n", topic, te, expTopicEvents)
}
event, err := cli.TopicEvent(expTopicEvents.Events[0].Link)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(event, expTopicEvents.Events[0]) {
t.Errorf("unexpected topic event for topic %q:\ngot\n%+v\nexp\n%+v\n", topic, event, expTopicEvents.Events[0])
}
te, err = cli.ListTopicEvents(l, &client.ListTopicEventsOptions{
MinLevel: "CRITICAL",
})
if err != nil {
t.Fatal(err)
}
expTopicEvents.Events = expTopicEvents.Events[0:0]
if !reflect.DeepEqual(te, expTopicEvents) {
t.Errorf("unexpected topic events with minLevel for topic %q:\ngot\n%+v\nexp\n%+v\n", topic, te, expTopicEvents)
}
l = cli.TopicLink(topic)
if err := cli.DeleteTopic(l); err != nil {
t.Fatal(err)
}
te, err = cli.ListTopicEvents(l, nil)
if err == nil {
t.Fatalf("expected error for deleted topic %q", topic)
}
}
}
func TestServer_Alert_Inhibition(t *testing.T) {
// Test Overview
// Create several alerts:
// * cpu - alert on host cpu usage by region,host,cpu
// * mem - alert on host mem usage by region,host
// * host - alert on host up/down by region,host
// * region - alert on region up/down by region
//
// The host alert will inhibit the cpu and mem alerts by host
// The region alert will inhibit the cpu mem and host alerts by region
//
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
closed := false
defer func() {
if !closed {
s.Close()
}
}()
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("inhibition"), client.TopicHandlerOptions{
ID: "tcpHandler",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
}); err != nil {
t.Fatal(err)
}
memAlert := `
stream
|from()
.measurement('mem')
.groupBy(*)
|alert()
.category('system')
.topic('inhibition')
.message('mem')
.details('')
.crit(lambda: "v")
`
cpuAlert := `
stream
|from()
.measurement('cpu')
.groupBy(*)
|alert()
.category('system')
.topic('inhibition')
.message('cpu')
.details('')
.crit(lambda: "v")
`
hostAlert := `
stream
|from()
.measurement('host')
.groupBy(*)
|alert()
.category('host_alert')
.topic('inhibition')
.message('host')
.details('')
.crit(lambda: "v")
.inhibit('system', 'region', 'host')
`
regionAlert := `
stream
|from()
.measurement('region')
.groupBy(*)
|alert()
.category('region_alert')
.topic('inhibition')
.message('region')
.details('')
.crit(lambda: "v")
.inhibit('host_alert', 'region')
.inhibit('system', 'region')
`
tasks := map[string]string{
"cpu": cpuAlert,
"mem": memAlert,
"host": hostAlert,
"region": regionAlert,
}
for id, tick := range tasks {
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
}
batches := []string{
//#0 Send initial batch with all alerts in the green state
`cpu,region=west,host=A,cpu=0 v=false 0
cpu,region=west,host=A,cpu=1 v=false 0
cpu,region=west,host=B,cpu=0 v=false 0
cpu,region=west,host=B,cpu=1 v=false 0
cpu,region=east,host=A,cpu=0 v=false 0
cpu,region=east,host=A,cpu=1 v=false 0
cpu,region=east,host=B,cpu=0 v=false 0
cpu,region=east,host=B,cpu=1 v=false 0
mem,region=west,host=A v=false 0
mem,region=west,host=B v=false 0
mem,region=east,host=A v=false 0
mem,region=east,host=B v=false 0
host,region=west,host=A v=false 0
host,region=west,host=B v=false 0
host,region=east,host=A v=false 0
host,region=east,host=B v=false 0
region,region=west v=false 0
region,region=east v=false 0
`,
//#1 Send batch where some mem and cpu alerts fire
`cpu,region=west,host=B,cpu=0 v=true 1
cpu,region=east,host=A,cpu=1 v=true 1
mem,region=west,host=B v=true 1
mem,region=east,host=A v=true 1
`,
//#2 Send batch where some host alerts fire
`host,region=west,host=B v=true 2
host,region=east,host=B v=true 2
`,
//#3 Send batch where some mem and cpu alerts fire
`cpu,region=west,host=B,cpu=0 v=true 3
cpu,region=east,host=A,cpu=1 v=true 3
mem,region=west,host=B v=true 3
mem,region=east,host=A v=true 3
`,
//#4 Send batch were hosts alerts recover
`host,region=west,host=B v=false 4
host,region=east,host=B v=false 4
`,
//#5 Send batch where some mem and cpu alerts fire
`cpu,region=west,host=B,cpu=0 v=true 5
cpu,region=east,host=A,cpu=1 v=true 5
mem,region=west,host=B v=true 5
mem,region=east,host=A v=true 5
`,
//#6 Send batch where region alert fires
`region,region=east v=true 6`,
//#7 Send batch where some mem, cpu and host alerts fire
`cpu,region=west,host=B,cpu=0 v=true 7
cpu,region=east,host=A,cpu=1 v=true 7
mem,region=west,host=B v=true 7
mem,region=east,host=A v=true 7
host,region=west,host=A v=true 7
host,region=east,host=B v=true 7
`,
//#8 Send batch where region alert recovers
`region,region=east v=false 8`,
//#9 Send batch where some mem, cpu and host alerts fire
`cpu,region=west,host=B,cpu=0 v=true 9
cpu,region=east,host=A,cpu=1 v=true 9
mem,region=west,host=B v=true 9
mem,region=east,host=A v=true 9
host,region=west,host=A v=true 9
host,region=east,host=B v=true 9
`,
}
v := url.Values{}
v.Add("precision", "s")
for _, p := range batches {
s.MustWrite("mydb", "myrp", p, v)
time.Sleep(50 * time.Millisecond)
}
// Close the entire server to ensure all data is processed
s.Close()
closed = true
want := []alert.Data{
// #1
{
ID: "cpu:cpu=0,host=B,region=west",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
{
ID: "cpu:cpu=1,host=A,region=east",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
{
ID: "mem:host=A,region=east",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
{
ID: "mem:host=B,region=west",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
// #2
{
ID: "host:host=B,region=east",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 2, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
{
ID: "host:host=B,region=west",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 2, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
// #3
{
ID: "cpu:cpu=1,host=A,region=east",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 3, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
{
ID: "mem:host=A,region=east",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 3, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
// #4
{
ID: "host:host=B,region=east",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 4, 0, time.UTC),
Level: alert.OK,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
{
ID: "host:host=B,region=west",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 4, 0, time.UTC),
Level: alert.OK,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
// #5
{
ID: "cpu:cpu=0,host=B,region=west",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 5, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 4 * time.Second,
Recoverable: true,
},
{
ID: "cpu:cpu=1,host=A,region=east",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 5, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 4 * time.Second,
Recoverable: true,
},
{
ID: "mem:host=A,region=east",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 5, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 4 * time.Second,
Recoverable: true,
},
{
ID: "mem:host=B,region=west",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 5, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 4 * time.Second,
Recoverable: true,
},
// #6
{
ID: "region:region=east",
Message: "region",
Time: time.Date(1970, 1, 1, 0, 0, 6, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
// #7
{
ID: "cpu:cpu=0,host=B,region=west",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 7, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 6 * time.Second,
Recoverable: true,
},
{
ID: "host:host=A,region=west",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 7, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 0,
Recoverable: true,
},
{
ID: "mem:host=B,region=west",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 7, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 6 * time.Second,
Recoverable: true,
},
// #8
{
ID: "region:region=east",
Message: "region",
Time: time.Date(1970, 1, 1, 0, 0, 8, 0, time.UTC),
Level: alert.OK,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
// #9
{
ID: "cpu:cpu=0,host=B,region=west",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 8 * time.Second,
Recoverable: true,
},
{
ID: "cpu:cpu=1,host=A,region=east",
Message: "cpu",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 8 * time.Second,
Recoverable: true,
},
{
ID: "host:host=A,region=west",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 2 * time.Second,
Recoverable: true,
},
{
ID: "host:host=B,region=east",
Message: "host",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.OK,
Duration: 2 * time.Second,
Recoverable: true,
},
{
ID: "mem:host=A,region=east",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 8 * time.Second,
Recoverable: true,
},
{
ID: "mem:host=B,region=west",
Message: "mem",
Time: time.Date(1970, 1, 1, 0, 0, 9, 0, time.UTC),
Level: alert.Critical,
PreviousLevel: alert.Critical,
Duration: 8 * time.Second,
Recoverable: true,
},
}
ts.Close()
got := ts.Data()
// Remove the .Data result from the alerts
for i := range got {
got[i].Data = models.Result{}
}
// Sort results since order doesn't matter
//sort.Slice(want, func(i, j int) bool {
// if want[i].Time.Equal(want[j].Time) {
// return want[i].ID < want[j].ID
// }
// return want[i].Time.Before(want[j].Time)
//})
sort.Slice(got, func(i, j int) bool {
if got[i].Time.Equal(got[j].Time) {
return got[i].ID < got[j].ID
}
return got[i].Time.Before(got[j].Time)
})
t.Logf("want: %d got: %d", len(want), len(got))
if !cmp.Equal(got, want) {
t.Errorf("unexpected alert during inhibited run -want/+got\n%s", cmp.Diff(want, got))
}
//for i := range want {
// if !cmp.Equal(got[i], want[i]) {
// t.Errorf("unexpected alert during inhibited run -want/+got\n%s", cmp.Diff(want[i], got[i]))
// }
//}
}
func TestServer_AlertListHandlers(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
thl := cli.TopicHandlersLink("test")
// Number of handlers to create
n := 3
for i := 0; i < n; i++ {
id := fmt.Sprintf("handler%d", i)
if _, err := cli.CreateTopicHandler(thl, client.TopicHandlerOptions{
ID: id,
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
}); err != nil {
t.Fatal(err)
}
}
expHandlers := client.TopicHandlers{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/test/handlers?pattern="},
Topic: "test",
Handlers: []client.TopicHandler{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/test/handlers/handler0"},
ID: "handler0",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/test/handlers/handler1"},
ID: "handler1",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/test/handlers/handler2"},
ID: "handler2",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
},
},
}
handlers, err := cli.ListTopicHandlers(thl, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(handlers, expHandlers) {
t.Errorf("unexpected handlers:\ngot\n%+v\nexp\n%+v\n", handlers, expHandlers)
}
// Restart the server
s.Restart()
// Check again
handlers, err = cli.ListTopicHandlers(thl, nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(handlers, expHandlers) {
t.Errorf("unexpected handlers after restart:\ngot\n%+v\nexp\n%+v\n", handlers, expHandlers)
}
var exp client.TopicHandlers
// Pattern = *
handlers, err = cli.ListTopicHandlers(thl, &client.ListTopicHandlersOptions{
Pattern: "*",
})
if err != nil {
t.Fatal(err)
}
exp = expHandlers
exp.Link.Href = "/kapacitor/v1/alerts/topics/test/handlers?pattern=%2A"
if !reflect.DeepEqual(handlers, exp) {
t.Errorf("unexpected handlers with pattern \"*\":\ngot\n%+v\nexp\n%+v\n", handlers, exp)
}
// Pattern = handler*
handlers, err = cli.ListTopicHandlers(thl, &client.ListTopicHandlersOptions{
Pattern: "handler*",
})
if err != nil {
t.Fatal(err)
}
exp = expHandlers
exp.Link.Href = "/kapacitor/v1/alerts/topics/test/handlers?pattern=handler%2A"
if !reflect.DeepEqual(handlers, exp) {
t.Errorf("unexpected handlers with pattern \"handler*\":\ngot\n%+v\nexp\n%+v\n", handlers, exp)
}
// Pattern = handler0
handlers, err = cli.ListTopicHandlers(thl, &client.ListTopicHandlersOptions{
Pattern: "handler0",
})
if err != nil {
t.Fatal(err)
}
exp = expHandlers
exp.Link.Href = "/kapacitor/v1/alerts/topics/test/handlers?pattern=handler0"
exp.Handlers = expHandlers.Handlers[0:1]
if !reflect.DeepEqual(handlers, exp) {
t.Errorf("unexpected handlers with pattern \"handler0\":\ngot\n%+v\nexp\n%+v\n", handlers, exp)
}
}
func TestServer_AlertTopic(t *testing.T) {
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("misc"), client.TopicHandlerOptions{
ID: "testAlertHandler",
Kind: "tcp",
Options: map[string]interface{}{"address": "localhost:4657"},
}); err != nil {
t.Fatal(err)
}
expTopic := client.Topic{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/misc"},
ID: "misc",
Level: "OK",
Collected: 0,
EventsLink: client.Link{Relation: "events", Href: "/kapacitor/v1/alerts/topics/misc/events"},
HandlersLink: client.Link{Relation: "handlers", Href: "/kapacitor/v1/alerts/topics/misc/handlers"},
}
topic, err := cli.Topic(cli.TopicLink("misc"))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(topic, expTopic) {
t.Errorf("unexpected topic:\ngot\n%+v\nexp\n%+v\n", topic, expTopic)
}
}
func TestServer_AlertListTopics(t *testing.T) {
// Setup test TCP server
ts, err := alerttest.NewTCPServer()
if err != nil {
t.Fatal(err)
}
defer ts.Close()
// Create default config
c := NewConfig()
s := OpenServer(c)
cli := Client(s)
defer s.Close()
for _, topic := range []string{"system", "misc", "test"} {
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink(topic), client.TopicHandlerOptions{
ID: "testAlertHandler",
Kind: "tcp",
Options: map[string]interface{}{"address": ts.Addr},
}); err != nil {
t.Fatal(err)
}
}
expTopics := client.Topics{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics?min-level=OK&pattern="},
Topics: []client.Topic{
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/misc"},
ID: "misc",
Level: "OK",
EventsLink: client.Link{Relation: "events", Href: "/kapacitor/v1/alerts/topics/misc/events"},
HandlersLink: client.Link{Relation: "handlers", Href: "/kapacitor/v1/alerts/topics/misc/handlers"},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/system"},
ID: "system",
Level: "OK",
EventsLink: client.Link{Relation: "events", Href: "/kapacitor/v1/alerts/topics/system/events"},
HandlersLink: client.Link{Relation: "handlers", Href: "/kapacitor/v1/alerts/topics/system/handlers"},
},
{
Link: client.Link{Relation: client.Self, Href: "/kapacitor/v1/alerts/topics/test"},
ID: "test",
Level: "OK",
EventsLink: client.Link{Relation: "events", Href: "/kapacitor/v1/alerts/topics/test/events"},
HandlersLink: client.Link{Relation: "handlers", Href: "/kapacitor/v1/alerts/topics/test/handlers"},
},
},
}
topics, err := cli.ListTopics(nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(topics, expTopics) {
t.Errorf("unexpected topics:\ngot\n%+v\nexp\n%+v\n", topics, expTopics)
}
tick := `
stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Restart the server
s.Restart()
// Update expected topics since we triggered an event.
expTopics.Topics[2].Level = "CRITICAL"
// Check again
topics, err = cli.ListTopics(nil)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(topics, expTopics) {
t.Errorf("unexpected topics after restart:\ngot\n%+v\nexp\n%+v\n", topics, expTopics)
}
var exp client.Topics
// Pattern = *
topics, err = cli.ListTopics(&client.ListTopicsOptions{
Pattern: "*",
})
if err != nil {
t.Fatal(err)
}
exp = expTopics
exp.Link.Href = "/kapacitor/v1/alerts/topics?min-level=OK&pattern=%2A"
if !reflect.DeepEqual(topics, exp) {
t.Errorf("unexpected topics with pattern \"*\":\ngot\n%+v\nexp\n%+v\n", topics, exp)
}
// Pattern = test
topics, err = cli.ListTopics(&client.ListTopicsOptions{
Pattern: "test",
})
if err != nil {
t.Fatal(err)
}
exp = expTopics
exp.Link.Href = "/kapacitor/v1/alerts/topics?min-level=OK&pattern=test"
exp.Topics = expTopics.Topics[2:]
if !reflect.DeepEqual(topics, exp) {
t.Errorf("unexpected topics with pattern \"test\":\ngot\n%+v\nexp\n%+v\n", topics, exp)
}
// MinLevel = INFO
topics, err = cli.ListTopics(&client.ListTopicsOptions{
MinLevel: "INFO",
})
if err != nil {
t.Fatal(err)
}
exp = expTopics
exp.Link.Href = "/kapacitor/v1/alerts/topics?min-level=INFO&pattern="
exp.Topics = expTopics.Topics[2:]
if !reflect.DeepEqual(topics, exp) {
t.Errorf("unexpected topics min level \"info\":\ngot\n%+v\nexp\n%+v\n", topics, exp)
}
}
func TestServer_AlertHandler_MultipleHandlers(t *testing.T) {
resultJSON := `{"series":[{"name":"alert","columns":["time","value"],"values":[["1970-01-01T00:00:00Z",1]]}]}`
// Create default config
c := NewConfig()
// Configure slack
slack := slacktest.NewServer()
c.Slack[0].Enabled = true
c.Slack[0].URL = slack.URL + "/test/slack/url"
// Configure victorops
vo := victoropstest.NewServer()
c.VictorOps.Enabled = true
c.VictorOps.URL = vo.URL
c.VictorOps.APIKey = "api_key"
s := OpenServer(c)
cli := Client(s)
closed := false
defer func() {
if !closed {
s.Close()
}
}()
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testAlertHandlers-VO",
Kind: "victorops",
Options: map[string]interface{}{
"routing-key": "key",
},
}); err != nil {
t.Fatal(err)
}
if _, err := cli.CreateTopicHandler(cli.TopicHandlersLink("test"), client.TopicHandlerOptions{
ID: "testAlertHandlers-Slack",
Kind: "slack",
Options: map[string]interface{}{
"channel": "#test",
},
}); err != nil {
t.Fatal(err)
}
tick := `
stream
|from()
.measurement('alert')
|alert()
.topic('test')
.id('id')
.message('message')
.details('details')
.crit(lambda: TRUE)
`
if _, err := cli.CreateTask(client.CreateTaskOptions{
ID: "testAlertHandlers",
Type: client.StreamTask,
DBRPs: []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}},
TICKscript: tick,
Status: client.Enabled,
}); err != nil {
t.Fatal(err)
}
point := "alert value=1 0000000000"
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", point, v)
// Close the entire server to ensure all data is processed
s.Close()
closed = true
// Validate slack
{
slack.Close()
got := slack.Requests()
exp := []slacktest.Request{{
URL: "/test/slack/url",
PostData: slacktest.PostData{
Channel: "#test",
Username: "kapacitor",
Text: "",
Attachments: []slacktest.Attachment{
{
Fallback: "message",
Color: "danger",
Text: "message",
Mrkdwn_in: []string{"text"},
},
},
},
}}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected slack request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
}
// Validate victorops
{
vo.Close()
got := vo.Requests()
exp := []victoropstest.Request{{
URL: "/api_key/key",
PostData: victoropstest.PostData{
MessageType: "CRITICAL",
EntityID: "id",
StateMessage: "message",
Timestamp: 0,
MonitoringTool: "kapacitor",
Data: resultJSON,
},
}}
if !reflect.DeepEqual(exp, got) {
t.Errorf("unexpected victorops request:\nexp\n%+v\ngot\n%+v\n", exp, got)
}
}
}
func TestStorage_Rebuild(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
storages, err := cli.ListStorage()
if err != nil {
t.Fatal(err)
}
for _, storage := range storages.Storage {
t.Log(storage.Link)
err := cli.DoStorageAction(storage.Link, client.StorageActionOptions{
Action: client.StorageRebuild,
})
if err != nil {
t.Errorf("error rebuilding storage %q: %v", storage.Name, err)
}
}
}
func TestStorage_Backup(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
// Create a task
id := "testTaskID"
ttype := client.StreamTask
dbrps := []client.DBRP{
{
Database: "mydb",
RetentionPolicy: "myrp",
},
{
Database: "otherdb",
RetentionPolicy: "default",
},
}
tick := `stream
|from()
.measurement('test')
`
task, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Disabled,
})
if err != nil {
t.Fatal(err)
}
// Perform backup
size, r, err := cli.Backup()
if err != nil {
t.Fatal(err)
}
defer r.Close()
backup, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err)
}
if got, exp := int64(len(backup)), size; got != exp {
t.Fatalf("unexpected backup size got %d exp %d", got, exp)
}
// Stop the server
s.Stop()
// Restore from backup
if err := ioutil.WriteFile(s.Config.Storage.BoltDBPath, backup, 0644); err != nil {
t.Fatal(err)
}
// Start the server again
s.Start()
// Check that the task was restored
ti, err := cli.Task(task.Link, nil)
if err != nil {
t.Fatal(err)
}
if ti.Error != "" {
t.Fatal(ti.Error)
}
if ti.ID != id {
t.Fatalf("unexpected id got %s exp %s", ti.ID, id)
}
if ti.Type != client.StreamTask {
t.Fatalf("unexpected type got %v exp %v", ti.Type, client.StreamTask)
}
if ti.Status != client.Disabled {
t.Fatalf("unexpected status got %v exp %v", ti.Status, client.Disabled)
}
if !reflect.DeepEqual(ti.DBRPs, dbrps) {
t.Fatalf("unexpected dbrps got %s exp %s", ti.DBRPs, dbrps)
}
if ti.TICKscript != tick {
t.Fatalf("unexpected TICKscript got %s exp %s", ti.TICKscript, tick)
}
dot := "digraph testTaskID {\nstream0 -> from1;\n}"
if ti.Dot != dot {
t.Fatalf("unexpected dot\ngot\n%s\nexp\n%s\n", ti.Dot, dot)
}
}
func TestLoadService(t *testing.T) {
s, c, cli := OpenLoadServer()
// If the list of test fixtures changes update this list
tasks := []string{"base", "cpu_alert", "implicit", "join", "other"}
ts, err := cli.ListTasks(nil)
if err != nil {
t.Fatalf("enountered error listing tasks: %v", err)
}
for i, task := range ts {
if exp, got := tasks[i], task.ID; exp != got {
t.Fatalf("expected task ID to be %v, got %v\n", exp, got)
}
}
// If the list of test fixtures changes update this list
templates := []string{"base_template", "implicit_template"}
tmps, err := cli.ListTemplates(nil)
if err != nil {
t.Fatalf("enountered error listing tasks: %v", err)
}
for i, template := range tmps {
if exp, got := templates[i], template.ID; exp != got {
t.Fatalf("expected template ID to be %v, got %v\n", exp, got)
}
}
// If the list of test fixtures changes update this list
topicHandlers := []string{"example", "other"}
link := cli.TopicHandlersLink("cpu")
ths, err := cli.ListTopicHandlers(link, nil)
if err != nil {
t.Fatalf("enountered error listing tasks: %v", err)
}
for i, th := range ths.Handlers {
if exp, got := topicHandlers[i], th.ID; exp != got {
t.Fatalf("expected topic-handler ID to be %v, got %v\n", exp, got)
}
}
// delete task file
err = os.Rename(
path.Join(c.Load.Dir, "tasks", "join.tick"),
path.Join(c.Load.Dir, "tasks", "z.tick"),
)
if err != nil {
t.Fatalf("failed to rename tickscript: %v", err)
}
// reload
s.Reload()
// If the list of test fixtures changes update this list
tasks = []string{"base", "cpu_alert", "implicit", "other", "z"}
ts, err = cli.ListTasks(nil)
if err != nil {
t.Fatalf("enountered error listing tasks: %v", err)
}
for i, task := range ts {
if exp, got := tasks[i], task.ID; exp != got {
t.Fatalf("expected task ID to be %v, got %v\n", exp, got)
}
}
// rename template file
err = os.Rename(
path.Join(c.Load.Dir, "templates", "base_template.tick"),
path.Join(c.Load.Dir, "templates", "new.tick"),
)
if err != nil {
t.Fatalf("failed to rename tickscript: %v", err)
}
// reload
s.Reload()
// If the list of test fixtures changes update this list
templates = []string{"implicit_template", "new"}
tmps, err = cli.ListTemplates(nil)
if err != nil {
t.Fatalf("enountered error listing templates: %v", err)
}
for i, template := range tmps {
if exp, got := templates[i], template.ID; exp != got {
t.Fatalf("expected template ID to be %v, got %v\n", exp, got)
}
}
// move template file back
err = os.Rename(
path.Join(c.Load.Dir, "templates", "new.tick"),
path.Join(c.Load.Dir, "templates", "base_template.tick"),
)
// add a new handler
f, err := os.Create(path.Join(c.Load.Dir, "handlers", "new.tick"))
if err != nil {
t.Fatalf("failed to create new handler file: %v", err)
}
script := `topic: cpu
id: new
kind: slack
match: changed() == TRUE
options:
channel: '#alerts'
`
if _, err := f.Write([]byte(script)); err != nil {
t.Fatalf("failed to write handler: %v", err)
}
f.Close()
// remove handler file back
if err := os.Remove(path.Join(c.Load.Dir, "handlers", "other.yaml")); err != nil {
t.Fatalf("failed to remove handler file: %v", err)
}
// reload
s.Reload()
// If the list of test fixtures changes update this list
topicHandlers = []string{"example", "new"}
link = cli.TopicHandlersLink("cpu")
ths, err = cli.ListTopicHandlers(link, nil)
if err != nil {
t.Fatalf("enountered error listing topic-handlers: %v", err)
}
for i, th := range ths.Handlers {
if exp, got := topicHandlers[i], th.ID; exp != got {
t.Fatalf("expected topic-handler ID to be %v, got %v\n", exp, got)
}
}
}
func TestSideloadService(t *testing.T) {
dir := MustTempDir()
defer os.RemoveAll(dir)
if err := copyFiles("testdata/sideload", dir); err != nil {
t.Fatal(err)
}
s, cli := OpenDefaultServer()
defer s.Close()
id := "testSideloadTask"
ttype := client.StreamTask
dbrps := []client.DBRP{{
Database: "mydb",
RetentionPolicy: "myrp",
}}
tick := fmt.Sprintf(`stream
|from()
.measurement('test')
|sideload()
.source('file://%s')
.order('host/{{.host}}.yml', 'service/{{.service}}.yml', 'region/{{.region}}.yml')
.field('cpu_usage_idle_warn', 30.0)
.field('cpu_usage_idle_crit', 15.0)
|httpOut('sideload')
`, dir)
_, err := cli.CreateTask(client.CreateTaskOptions{
ID: id,
Type: ttype,
DBRPs: dbrps,
TICKscript: tick,
Status: client.Enabled,
})
if err != nil {
t.Fatal(err)
}
endpoint := fmt.Sprintf("%s/tasks/%s/sideload", s.URL(), id)
// Request data before any writes and expect null responses
nullResponse := `{"series":null}`
err = s.HTTPGetRetry(endpoint, nullResponse, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
points := `test,host=host002,service=cart,region=us-east-1 value=1 0000000000`
v := url.Values{}
v.Add("precision", "s")
s.MustWrite("mydb", "myrp", points, v)
exp := `{"series":[{"name":"test","tags":{"host":"host002","region":"us-east-1","service":"cart"},"columns":["time","cpu_usage_idle_crit","cpu_usage_idle_warn","value"],"values":[["1970-01-01T00:00:00Z",4,10,1]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
// Update source file
host002Override := `
---
cpu_usage_idle_warn: 8
`
f, err := os.Create(filepath.Join(dir, "host/host002.yml"))
if err != nil {
t.Fatal(err)
}
_, err = io.Copy(f, strings.NewReader(host002Override))
if err != nil {
t.Fatal(err)
}
f.Close()
// reload
s.Reload()
// Write new points
points = `test,host=host002,service=cart,region=us-east-1 value=2 0000000001`
s.MustWrite("mydb", "myrp", points, v)
exp = `{"series":[{"name":"test","tags":{"host":"host002","region":"us-east-1","service":"cart"},"columns":["time","cpu_usage_idle_crit","cpu_usage_idle_warn","value"],"values":[["1970-01-01T00:00:01Z",5,8,2]]}]}`
err = s.HTTPGetRetry(endpoint, exp, 100, time.Millisecond*5)
if err != nil {
t.Error(err)
}
}
func TestLogSessions_HeaderJSON(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
u := cli.BaseURL()
u.Path = "/logs"
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
t.Fatal(err)
return
}
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
return
}
defer resp.Body.Close()
if exp, got := "application/json; charset=utf-8", resp.Header.Get("Content-Type"); exp != got {
t.Fatalf("expected: %v, got: %v\n", exp, got)
return
}
}
func TestLogSessions_HeaderGzip(t *testing.T) {
s, cli := OpenDefaultServer()
defer s.Close()
u := cli.BaseURL()
u.Path = "/logs"
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
t.Fatal(err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
return
}
defer resp.Body.Close()
if exp, got := "", resp.Header.Get("Content-Encoding"); exp != got {
t.Fatalf("expected: %v, got: %v\n", exp, got)
return
}
}
func TestFluxTasks_Basic(t *testing.T) {
conf := NewConfig()
conf.FluxTask.Enabled = true
conf.FluxTask.TaskRunInfluxDB = "none"
s := OpenServer(conf)
cli := Client(s)
defer s.Close()
// Check we can query empty tasks
u := cli.BaseURL()
basePath := "kapacitor/v1/api/v2/tasks"
query := func(method string, path string, body string) string {
u.Path = path
t.Log("Querying: ", method, u.String())
req, err := http.NewRequest(method, u.String(), bytes.NewBufferString(body))
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
buf := bytes.Buffer{}
_, err = io.Copy(&buf, resp.Body)
require.NoError(t, err)
return strings.Trim(buf.String(), "\n")
}
assert.Equal(t, `{"links":{"self":"/kapacitor/v1/api/v2/tasks?limit=100"},"tasks":[]}`, query("GET", basePath, ""))
// Start a simple server. It listens on port and closes requestDone when finished.
// This lets us create a task that uses the flux-native http.Post and assert that
// flux is configured properly
listener, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
port := listener.Addr().(*net.TCPAddr).Port
server := &http.Server{}
requestStarted := make(chan struct{})
requestStopped := make(chan struct{})
go func() {
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
<-requestStarted
<-requestStopped
})
server.Serve(listener)
}()
defer server.Close()
// create a task, assert on the important parts of it
fluxScript := fmt.Sprintf(`import "http"
option task = {concurrency: 1, name:"poster", every:1s}
http.post(url: "http://localhost:%d")
`, port)
task := fmt.Sprintf(`{"status": "active", "description": "simple post", "flux": %q}`, fluxScript)
createResp := make(map[string]interface{})
require.NoError(t, json.Unmarshal([]byte(query("POST", basePath, task)), &createResp))
id := createResp["id"].(string)
assert.Equal(t, 16, len(id))
assert.Contains(t, createResp, "orgID")
assert.Equal(t, "", createResp["orgID"])
assert.Equal(t, "poster", createResp["name"])
logPath := fmt.Sprintf("/kapacitor/v1/api/v2/tasks/%s/logs", id)
runPath := fmt.Sprintf("/kapacitor/v1/api/v2/tasks/%s/runs", id)
selfPath := fmt.Sprintf("/kapacitor/v1/api/v2/tasks/%s", id)
assert.Equal(t, map[string]interface{}{
"logs": logPath,
"runs": runPath,
"self": selfPath,
}, createResp["links"])
t.Log("waiting for request")
requestStarted <- struct{}{}
// Request is now started (it hit our test server with a post) but can't finish - time to assert that we have runs and logs
logResp := make(map[string]interface{})
require.NoError(t, json.Unmarshal([]byte(query("GET", logPath, task)), &logResp))
expectMessage := "Started task from script:"
assert.Equal(t, expectMessage, logResp["events"].([]interface{})[0].(map[string]interface{})["message"].(string)[:len(expectMessage)])
runResp := make(map[string]interface{})
require.NoError(t, json.Unmarshal([]byte(query("GET", runPath, task)), &runResp))
assert.Equal(t, map[string]interface{}{
"task": selfPath,
"self": runPath,
}, runResp["links"])
// stop blocking the server
close(requestStarted)
close(requestStopped)
// Assert that we can really update a task
query("PATCH", selfPath, `{"every": "10m"}`)
getResp := make(map[string]interface{})
require.NoError(t, json.Unmarshal([]byte(query("GET", selfPath, task)), &getResp))
assert.Equal(t, getResp["every"], "10m")
// Assert that when we delete a task it goes away
query("DELETE", selfPath, "")
assert.Equal(t, `{"links":{"self":"/kapacitor/v1/api/v2/tasks?limit=100"},"tasks":[]}`, query("GET", basePath, ""))
}
func compareListIgnoreOrder(got, exp []interface{}, cmpF func(got, exp interface{}) bool) error {
if len(got) != len(exp) {
return fmt.Errorf("unequal lists ignoring order:\ngot\n%s\nexp\n%s\n", spew.Sdump(got), spew.Sdump(exp))
}
if cmpF == nil {
cmpF = func(got, exp interface{}) bool {
if !reflect.DeepEqual(got, exp) {
return false
}
return true
}
}
for _, e := range exp {
found := false
for _, g := range got {
if cmpF(g, e) {
found = true
break
}
}
if !found {
return fmt.Errorf("unequal lists ignoring order:\ngot\n%s\nexp\n%s\n", spew.Sdump(got), spew.Sdump(exp))
}
}
return nil
}
func TestServer_Authenticate_Fail_Enterprise(t *testing.T) {
t.Parallel()
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
defer s.Close()
cli, err := client.New(client.Config{
URL: s.URL(),
})
if err != nil {
t.Fatal(err)
}
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "unable to parse authentication credentials", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_User_Enterprise(t *testing.T) {
t.Parallel()
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
defer s.Close()
s.AuthService.(*auth.Service).CreateUser("root", "kapacitor", true, nil)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "root",
Password: "kapacitor",
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateUser(client.CreateUserOptions{
Name: "bob",
Password: "secret",
Type: client.AdminUser,
}); err != nil {
t.Fatal(err)
}
if err := s.PingAsUser("bob", "secret"); err != nil {
t.Fatal(err)
}
}
func TestServer_Authenticate_Bearer_Fail_Enterprise(t *testing.T) {
t.Parallel()
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(10 * time.Second).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
// Use a different secret so the token is invalid
conf.HTTP.SharedSecret = secret + "extra secret"
s := OpenServer(conf)
defer s.Close()
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
})
if err != nil {
t.Fatal(err)
}
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "invalid token: signature is invalid", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_Bearer_Expired_Enteprise(t *testing.T) {
t.Parallel()
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(-10 * time.Second).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.HTTP.AuthEnabled = true
conf.HTTP.SharedSecret = secret
s := OpenServer(conf)
defer s.Close()
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
})
if err != nil {
t.Fatal(err)
}
_, _, err = cli.Ping()
if err == nil {
t.Error("expected authentication error")
} else if exp, got := "invalid token: Token is expired", err.Error(); got != exp {
t.Errorf("unexpected error message: got %q exp %q", got, exp)
}
}
func TestServer_Authenticate_Bearer_Enterprise(t *testing.T) {
t.Parallel()
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(time.Minute).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
conf.HTTP.SharedSecret = secret
s := OpenServer(conf)
defer s.Close()
s.AuthService.(*auth.Service).CreateUser("root", "kapacitor", true, nil)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "root",
Password: "kapacitor",
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateUser(client.CreateUserOptions{
Name: "bob",
Password: "secret",
Type: client.AdminUser,
}); err != nil {
t.Fatal(err)
}
if err := s.PingWithToken(tokenString); err != nil {
t.Fatal(err)
}
}
func TestServer_Authenticate_Bearer_PermissionDenied(t *testing.T) {
t.Parallel()
secret := "secret"
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": "bob",
"exp": time.Now().Add(time.Minute).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatal(err)
}
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
conf.HTTP.SharedSecret = secret
s := OpenServer(conf)
defer s.Close()
s.AuthService.(*auth.Service).CreateUser("root", "kapacitor", true, nil)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "root",
Password: "kapacitor",
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateUser(client.CreateUserOptions{
Name: "bob",
Password: "secret",
Type: client.NormalUser,
Permissions: []client.Permission{
client.WritePointsPermission,
},
}); err != nil {
t.Fatal(err)
}
if bobsCLI, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.BearerAuthentication,
Token: tokenString,
},
}); err != nil {
t.Fatal(err)
} else {
// Ping is allowed
if _, version, err := bobsCLI.Ping(); err != nil {
t.Fatal(err)
} else if version != "testServer" {
t.Fatal("unexpected version", version)
}
// Delete user is not allowed
if err := bobsCLI.DeleteUser(bobsCLI.UserLink("root")); err == nil {
t.Fatal("expected permission denied error")
} else if got, exp := err.Error(), `user bob does not have "delete" privilege for API endpoint "/kapacitor/v1/users/root"`; got != exp {
t.Errorf("unexpected error message: got %s exp %s", got, exp)
}
}
}
func TestServer_Authenticate_User_PermissionDenied(t *testing.T) {
t.Parallel()
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
defer s.Close()
s.AuthService.(*auth.Service).CreateUser("root", "kapacitor", true, nil)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "root",
Password: "kapacitor",
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateUser(client.CreateUserOptions{
Name: "bob",
Password: "secret",
Type: client.NormalUser,
Permissions: []client.Permission{
client.WritePointsPermission,
},
}); err != nil {
t.Fatal(err)
}
if bobsCLI, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "bob",
Password: "secret",
},
}); err != nil {
t.Fatal(err)
} else {
// Ping is allowed
if _, version, err := bobsCLI.Ping(); err != nil {
t.Fatal(err)
} else if version != "testServer" {
t.Fatal("unexpected version", version)
}
// Delete user is not allowed
if err := bobsCLI.DeleteUser(bobsCLI.UserLink("root")); err == nil {
t.Fatal("expected permission denied error")
} else if got, exp := err.Error(), `user bob does not have "delete" privilege for API endpoint "/kapacitor/v1/users/root"`; got != exp {
t.Errorf("unexpected error message: got %s exp %s", got, exp)
}
}
}
func TestServer_Authenticate_User_Multiple(t *testing.T) {
t.Parallel()
conf := NewConfig()
conf.Auth = auth.NewEnabledConfig()
conf.HTTP.AuthEnabled = true
s := OpenServer(conf)
defer s.Close()
s.AuthService.(*auth.Service).CreateUser("root", "kapacitor", true, nil)
cli, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "root",
Password: "kapacitor",
},
})
if err != nil {
t.Fatal(err)
}
if _, err := cli.CreateUser(client.CreateUserOptions{
Name: "bob",
Password: "secret",
Type: client.NormalUser,
Permissions: []client.Permission{
client.WritePointsPermission,
},
}); err != nil {
t.Fatal(err)
}
if bobsCLI, err := client.New(client.Config{
URL: s.URL(),
Credentials: &client.Credentials{
Method: client.UserAuthentication,
Username: "bob",
Password: "secret",
},
}); err != nil {
t.Fatal(err)
} else {
count := 10
for i := 0; i < count; i++ {
// Ping is allowed
if _, version, err := bobsCLI.Ping(); err != nil {
t.Fatal(err)
} else if version != "testServer" {
t.Fatal("unexpected version", version)
}
// Delete user is not allowed
if err := bobsCLI.DeleteUser(bobsCLI.UserLink("root")); err == nil {
t.Fatal("expected permission denied error")
} else if got, exp := err.Error(), `user bob does not have "delete" privilege for API endpoint "/kapacitor/v1/users/root"`; got != exp {
t.Errorf("unexpected error message: got %s exp %s", got, exp)
}
}
}
}
func TestServer_UpdateUser_EmptyPermissions(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
username := "bob"
utype := client.NormalUser
permissions := []client.Permission{
client.APIPermission,
}
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: "hunter2",
Type: utype,
Permissions: permissions,
})
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
user, err = cli.UpdateUser(user.Link, client.UpdateUserOptions{
Permissions: []client.Permission{},
})
if err != nil {
t.Fatal(err)
}
user, err = cli.User(user.Link)
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if got, exp := len(user.Permissions), 0; got != exp {
t.Fatalf("unexpected permission count got %d exp %d", got, exp)
}
}
func TestServer_UpdateUser_Password_IgnorePerms(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
username := "bob"
utype := client.NormalUser
password := "hunter2"
permissions := []client.Permission{client.WritePointsPermission}
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: password,
Type: utype,
Permissions: permissions,
})
if err != nil {
t.Fatal(err)
}
if err := s.PingAsUser(username, password); err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
// Update password only, permissions should remain the same.
password = "*******"
user, err = cli.UpdateUser(user.Link, client.UpdateUserOptions{
Password: password,
})
if err != nil {
t.Fatal(err)
}
if err := s.PingAsUser(username, password); err != nil {
t.Fatal(err)
}
user, err = cli.User(user.Link)
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
}
func TestServer_UpdateUser_Type(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
username := "bob"
utype := client.AdminUser
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: "hunter2",
Type: utype,
})
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if got, exp := len(user.Permissions), 0; got != exp {
t.Fatalf("unexpected permission count got %d exp %d", got, exp)
}
utype = client.NormalUser
user, err = cli.UpdateUser(user.Link, client.UpdateUserOptions{
Type: utype,
})
if err != nil {
t.Fatal(err)
}
user, err = cli.User(user.Link)
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if got, exp := len(user.Permissions), 0; got != exp {
t.Fatalf("unexpected permission count got %d exp %d", got, exp)
}
}
func TestServer_DeleteUser(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
username := "bob"
utype := client.AdminUser
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: "hunter2",
Type: utype,
})
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, "/kapacitor/v1/users/bob"; got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if got, exp := len(user.Permissions), 0; got != exp {
t.Fatalf("unexpected permission count got %d exp %d", got, exp)
}
if err := cli.DeleteUser(user.Link); err != nil {
t.Fatal(err)
}
if _, err := cli.User(user.Link); err == nil {
t.Fatal("expected error for non existent user")
}
}
func TestServer_ListUsers(t *testing.T) {
t.Parallel()
config := NewConfig()
config.Auth = auth.NewEnabledConfig()
s := OpenServer(config)
cli := Client(s)
defer s.Close()
utype := client.NormalUser
permissions := []client.Permission{
client.APIPermission,
}
count := 20
for i := 0; i < count; i++ {
username := fmt.Sprintf("bob%02d", i)
user, err := cli.CreateUser(client.CreateUserOptions{
Name: username,
Password: "hunter2",
Type: utype,
Permissions: permissions,
})
if err != nil {
t.Fatal(err)
}
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, fmt.Sprintf("/kapacitor/v1/users/%s", username); got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
}
// List only bob* users, aka exclude the root user
users, err := cli.ListUsers(&client.ListUsersOptions{
Pattern: "bob*",
})
if err != nil {
t.Fatal(err)
}
if got, exp := len(users), count; got != exp {
t.Fatalf("unexpected user count got %d exp %d", got, exp)
}
for i, user := range users {
username := fmt.Sprintf("bob%02d", i)
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, fmt.Sprintf("/kapacitor/v1/users/%s", username); got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
if !reflect.DeepEqual(user.Permissions, permissions) {
t.Fatalf("unexpected permissions got %s exp %s", user.Permissions, permissions)
}
}
// List only bob1* users at +2 offset
users, err = cli.ListUsers(&client.ListUsersOptions{
Pattern: "bob1*",
Fields: []string{"type"},
Offset: 2,
})
if err != nil {
t.Fatal(err)
}
if got, exp := len(users), 8; got != exp {
t.Fatalf("unexpected user count got %d exp %d", got, exp)
}
for i, user := range users {
username := fmt.Sprintf("bob%02d", i+12)
if got, exp := user.Name, username; got != exp {
t.Fatalf("unexpected username got %s exp %s", got, exp)
}
if got, exp := user.Link.Href, fmt.Sprintf("/kapacitor/v1/users/%s", username); got != exp {
t.Fatalf("unexpected link got %s exp %s", got, exp)
}
if got, exp := user.Type, utype; got != exp {
t.Fatalf("unexpected type got %v exp %v", got, exp)
}
}
}
|
[
"\"PYTHONPATH\"",
"\"PYTHONPATH\"",
"\"PYTHONPATH\"",
"\"PYTHONPATH\"",
"\"PYTHONPATH\"",
"\"PYTHONPATH\""
] |
[] |
[
"PYTHONPATH"
] |
[]
|
["PYTHONPATH"]
|
go
| 1 | 0 | |
venv/Lib/site-packages/coverage/misc.py
|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Miscellaneous stuff for coverage.py."""
import errno
import hashlib
import inspect
import locale
import os
import os.path
import random
import re
import socket
import sys
import types
from coverage import env
from coverage.backward import to_bytes, unicode_class
ISOLATED_MODULES = {}
def isolate_module(mod):
"""Copy a module so that we are isolated from aggressive mocking.
If a test suite mocks os.path.exists (for example), and then we need to use
it during the test, everything will get tangled up if we use their mock.
Making a copy of the module when we import it will isolate coverage.py from
those complications.
"""
if mod not in ISOLATED_MODULES:
new_mod = types.ModuleType(mod.__name__)
ISOLATED_MODULES[mod] = new_mod
for name in dir(mod):
value = getattr(mod, name)
if isinstance(value, types.ModuleType):
value = isolate_module(value)
setattr(new_mod, name, value)
return ISOLATED_MODULES[mod]
os = isolate_module(os)
def dummy_decorator_with_args(*args_unused, **kwargs_unused):
"""Dummy no-op implementation of a decorator with arguments."""
def _decorator(func):
return func
return _decorator
# Environment COVERAGE_NO_CONTRACTS=1 can turn off contracts while debugging
# tests to remove noise from stack traces.
# $set_env.py: COVERAGE_NO_CONTRACTS - Disable PyContracts to simplify stack traces.
USE_CONTRACTS = env.TESTING and not bool(int(os.environ.get("COVERAGE_NO_CONTRACTS", 0)))
# Use PyContracts for assertion testing on parameters and returns, but only if
# we are running our own test suite.
if USE_CONTRACTS:
from contracts import contract # pylint: disable=unused-import
from contracts import new_contract as raw_new_contract
def new_contract(*args, **kwargs):
"""A proxy for contracts.new_contract that doesn't mind happening twice."""
try:
raw_new_contract(*args, **kwargs)
except ValueError:
# During meta-coverage, this module is imported twice, and
# PyContracts doesn't like redefining contracts. It's OK.
pass
# Define contract words that PyContract doesn't have.
new_contract('bytes', lambda v: isinstance(v, bytes))
if env.PY3:
new_contract('unicode', lambda v: isinstance(v, unicode_class))
def one_of(argnames):
"""Ensure that only one of the argnames is non-None."""
def _decorator(func):
argnameset = {name.strip() for name in argnames.split(",")}
def _wrapper(*args, **kwargs):
vals = [kwargs.get(name) for name in argnameset]
assert sum(val is not None for val in vals) == 1
return func(*args, **kwargs)
return _wrapper
return _decorator
else: # pragma: not testing
# We aren't using real PyContracts, so just define our decorators as
# stunt-double no-ops.
contract = dummy_decorator_with_args
one_of = dummy_decorator_with_args
def new_contract(*args_unused, **kwargs_unused):
"""Dummy no-op implementation of `new_contract`."""
pass
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end)
def expensive(fn):
"""A decorator to indicate that a method shouldn't be called more than once.
Normally, this does nothing. During testing, this raises an exception if
called more than once.
"""
if env.TESTING:
attr = "_once_" + fn.__name__
def _wrapper(self):
if hasattr(self, attr):
raise AssertionError("Shouldn't have called %s more than once" % fn.__name__)
setattr(self, attr, True)
return fn(self)
return _wrapper
else:
return fn # pragma: not testing
def bool_or_none(b):
"""Return bool(b), but preserve None."""
if b is None:
return None
else:
return bool(b)
def join_regex(regexes):
"""Combine a list of regexes into one that matches any of them."""
return "|".join("(?:%s)" % r for r in regexes)
def file_be_gone(path):
"""Remove a file, and don't get annoyed if it doesn't exist."""
try:
os.remove(path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def ensure_dir(directory):
"""Make sure the directory exists.
If `directory` is None or empty, do nothing.
"""
if directory and not os.path.isdir(directory):
os.makedirs(directory)
def ensure_dir_for_file(path):
"""Make sure the directory for the path exists."""
ensure_dir(os.path.dirname(path))
def output_encoding(outfile=None):
"""Determine the encoding to use for output written to `outfile` or stdout."""
if outfile is None:
outfile = sys.stdout
encoding = (
getattr(outfile, "encoding", None) or
getattr(sys.__stdout__, "encoding", None) or
locale.getpreferredencoding()
)
return encoding
def filename_suffix(suffix):
"""Compute a filename suffix for a data file.
If `suffix` is a string or None, simply return it. If `suffix` is True,
then build a suffix incorporating the hostname, process id, and a random
number.
Returns a string or None.
"""
if suffix is True:
# If data_suffix was a simple true value, then make a suffix with
# plenty of distinguishing information. We do this here in
# `save()` at the last minute so that the pid will be correct even
# if the process forks.
dice = random.Random(os.urandom(8)).randint(0, 999999)
suffix = "%s.%s.%06d" % (socket.gethostname(), os.getpid(), dice)
return suffix
class Hasher(object):
"""Hashes Python data into md5."""
def __init__(self):
self.md5 = hashlib.md5()
def update(self, v):
"""Add `v` to the hash, recursively if needed."""
self.md5.update(to_bytes(str(type(v))))
if isinstance(v, unicode_class):
self.md5.update(v.encode('utf8'))
elif isinstance(v, bytes):
self.md5.update(v)
elif v is None:
pass
elif isinstance(v, (int, float)):
self.md5.update(to_bytes(str(v)))
elif isinstance(v, (tuple, list)):
for e in v:
self.update(e)
elif isinstance(v, dict):
keys = v.keys()
for k in sorted(keys):
self.update(k)
self.update(v[k])
else:
for k in dir(v):
if k.startswith('__'):
continue
a = getattr(v, k)
if inspect.isroutine(a):
continue
self.update(k)
self.update(a)
self.md5.update(b'.')
def hexdigest(self):
"""Retrieve the hex digest of the hash."""
return self.md5.hexdigest()
def _needs_to_implement(that, func_name):
"""Helper to raise NotImplementedError in interface stubs."""
if hasattr(that, "_coverage_plugin_name"):
thing = "Plugin"
name = that._coverage_plugin_name
else:
thing = "Class"
klass = that.__class__
name = "{klass.__module__}.{klass.__name__}".format(klass=klass)
raise NotImplementedError(
"{thing} {name!r} needs to implement {func_name}()".format(
thing=thing, name=name, func_name=func_name
)
)
class DefaultValue(object):
"""A sentinel object to use for unusual default-value needs.
Construct with a string that will be used as the repr, for display in help
and Sphinx output.
"""
def __init__(self, display_as):
self.display_as = display_as
def __repr__(self):
return self.display_as
def substitute_variables(text, variables):
"""Substitute ``${VAR}`` variables in `text` with their values.
Variables in the text can take a number of shell-inspired forms::
$VAR
${VAR}
${VAR?} strict: an error if VAR isn't defined.
${VAR-missing} defaulted: "missing" if VAR isn't defined.
$$ just a dollar sign.
`variables` is a dictionary of variable values.
Returns the resulting text with values substituted.
"""
dollar_pattern = r"""(?x) # Use extended regex syntax
\$ # A dollar sign,
(?: # then
(?P<dollar>\$) | # a dollar sign, or
(?P<word1>\w+) | # a plain word, or
{ # a {-wrapped
(?P<word2>\w+) # word,
(?:
(?P<strict>\?) | # with a strict marker
-(?P<defval>[^}]*) # or a default value
)? # maybe.
}
)
"""
def dollar_replace(match):
"""Called for each $replacement."""
# Only one of the groups will have matched, just get its text.
word = next(g for g in match.group('dollar', 'word1', 'word2') if g)
if word == "$":
return "$"
elif word in variables:
return variables[word]
elif match.group('strict'):
msg = "Variable {} is undefined: {!r}".format(word, text)
raise CoverageException(msg)
else:
return match.group('defval')
text = re.sub(dollar_pattern, dollar_replace, text)
return text
class BaseCoverageException(Exception):
"""The base of all Coverage exceptions."""
pass
class CoverageException(BaseCoverageException):
"""An exception raised by a coverage.py function."""
pass
class NoSource(CoverageException):
"""We couldn't find the source for a module."""
pass
class NoCode(NoSource):
"""We couldn't find any code at all."""
pass
class NotPython(CoverageException):
"""A source file turned out not to be parsable Python."""
pass
class ExceptionDuringRun(CoverageException):
"""An exception happened while running customer code.
Construct it with three arguments, the values from `sys.exc_info`.
"""
pass
class StopEverything(BaseCoverageException):
"""An exception that means everything should stop.
The CoverageTest class converts these to SkipTest, so that when running
tests, raising this exception will automatically skip the test.
"""
pass
|
[] |
[] |
[
"COVERAGE_NO_CONTRACTS"
] |
[]
|
["COVERAGE_NO_CONTRACTS"]
|
python
| 1 | 0 | |
ce_expansion/atomgraph/bcm.py
|
import itertools
import collections.abc
import functools
from typing import Iterable, Optional, Dict
import numpy as np
import ase
import ase.units
from ce_expansion.atomgraph import adjacency
from ce_expansion.data.gamma import GammaValues
def recursive_update(d: dict, u: dict) -> dict:
"""
recursively updates 'dict of dicts'
Ex)
d = {0: {1: 2}}
u = {0: {3: 4}, 8: 9}
recursive_update(d, u) == {0: {1: 2, 3: 4}, 8: 9}
Args:
d (dict): the nested dict object to update
u (dict): the nested dict that contains new key-value pairs
Returns:
d (dict): the final updated dict
"""
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = recursive_update(d.get(k, {}), v)
else:
d[k] = v
return d
class BCModel:
def __init__(self, atoms: ase.Atoms, metal_types: Optional[Iterable] = None,
bond_list: Optional[Iterable] = None, info: dict = {}):
"""
Based on metal_types, create ce_bulk and gamma dicts from data given
Args:
atoms: ASE atoms object which contains the data of the NP being tested
bond_list: list of atom indices involved in each bond
KArgs:
metal_types: List of metals found within the nano-particle
If not passed, use elements provided by the atoms object
"""
self.atoms = atoms.copy()
self.atoms.pbc = False
self.info = info
if metal_types is None:
# get metal_types from atoms object
self.metal_types = sorted(set(atoms.symbols))
else:
# ensure metal_types to unique, sorted list of metals
self.metal_types = sorted(set(m.title() for m in metal_types))
self.bond_list = bond_list
if self.bond_list is None:
self.bond_list = adjacency.build_bonds_arr(self.atoms)
self.cn = np.bincount(self.bond_list[:, 0])
# creating gamma list for every possible atom pairing
self.gammas = None
self.ce_bulk = None
self._get_bcm_params()
# get bonded atom columns
self.a1 = self.bond_list[:, 0]
self.a2 = self.bond_list[:, 1]
# Calculate and set the precomps matrix
self.precomps = None
self.cn_precomps = None
self._get_precomps()
def __len__(self) -> int:
return len(self.atoms)
def calc_ce(self, orderings: np.ndarray) -> float:
"""
Calculates the Cohesive energy (in eV / atom) of the ordering given or of the default ordering of the NP
[Cohesive Energy] = ( [precomp values of element A and B] / sqrt(12 * CN) ) / [num atoms]
Args:
orderings: The ordering of atoms within the NP; ordering key is based on Metals in alphabetical order
Returns:
Cohesive Energy (eV / atom)
"""
return (self.precomps[orderings[self.a1], orderings[self.a2]] / self.cn_precomps).sum() / len(self.atoms)
def calc_ee(self, orderings: np.ndarray) -> float:
"""
Calculates the Excess energy (in eV / atom) of the ordering given or of the default ordering of the NP
[Excess Energy] = [CE of NP] - sum([Pure Element NP] * [Comp of Element in NP])
Args:
orderings: The ordering of atoms within the NP; ordering key is based on Metals in alphabetical order
Returns:
Excess Energy (eV / atom)
"""
metals = np.bincount(orderings)
# obtain atom fractions of each tested element
x_i = np.zeros(len(self.metal_types)).astype(float)
x_i[:len(metals)] = metals / metals.sum()
# calculate energy of tested NP first;
ee = self.calc_ce(orderings)
# Then, subtract calculated pure NP energies multiplied by respective
# fractions to get Excess Energy
for ele in range(len(self.metal_types)):
x_ele = x_i[ele]
o_mono_x = np.ones(len(self), int) * ele
ee -= self.calc_ce(o_mono_x) * x_ele
return ee
def calc_smix(self, orderings: np.ndarray) -> float:
"""
Uses boltzman constant, orderings, and element compositions to determine the smix of the nanoparticle
Args:
orderings: The ordering of atoms within the NP; ordering key is based on Metals in alphabetical order
Returns:
entropy of mixing (smix)
"""
x_i = np.bincount(orderings) / len(orderings)
# drop 0s to avoid errors
x_i = x_i[x_i != 0]
kb = ase.units.kB
smix = -kb * sum(x_i * np.log(x_i))
return smix
def calc_gmix(self, orderings: np.ndarray, T: float = 298.15) -> float:
"""
gmix (eV / atom) = self.ee - T * self.calc_smix(ordering)
Args:
T: Temperature of the system in Kelvin; Defaults at room temp of 25 C
orderings: The ordering of atoms within the NP; ordering key is based on Metals in alphabetical order
Returns:
free energy of mixing (gmix)
"""
return self.calc_ee(orderings) - T * self.calc_smix(orderings)
def metropolis(self, ordering: np.ndarray, num_steps: int = 1000) -> None:
"""
Metropolis-Hastings-based exploration of similar NPs
Args:
ordering: 1D chemical ordering array
num_steps: How many steps to simulate for
"""
# Initialization
# create new instance of ordering array
ordering = ordering.copy()
best_ordering = ordering.copy()
best_energy = self.calc_ce(ordering)
prev_energy = best_energy
energy_history = np.zeros(num_steps)
energy_history[0] = best_energy
ordering_indices = np.arange(len(ordering))
for step in range(1, num_steps):
prev_ordering = ordering.copy()
i, j = np.random.choice(ordering_indices, 2, replace=False)
ordering[i], ordering[j] = ordering[j], ordering[i]
# Evaluate the energy change
energy = self.calc_ce(ordering)
# Metropolis-related stuff
ratio = energy / prev_energy
if ratio > np.random.uniform():
# Commit to the step
energy_history[step] = energy
if energy < best_energy:
best_energy = energy
best_ordering = ordering.copy()
else:
# Reject the step
ordering = prev_ordering.copy()
energy_history[step] = prev_energy
return best_ordering, best_energy, energy_history
@functools.cached_property
def num_shells(self) -> int:
"""
Return number of shells in NP
Use calc_shell_map if user did not define num_shells
"""
return max(self.shell_map)
@functools.cached_property
def shell_map(self) -> Dict[int, Iterable[int]]:
"""
Map of shell number and atom indices in shell
0: core atom(s)
1: shell (layer) 1 over core atom(s)
etc.
Returns:
shell_map: dict of shell number and array of atom indices in shell
"""
remaining_atoms = set(range(len(self.atoms)))
shell_map = {}
cur_shell = 0
srf = np.where(self.cn < 12)[0]
shell_map[cur_shell] = srf
remaining_atoms -= set(srf)
coord_dict = {i: set(self.bond_list[self.bond_list[:, 0] == i].ravel())
for i in remaining_atoms}
while remaining_atoms:
cur_shell -= 1
shell = [i for i in remaining_atoms
if coord_dict[i] - remaining_atoms]
shell_map[cur_shell] = np.array(shell)
remaining_atoms -= set(shell)
shell_map = {k - cur_shell: v for k, v in shell_map.items()}
return shell_map
def get_info(self):
"""
Prints out and returns the information stored in the bcm object on how the model
was parameterized. This can be any info that may be relevant but some good info to store
are:
1. What method was used to calculate the Gamma values (e.g. NP or Dimer method)
2. Other info on how the gamma values were calculated (were energies from DFT (if so then what functional was used), experimental or approximated)
3. Information on the CE_Bulk value being used
Returns:
Info [dict]: Original info dictionary used to initialize the bcm instance
"""
for key in self.info:
print(f'{key}: {self.info[key]}\n')
return self.info
def _get_bcm_params(self) -> None:
"""
Creates gamma and ce_bulk dictionaries which are then used
to created precomputed values for the BCM calculation
Sets:
gamma: Weighting factors of the computed elements within the BCM
ce_bulk: Bulk Cohesive energy values
"""
gammas = {}
ce_bulk = {}
for item in itertools.combinations_with_replacement(self.metal_types, 2):
# Casting metals and setting keys for dictionary
metal_1, metal_2 = item
gamma_obj = GammaValues(metal_1, metal_2)
# using Update function to create clean Gamma an bulk dictionaries
gammas = recursive_update(gammas, gamma_obj.gamma)
# add ce_bulk vals
ce_bulk[gamma_obj.element_a] = gamma_obj.ce_a
ce_bulk[gamma_obj.element_b] = gamma_obj.ce_b
self.ce_bulk = ce_bulk
self.gammas = gammas
def _get_precomps(self) -> None:
"""
Uses the Gamma and ce_bulk dictionaries to create a precomputed
BCM matrix of gammas and ce_bulk values
[precomps] = [gamma of element 1] * [ce_bulk of element 1 to element 2]
Sets:
precomps: Precomp Matrix
"""
# precompute values for BCM calc
n_met = len(self.metal_types)
precomps = np.ones((n_met, n_met))
for i in range(n_met):
for j in range(n_met):
M1 = self.metal_types[i]
M2 = self.metal_types[j]
precomp_bulk = self.ce_bulk[M1]
precomp_gamma = self.gammas[M1][M2]
precomps[i, j] = precomp_gamma * precomp_bulk
self.precomps = precomps
self.cn_precomps = np.sqrt(self.cn * 12)[self.a1]
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
Micoin/contrib/gitian-build.py
|
#!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
def setup():
global args, workdir
programs = ['ruby', 'git', 'apt-cacher-ng', 'make', 'wget']
if args.kvm:
programs += ['python-vm-builder', 'qemu-kvm', 'qemu-utils']
elif args.docker:
dockers = ['docker.io', 'docker-ce']
for i in dockers:
return_code = subprocess.call(['sudo', 'apt-get', 'install', '-qq', i])
if return_code == 0:
break
if return_code != 0:
print('Cannot find any way to install docker', file=sys.stderr)
exit(1)
else:
programs += ['lxc', 'debootstrap']
subprocess.check_call(['sudo', 'apt-get', 'install', '-qq'] + programs)
if not os.path.isdir('gitian.sigs.ltc'):
subprocess.check_call(['git', 'clone', 'https://github.com/micoin-project/gitian.sigs.ltc.git'])
if not os.path.isdir('micoin-detached-sigs'):
subprocess.check_call(['git', 'clone', 'https://github.com/micoin-project/micoin-detached-sigs.git'])
if not os.path.isdir('gitian-builder'):
subprocess.check_call(['git', 'clone', 'https://github.com/devrandom/gitian-builder.git'])
if not os.path.isdir('micoin'):
subprocess.check_call(['git', 'clone', 'https://github.com/micoin-project/micoin.git'])
os.chdir('gitian-builder')
make_image_prog = ['bin/make-base-vm', '--suite', 'bionic', '--arch', 'amd64']
if args.docker:
make_image_prog += ['--docker']
elif not args.kvm:
make_image_prog += ['--lxc']
subprocess.check_call(make_image_prog)
os.chdir(workdir)
if args.is_bionic and not args.kvm and not args.docker:
subprocess.check_call(['sudo', 'sed', '-i', 's/lxcbr0/br0/', '/etc/default/lxc-net'])
print('Reboot is required')
exit(0)
def build():
global args, workdir
os.makedirs('micoin-binaries/' + args.version, exist_ok=True)
print('\nBuilding Dependencies\n')
os.chdir('gitian-builder')
os.makedirs('inputs', exist_ok=True)
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz'])
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch'])
subprocess.check_call(["echo 'a8c4e9cafba922f89de0df1f2152e7be286aba73f78505169bc351a7938dd911 inputs/osslsigncode-Backports-to-1.7.1.patch' | sha256sum -c"], shell=True)
subprocess.check_call(["echo 'f9a8cdb38b9c309326764ebc937cba1523a3a751a7ab05df3ecc99d18ae466c9 inputs/osslsigncode-1.7.1.tar.gz' | sha256sum -c"], shell=True)
subprocess.check_call(['make', '-C', '../micoin/depends', 'download', 'SOURCES_PATH=' + os.getcwd() + '/cache/common'])
if args.linux:
print('\nCompiling ' + args.version + ' Linux')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'micoin='+args.commit, '--url', 'micoin='+args.url, '../micoin/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-linux', '--destination', '../gitian.sigs.ltc/', '../micoin/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call('mv build/out/micoin-*.tar.gz build/out/src/micoin-*.tar.gz ../micoin-binaries/'+args.version, shell=True)
if args.windows:
print('\nCompiling ' + args.version + ' Windows')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'micoin='+args.commit, '--url', 'micoin='+args.url, '../micoin/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-unsigned', '--destination', '../gitian.sigs.ltc/', '../micoin/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call('mv build/out/micoin-*-win-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/micoin-*.zip build/out/micoin-*.exe ../micoin-binaries/'+args.version, shell=True)
if args.macos:
print('\nCompiling ' + args.version + ' MacOS')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'micoin='+args.commit, '--url', 'micoin='+args.url, '../micoin/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-unsigned', '--destination', '../gitian.sigs.ltc/', '../micoin/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call('mv build/out/micoin-*-osx-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/micoin-*.tar.gz build/out/micoin-*.dmg ../micoin-binaries/'+args.version, shell=True)
os.chdir(workdir)
if args.commit_files:
print('\nCommitting '+args.version+' Unsigned Sigs\n')
os.chdir('gitian.sigs.ltc')
subprocess.check_call(['git', 'add', args.version+'-linux/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-win-unsigned/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-osx-unsigned/'+args.signer])
subprocess.check_call(['git', 'commit', '-m', 'Add '+args.version+' unsigned sigs for '+args.signer])
os.chdir(workdir)
def sign():
global args, workdir
os.chdir('gitian-builder')
if args.windows:
print('\nSigning ' + args.version + ' Windows')
subprocess.check_call('cp inputs/micoin-' + args.version + '-win-unsigned.tar.gz inputs/micoin-win-unsigned.tar.gz', shell=True)
subprocess.check_call(['bin/gbuild', '-i', '--commit', 'signature='+args.commit, '../micoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-signed', '--destination', '../gitian.sigs.ltc/', '../micoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
subprocess.check_call('mv build/out/micoin-*win64-setup.exe ../micoin-binaries/'+args.version, shell=True)
subprocess.check_call('mv build/out/micoin-*win32-setup.exe ../micoin-binaries/'+args.version, shell=True)
if args.macos:
print('\nSigning ' + args.version + ' MacOS')
subprocess.check_call('cp inputs/micoin-' + args.version + '-osx-unsigned.tar.gz inputs/micoin-osx-unsigned.tar.gz', shell=True)
subprocess.check_call(['bin/gbuild', '-i', '--commit', 'signature='+args.commit, '../micoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-signed', '--destination', '../gitian.sigs.ltc/', '../micoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call('mv build/out/micoin-osx-signed.dmg ../micoin-binaries/'+args.version+'/micoin-'+args.version+'-osx.dmg', shell=True)
os.chdir(workdir)
if args.commit_files:
print('\nCommitting '+args.version+' Signed Sigs\n')
os.chdir('gitian.sigs.ltc')
subprocess.check_call(['git', 'add', args.version+'-win-signed/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-osx-signed/'+args.signer])
subprocess.check_call(['git', 'commit', '-a', '-m', 'Add '+args.version+' signed binary sigs for '+args.signer])
os.chdir(workdir)
def verify():
global args, workdir
os.chdir('gitian-builder')
print('\nVerifying v'+args.version+' Linux\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-linux', '../micoin/contrib/gitian-descriptors/gitian-linux.yml'])
print('\nVerifying v'+args.version+' Windows\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-win-unsigned', '../micoin/contrib/gitian-descriptors/gitian-win.yml'])
print('\nVerifying v'+args.version+' MacOS\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-osx-unsigned', '../micoin/contrib/gitian-descriptors/gitian-osx.yml'])
print('\nVerifying v'+args.version+' Signed Windows\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-win-signed', '../micoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
print('\nVerifying v'+args.version+' Signed MacOS\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-osx-signed', '../micoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
os.chdir(workdir)
def main():
global args, workdir
parser = argparse.ArgumentParser(usage='%(prog)s [options] signer version')
parser.add_argument('-c', '--commit', action='store_true', dest='commit', help='Indicate that the version argument is for a commit or branch')
parser.add_argument('-p', '--pull', action='store_true', dest='pull', help='Indicate that the version argument is the number of a github repository pull request')
parser.add_argument('-u', '--url', dest='url', default='https://github.com/micoin-project/micoin', help='Specify the URL of the repository. Default is %(default)s')
parser.add_argument('-v', '--verify', action='store_true', dest='verify', help='Verify the Gitian build')
parser.add_argument('-b', '--build', action='store_true', dest='build', help='Do a Gitian build')
parser.add_argument('-s', '--sign', action='store_true', dest='sign', help='Make signed binaries for Windows and MacOS')
parser.add_argument('-B', '--buildsign', action='store_true', dest='buildsign', help='Build both signed and unsigned binaries')
parser.add_argument('-o', '--os', dest='os', default='lwm', help='Specify which Operating Systems the build is for. Default is %(default)s. l for Linux, w for Windows, m for MacOS')
parser.add_argument('-j', '--jobs', dest='jobs', default='2', help='Number of processes to use. Default %(default)s')
parser.add_argument('-m', '--memory', dest='memory', default='2000', help='Memory to allocate in MiB. Default %(default)s')
parser.add_argument('-k', '--kvm', action='store_true', dest='kvm', help='Use KVM instead of LXC')
parser.add_argument('-d', '--docker', action='store_true', dest='docker', help='Use Docker instead of LXC')
parser.add_argument('-S', '--setup', action='store_true', dest='setup', help='Set up the Gitian building environment. Uses LXC. If you want to use KVM, use the --kvm option. Only works on Debian-based systems (Ubuntu, Debian)')
parser.add_argument('-D', '--detach-sign', action='store_true', dest='detach_sign', help='Create the assert file for detached signing. Will not commit anything.')
parser.add_argument('-n', '--no-commit', action='store_false', dest='commit_files', help='Do not commit anything to git')
parser.add_argument('signer', help='GPG signer to sign each build assert file')
parser.add_argument('version', help='Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified')
args = parser.parse_args()
workdir = os.getcwd()
args.linux = 'l' in args.os
args.windows = 'w' in args.os
args.macos = 'm' in args.os
args.is_bionic = b'bionic' in subprocess.check_output(['lsb_release', '-cs'])
if args.buildsign:
args.build=True
args.sign=True
if args.kvm and args.docker:
raise Exception('Error: cannot have both kvm and docker')
args.sign_prog = 'true' if args.detach_sign else 'gpg --detach-sign'
# Set environment variable USE_LXC or USE_DOCKER, let gitian-builder know that we use lxc or docker
if args.docker:
os.environ['USE_DOCKER'] = '1'
elif not args.kvm:
os.environ['USE_LXC'] = '1'
if not 'GITIAN_HOST_IP' in os.environ.keys():
os.environ['GITIAN_HOST_IP'] = '10.0.3.1'
if not 'LXC_GUEST_IP' in os.environ.keys():
os.environ['LXC_GUEST_IP'] = '10.0.3.5'
# Disable for MacOS if no SDK found
if args.macos and not os.path.isfile('gitian-builder/inputs/MacOSX10.11.sdk.tar.gz'):
print('Cannot build for MacOS, SDK does not exist. Will build for other OSes')
args.macos = False
script_name = os.path.basename(sys.argv[0])
# Signer and version shouldn't be empty
if args.signer == '':
print(script_name+': Missing signer.')
print('Try '+script_name+' --help for more information')
exit(1)
if args.version == '':
print(script_name+': Missing version.')
print('Try '+script_name+' --help for more information')
exit(1)
# Add leading 'v' for tags
if args.commit and args.pull:
raise Exception('Cannot have both commit and pull')
args.commit = ('' if args.commit else 'v') + args.version
if args.setup:
setup()
os.chdir('micoin')
if args.pull:
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
os.chdir('../gitian-builder/inputs/micoin')
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
args.commit = subprocess.check_output(['git', 'show', '-s', '--format=%H', 'FETCH_HEAD'], universal_newlines=True, encoding='utf8').strip()
args.version = 'pull-' + args.version
print(args.commit)
subprocess.check_call(['git', 'fetch'])
subprocess.check_call(['git', 'checkout', args.commit])
os.chdir(workdir)
if args.build:
build()
if args.sign:
sign()
if args.verify:
verify()
if __name__ == '__main__':
main()
|
[] |
[] |
[
"USE_DOCKER",
"GITIAN_HOST_IP",
"USE_LXC",
"LXC_GUEST_IP"
] |
[]
|
["USE_DOCKER", "GITIAN_HOST_IP", "USE_LXC", "LXC_GUEST_IP"]
|
python
| 4 | 0 | |
hackerrank/test/mercari/03_counting_pairs/main.go
|
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
/*
* Complete the 'countPairs' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER_ARRAY numbers
* 2. INTEGER k
*/
func countPairs(numbers []int32, k int32) int32 {
dict := make(map[int32]bool)
for _, v := range numbers {
dict[v] = true
}
var res int32
for key := range dict {
if dict[key+k] {
res++
}
}
return res
}
//func countPairs(numbers []int32, k int32) int32 {
// results := make(map[int]bool)
// var res int32
// nums := make([]int, len(numbers))
// for i, v := range numbers {
// nums [i] = int(v)
// }
// sort.Ints(nums)
// for i := 0; i < len(nums); i++ {
// l := nums[i]
// for j := i + 1; j < len(nums); j++ {
// if l+int(k) == nums[j] {
// if !results[l] {
// results[l] = true
// res++
// }
// }
// }
// }
// return res
//}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 16*1024*1024)
numbersCount, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
var numbers []int32
for i := 0; i < int(numbersCount); i++ {
numbersItemTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
numbersItem := int32(numbersItemTemp)
numbers = append(numbers, numbersItem)
}
kTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
k := int32(kTemp)
result := countPairs(numbers, k)
fmt.Fprintf(writer, "%d\n", result)
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
|
[
"\"OUTPUT_PATH\""
] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
go
| 1 | 0 | |
drivers/dns/src/main/java/uniresolver/driver/dns/DnsDriver.java
|
package uniresolver.driver.dns;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.Type;
import org.xbill.DNS.URIRecord;
import uniresolver.ResolutionException;
import uniresolver.driver.Driver;
import uniresolver.result.ResolveResult;
public class DnsDriver implements Driver {
private static Logger log = LoggerFactory.getLogger(DnsDriver.class);
public static final Pattern DNS_PATTERN = Pattern.compile("^((?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9]))$");
private Map<String, Object> properties;
private String dnsServers;
private Resolver resolver = null;
public DnsDriver(Map<String, Object> properties) {
this.setProperties(properties);
}
public DnsDriver() {
this.setProperties(getPropertiesFromEnvironment());
}
private static Map<String, Object> getPropertiesFromEnvironment() {
if (log.isDebugEnabled()) log.debug("Loading from environment: " + System.getenv());
Map<String, Object> properties = new HashMap<String, Object> ();
try {
String env_dnsServers = System.getenv("uniresolver_driver_dns_dnsServers");
if (env_dnsServers != null) properties.put("dnsServers", env_dnsServers);
} catch (Exception ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
return properties;
}
private void configureFromProperties() {
if (log.isDebugEnabled()) log.debug("Configuring from properties: " + this.getProperties());
try {
String prop_dnsServers = (String) this.getProperties().get("dnsServers");
if (prop_dnsServers != null) this.setDnsServers(prop_dnsServers);
} catch (Exception ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
@Override
public ResolveResult resolve(String identifier) throws ResolutionException {
// open pool
if (this.getResolver() == null) this.openResolver();
// parse identifier
Matcher matcher = DNS_PATTERN.matcher(identifier);
if (! matcher.matches()) return null;
// DNS lookup
Lookup lookup = null;
Record[] records;
try {
lookup = new Lookup("_did." + identifier, Type.URI);
lookup.setResolver(this.getResolver());
records = lookup.run();
} catch (Exception ex) {
throw new ResolutionException("DNS resolution problem: " + ex.getMessage() + (lookup != null ? (" (" + lookup.getErrorString() + ")") : ""));
}
if (lookup.getErrorString() != null && ! "successful".equals(lookup.getErrorString())) {
if (log.isDebugEnabled()) log.debug("For identifier " + identifier + " got error: " + lookup.getErrorString());
throw new ResolutionException("DNS resolution error: " + lookup.getErrorString());
}
if (records == null) return null;
for (int i=0; i<records.length; i++) {
URIRecord uri = (URIRecord) records[i];
if (log.isDebugEnabled()) log.debug("For identifier " + identifier + " found entry " + uri.getTarget() + " with preference " + uri.getPriority());
}
String did = records.length > 0 ? ((URIRecord) records[0]).getTarget() : null;
Integer priority = records.length > 0 ? Integer.valueOf(((URIRecord) records[0]).getPriority()) : null;
// create METHOD METADATA
Map<String, Object> methodMetadata = new LinkedHashMap<String, Object> ();
if (did != null) methodMetadata.put("redirect", did);
if (priority != null) methodMetadata.put("priority", priority);
// create RESOLVE RESULT
ResolveResult resolveResult = ResolveResult.build(did, null, null, methodMetadata);
// done
return resolveResult;
}
@Override
public Map<String, Object> properties() {
return this.getProperties();
}
private void openResolver() throws ResolutionException {
// create resolver
try {
if (this.getDnsServers() != null && ! this.getDnsServers().trim().isEmpty()) {
String[] dnsServers = this.getDnsServers().split(";");
this.resolver = new ExtendedResolver(dnsServers);
if (log.isInfoEnabled()) log.info("Created DNS resolver with servers " + Arrays.asList(dnsServers) + ".");
} else {
this.resolver = new ExtendedResolver();
if (log.isInfoEnabled()) log.info("Created default DNS resolver.");
}
} catch (UnknownHostException ex) {
throw new ResolutionException("Unable to create DNS resolver: " + ex.getMessage(), ex);
}
}
/*
* Getters and setters
*/
public Map<String, Object> getProperties() {
return this.properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
this.configureFromProperties();
}
public String getDnsServers() {
return this.dnsServers;
}
public void setDnsServers(String dnsServers) {
this.dnsServers = dnsServers;
}
public Resolver getResolver() {
return this.resolver;
}
public void setResolver(Resolver resolver) {
this.resolver = resolver;
}
}
|
[
"\"uniresolver_driver_dns_dnsServers\""
] |
[] |
[
"uniresolver_driver_dns_dnsServers"
] |
[]
|
["uniresolver_driver_dns_dnsServers"]
|
java
| 1 | 0 | |
vendor/github.com/Cray-HPE/hms-trs-app-api/pkg/trs_http_api/trshttp_remote.go
|
// MIT License
//
// (C) Copyright [2020-2021] Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package trs_http_api
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/Shopify/sarama"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"os"
"github.com/Cray-HPE/hms-base"
tkafka "github.com/Cray-HPE/hms-trs-kafkalib/pkg/trs-kafkalib"
"strings"
"time"
)
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// R E M O T E I N T E R F A C E
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Initialize a remote HTTP task system. NOTE: if multiple instances of
// an HTTP interface are to be used at the same time, then one of ServiceName,
// or sender must be unique to each instance.
//
// ServiceName: Name of running service/application.
// logger: logger instance the library should use.
// Return: Error string if something went wrong.
func (tloc *TRSHTTPRemote) Init(serviceName string, logger *logrus.Logger) error {
if logger != nil {
tloc.Logger = logger
} else {
tloc.Logger = logrus.New()
}
tloc.svcName = strings.ToLower(serviceName)
tloc.brokerSpec = "kafka:9092"
envstr := os.Getenv("BROKER_SPEC")
if envstr != "" {
tloc.brokerSpec = envstr
} else {
tloc.Logger.Warningf("env var: BROKER_SPEC is not set; falling back to: %s", tloc.brokerSpec)
}
tloc.Logger.Infof("BROKER_SPEC: %s", tloc.brokerSpec)
tloc.ctx, tloc.ctxCancelFunc = context.WithCancel(context.Background())
if tloc.taskMap == nil {
tloc.taskMutex.Lock()
tloc.taskMap = make(map[uuid.UUID]*taskChannelTuple)
tloc.taskMutex.Unlock()
}
tloc.kafkaRspChan = make(chan *sarama.ConsumerMessage)
tloc.KafkaInstance = &tkafka.TRSKafka{}
//tkafka.DebugLevel(5)
//This makes the send topic / return topic global for the instance of the TRSHTTPRemote obj.
var tmpRecTop string
tloc.sendTopic, tmpRecTop, tloc.consumerGroup = tkafka.GenerateSendReceiveConsumerGroupName(tloc.svcName, "http-v1", "")
tloc.receiveTopics = append(tloc.receiveTopics, tmpRecTop)
tloc.Logger.Tracef("SEND: %s, RECEIVE: %s, ConsumerGroup: %s", tloc.sendTopic, tloc.receiveTopics, tloc.consumerGroup)
kafkaLogger := logrus.New()
err := tloc.KafkaInstance.Init(tloc.ctx, tloc.receiveTopics, tloc.consumerGroup, tloc.brokerSpec, tloc.kafkaRspChan, kafkaLogger)
if err != nil {
tloc.Logger.Error(err)
}
go func() {
var tData HttpKafkaRx
for {
select {
//This was a MAJOR PAIN!!! : https://stackoverflow.com/questions/3398490/checking-if-a-channel-has-a-ready-to-read-value-using-go
case raw, ok := <-tloc.kafkaRspChan:
if ok {
tloc.Logger.Debugf("RECEIVED: '%s'\n", string(raw.Value))
//unmarshal, then look up task tuple, put into it's chan
err := json.Unmarshal(raw.Value, &tData)
if err != nil {
tloc.Logger.Printf("ERROR unmarshaling received data: %v\n", err)
continue
}
taskMapEntry, ok := tloc.taskMap[tData.ID]
if !ok {
tloc.Logger.Printf("ERROR, can't find task map entry for msgID %d\n",
tData.ID)
break
}
resp := tData.Response.ToHttpResponse()
tloc.taskMutex.Lock()
tloc.taskMap[tData.ID].task.Request.Response = &resp
tloc.taskMap[tData.ID].task.Err = tData.Err
tloc.taskMutex.Unlock()
taskMapEntry.taskListChannel <- taskMapEntry.task
} else {
tloc.Logger.Info("Kafka Response Channel closed! Exiting Go Routine")
return
}
}
}
}()
return err
}
// Set up security paramters. This is a place holder for now.
func (tloc *TRSHTTPRemote) SetSecurity(inParams interface{}) error {
return nil
}
// Create an array of task descriptors. Copy data from the source task
// into each element of the returned array. Per-task data has to be
// populated separately by the caller.
//
// The message ID in each task is populated regardless of the value in
// the source. It is generated using a pseudo-random value in the upper
// 32 bits, which is the message group ID, followed by a monotonically
// increasing value in the lower 32 bits, starting with 0, which functions
// as the message ID.
//
// source: Ptr to a task descriptor populated with relevant data.
// numTasks: Number of elements in the returned array.
// Return: Array of populated task descriptors.
func (tloc *TRSHTTPRemote) CreateTaskList(source *HttpTask, numTasks int) []HttpTask {
return createHTTPTaskArray(source, numTasks)
}
// Launch an array of tasks. This is non-blocking. Use Check() to get
// current status of the task launch.
//
// taskList: Ptr to a list of HTTP tasks to launch.
// Return: Chan of *HttpTxTask, sized by task list, which caller can
// use to get notified of each task completion, or safely
// ignore. CALLER MUST CLOSE.
// Error message if something went wrong with the launch.
func (tloc *TRSHTTPRemote) Launch(taskList *[]HttpTask) (chan *HttpTask, error) {
var retErr error
stockError := errors.New("error encountered while processing, check tasks for error ")
if len(*taskList) == 0 {
emptyChannel := make(chan *HttpTask, 1)
err := fmt.Errorf("empty task list, nothing to do")
return emptyChannel, err
}
taskListChannel := make(chan *HttpTask, len(*taskList))
for ii := 0; ii < len(*taskList); ii++ {
if (*taskList)[ii].Ignore == true {
continue
}
//Always set the response to nil; make sure its clean, add
//user-agent header
if (*taskList)[ii].Request != nil {
base.SetHTTPUserAgent((*taskList)[ii].Request,tloc.svcName)
(*taskList)[ii].Request.Response = nil
}
//make sure the id is set
if (*taskList)[ii].id == uuid.Nil {
(*taskList)[ii].id = uuid.New()
}
//make sure the service name is set
if (*taskList)[ii].ServiceName == "" {
(*taskList)[ii].ServiceName = tloc.svcName
}
//make sure the timestamp is set
if (*taskList)[ii].TimeStamp == "" {
(*taskList)[ii].TimeStamp = time.Now().Format(time.RFC3339Nano)
}
tct := taskChannelTuple{
taskListChannel: taskListChannel,
task: &(*taskList)[ii],
}
tloc.taskMutex.Lock()
tloc.taskMap[(*taskList)[ii].id ] = &tct
tloc.taskMutex.Unlock()
kdata := (*taskList)[ii].ToHttpKafkaTx()
jdata, jerr := json.Marshal(kdata)
if jerr != nil {
retErr = stockError
tct.task.Err = &jerr
}
if valid, err := tct.task.Validate(); !valid {
retErr = stockError
tct.task.Err = &err
}
if tct.task.Err != nil {
go SendDelayedError(tct, tloc.Logger)
} else {
tloc.KafkaInstance.Write(tloc.sendTopic, jdata)
}
}
return taskListChannel, retErr
}
// Check on the status of the most recently launched task list.
//
// taskList: Ptr to a recently launched task list.
// Return: Task list still running: true/false
// Error message, if any, associated with the task run.
func (tloc *TRSHTTPRemote) Check(taskList *[]HttpTask) (bool, error) {
for _, v := range *taskList {
if v.Ignore == false {
if v.Request.Response == nil && v.Err == nil {
return true, nil
}
}
}
return false, nil
}
// Check the health of the remote HTTP task launch system.
//
// Return: Alive and operational -- true/false
// Error message associated with non-alive/functional state
func (tloc *TRSHTTPRemote) Alive() (bool, error) {
if tloc.KafkaInstance.Client == nil {
return false, errors.New("Kafka client is nil")
}
if tloc.taskMap == nil {
return false, errors.New("taskMap is nil")
}
return true, nil
}
// Cancel a currently-running task set. Note that this won't (yet) kill
// the individual in-flight tasks, but just kills the overall operation.
// Thus, for tasks with no time-out which are hung, it could result in
// a resource leak. But this can be used to at least wrestle control
// over a task set.
//
// taskList: Ptr to a list of HTTP tasks to launch.
func (tloc *TRSHTTPRemote) Cancel(taskList *[]HttpTask) {
//TODO Mk3 -> send a messaage via Kafka to CANCEL a running task
}
// Close out a task list transaction. The frees up a small amount of resources
// so it should not be skipped.
//
// taskList: Ptr to a recently launched task list.
func (tloc *TRSHTTPRemote) Close(taskList *[]HttpTask) {
for _, v := range *taskList {
tloc.taskMutex.Lock()
delete(tloc.taskMap, v.id)
tloc.taskMutex.Unlock()
}
}
// Clean up a Remote HTTP task system.
func (tloc *TRSHTTPRemote) Cleanup() {
//statement order is important! NO CHANGE
tloc.KafkaInstance.Shutdown()
tloc.ctxCancelFunc()
close(tloc.kafkaRspChan)
//statement order is important! NO CHANGE
}
|
[
"\"BROKER_SPEC\""
] |
[] |
[
"BROKER_SPEC"
] |
[]
|
["BROKER_SPEC"]
|
go
| 1 | 0 | |
zero/cli.py
|
from datetime import datetime
import logging
import os
import subprocess
import sys
from argparse import Namespace
logging.getLogger("transformers").setLevel(logging.WARNING)
import click
import torch
from luke.utils.model_utils import ModelArchive
from zero.utils.experiment_logger import commet_logger_args, CometLogger, NullLogger
LOG_FORMAT = "[%(asctime)s] [%(levelname)s] %(message)s (%(funcName)s@%(filename)s:%(lineno)s)"
try:
import absl.logging
# https://github.com/tensorflow/tensorflow/issues/27045#issuecomment-519642980
logging.getLogger().removeHandler(absl.logging._absl_handler)
absl.logging._warn_preinit_stderr = False
except ImportError:
pass
logger = logging.getLogger(__name__)
@click.group()
@click.option(
"--output-dir", default="models", type=click.Path()
)
@click.option("--num-gpus", default=1)
@click.option("--experiment-logger", "--logger", type=click.Choice(["comet"]))
@click.option("--master-port", default=29500)
@click.option("--local-rank", "--local_rank", default=-1)
@click.option("--model-file", type=click.Path(exists=True))
@click.option("--device-id", type=int)
@commet_logger_args
@click.pass_context
def cli(ctx, **kwargs):
args = Namespace(**kwargs)
if args.local_rank == -1 and args.num_gpus > 1:
current_env = os.environ.copy()
current_env["MASTER_ADDR"] = "127.0.0.1"
current_env["MASTER_PORT"] = str(args.master_port)
current_env["WORLD_SIZE"] = str(args.num_gpus)
processes = []
for args.local_rank in range(0, args.num_gpus):
current_env["RANK"] = str(args.local_rank)
current_env["LOCAL_RANK"] = str(args.local_rank)
cmd = [sys.executable, "-u", "-m", "examples.cli", "--local-rank={}".format(args.local_rank)]
cmd.extend(sys.argv[1:])
process = subprocess.Popen(cmd, env=current_env)
processes.append(process)
for process in processes:
process.wait()
if process.returncode != 0:
raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
sys.exit(0)
else:
if args.local_rank not in (-1, 0):
logging.basicConfig(format=LOG_FORMAT, level=logging.WARNING)
else:
logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
logger.info("Output dir: %s", args.output_dir)
# NOTE: ctx.obj is documented here: http://click.palletsprojects.com/en/7.x/api/#click.Context.obj
ctx.obj = dict(local_rank=args.local_rank, output_dir=args.output_dir)
if args.num_gpus == 0:
ctx.obj["device"] = torch.device("cpu")
elif args.local_rank == -1:
ctx.obj["device"] = torch.device("cuda:{}".format(args.device_id))
else:
torch.cuda.set_device(args.local_rank)
ctx.obj["device"] = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
experiment_logger = NullLogger()
if args.local_rank in (-1, 0) and args.experiment_logger == "comet":
experiment_logger = CometLogger(args)
experiment_logger.log_parameters({p.name: getattr(args, p.name) for p in cli.params})
ctx.obj["experiment"] = experiment_logger
if args.model_file:
model_archive = ModelArchive.load(args.model_file)
ctx.obj["tokenizer"] = model_archive.tokenizer
ctx.obj["entity_vocab"] = model_archive.entity_vocab
ctx.obj["bert_model_name"] = model_archive.bert_model_name
ctx.obj["model_config"] = model_archive.config
ctx.obj["max_mention_length"] = model_archive.max_mention_length
ctx.obj["model_weights"] = model_archive.state_dict
experiment_logger.log_parameter("model_file_name", os.path.basename(args.model_file))
from zero.ner.main import cli as ner_cli
cli.add_command(ner_cli)
if __name__ == "__main__":
cli()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
dm/relay/relay_test.go
|
// Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package relay
import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/BurntSushi/toml"
"github.com/DATA-DOG/go-sqlmock"
gmysql "github.com/go-mysql-org/go-mysql/mysql"
"github.com/go-mysql-org/go-mysql/replication"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tiflow/dm/dm/config"
"github.com/pingcap/tiflow/dm/pkg/binlog/event"
"github.com/pingcap/tiflow/dm/pkg/conn"
"github.com/pingcap/tiflow/dm/pkg/gtid"
"github.com/pingcap/tiflow/dm/pkg/utils"
)
var _ = Suite(&testRelaySuite{})
func TestSuite(t *testing.T) {
TestingT(t)
}
type testRelaySuite struct{}
func newRelayCfg(c *C, flavor string) *Config {
dbCfg := getDBConfigForTest()
return &Config{
EnableGTID: false, // position mode, so auto-positioning can work
Flavor: flavor,
RelayDir: c.MkDir(),
ServerID: 12321,
From: config.DBConfig{
Host: dbCfg.Host,
Port: dbCfg.Port,
User: dbCfg.User,
Password: dbCfg.Password,
},
ReaderRetry: ReaderRetryConfig{
BackoffRollback: 200 * time.Millisecond,
BackoffMax: 1 * time.Second,
BackoffMin: 1 * time.Millisecond,
BackoffJitter: true,
BackoffFactor: 2,
},
}
}
func getDBConfigForTest() *config.DBConfig {
host := os.Getenv("MYSQL_HOST")
if host == "" {
host = "127.0.0.1"
}
port, _ := strconv.Atoi(os.Getenv("MYSQL_PORT"))
if port == 0 {
port = 3306
}
user := os.Getenv("MYSQL_USER")
if user == "" {
user = "root"
}
password := os.Getenv("MYSQL_PSWD")
return &config.DBConfig{
Host: host,
Port: port,
User: user,
Password: password,
}
}
// mockReader is used only for relay testing.
type mockReader struct {
result RResult
err error
}
func (r *mockReader) Start() error {
return nil
}
func (r *mockReader) Close() error {
return nil
}
func (r *mockReader) GetEvent(ctx context.Context) (RResult, error) {
select {
case <-ctx.Done():
return RResult{}, ctx.Err()
default:
}
return r.result, r.err
}
// mockWriter is used only for relay testing.
type mockWriter struct {
result WResult
err error
latestEvent *replication.BinlogEvent
}
func (w *mockWriter) IsActive(uuid, filename string) (bool, int64) {
return false, 0
}
func (w *mockWriter) Close() error {
return nil
}
func (w *mockWriter) Init(relayDir, filename string) {
}
func (w *mockWriter) WriteEvent(ev *replication.BinlogEvent) (WResult, error) {
w.latestEvent = ev // hold it
return w.result, w.err
}
func (w *mockWriter) Flush() error {
return nil
}
func (t *testRelaySuite) TestTryRecoverLatestFile(c *C) {
var (
uuid = "24ecd093-8cec-11e9-aa0d-0242ac170002"
uuidWithSuffix = fmt.Sprintf("%s.000001", uuid)
previousGTIDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-14,53bfca22-690d-11e7-8a62-18ded7a37b78:1-495,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456"
latestGTIDStr1 = "3ccc475b-2343-11e7-be21-6c0b84d59f30:14"
latestGTIDStr2 = "53bfca22-690d-11e7-8a62-18ded7a37b78:495"
recoverGTIDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-17,53bfca22-690d-11e7-8a62-18ded7a37b78:1-505,406a3f61-690d-11e7-87c5-6c92bf46f384:1-456" // 406a3f61-690d-11e7-87c5-6c92bf46f384:123-456 --> 406a3f61-690d-11e7-87c5-6c92bf46f384:1-456
greaterGITDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-20,53bfca22-690d-11e7-8a62-18ded7a37b78:1-510,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456"
filename = "mysql-bin.000001"
startPos = gmysql.Position{Name: filename, Pos: 123}
parser2 = parser.New()
relayCfg = newRelayCfg(c, gmysql.MySQLFlavor)
r = NewRelay(relayCfg).(*Relay)
)
c.Assert(failpoint.Enable("github.com/pingcap/tiflow/dm/pkg/utils/GetGTIDPurged", `return("406a3f61-690d-11e7-87c5-6c92bf46f384:1-122")`), IsNil)
//nolint:errcheck
defer failpoint.Disable("github.com/pingcap/tiflow/dm/pkg/utils/GetGTIDPurged")
cfg := getDBConfigForTest()
conn.InitMockDB(c)
db, err := conn.DefaultDBProvider.Apply(cfg)
c.Assert(err, IsNil)
r.db = db
c.Assert(r.Init(context.Background()), IsNil)
// purge old relay dir
f, err := os.Create(filepath.Join(r.cfg.RelayDir, "old_relay_log"))
c.Assert(err, IsNil)
f.Close()
c.Assert(r.PurgeRelayDir(), IsNil)
files, err := os.ReadDir(r.cfg.RelayDir)
c.Assert(err, IsNil)
c.Assert(files, HasLen, 0)
c.Assert(r.meta.Load(), IsNil)
// no file specified, no need to recover
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
// save position into meta
c.Assert(r.meta.AddDir(uuid, &startPos, nil, 0), IsNil)
// relay log file does not exists, no need to recover
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
// use a generator to generate some binlog events
previousGTIDSet, err := gtid.ParserGTID(relayCfg.Flavor, previousGTIDSetStr)
c.Assert(err, IsNil)
latestGTID1, err := gtid.ParserGTID(relayCfg.Flavor, latestGTIDStr1)
c.Assert(err, IsNil)
latestGTID2, err := gtid.ParserGTID(relayCfg.Flavor, latestGTIDStr2)
c.Assert(err, IsNil)
g, events, data := genBinlogEventsWithGTIDs(c, relayCfg.Flavor, previousGTIDSet, latestGTID1, latestGTID2)
// write events into relay log file
err = os.WriteFile(filepath.Join(r.meta.Dir(), filename), data, 0o600)
c.Assert(err, IsNil)
// all events/transactions are complete, no need to recover
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
// now, we will update position/GTID set in meta to latest location in relay logs
lastEvent := events[len(events)-1]
pos := startPos
pos.Pos = lastEvent.Header.LogPos
t.verifyMetadata(c, r, uuidWithSuffix, pos, recoverGTIDSetStr, []string{uuidWithSuffix})
// write some invalid data into the relay log file
f, err = os.OpenFile(filepath.Join(r.meta.Dir(), filename), os.O_WRONLY|os.O_APPEND, 0o600)
c.Assert(err, IsNil)
_, err = f.Write([]byte("invalid event data"))
c.Assert(err, IsNil)
f.Close()
// write a greater GTID sets in meta
greaterGITDSet, err := gtid.ParserGTID(relayCfg.Flavor, greaterGITDSetStr)
c.Assert(err, IsNil)
c.Assert(r.SaveMeta(startPos, greaterGITDSet), IsNil)
// invalid data truncated, meta updated
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
_, latestPos := r.meta.Pos()
c.Assert(latestPos, DeepEquals, gmysql.Position{Name: filename, Pos: g.LatestPos})
_, latestGTIDs := r.meta.GTID()
recoverGTIDSet, err := gtid.ParserGTID(relayCfg.Flavor, recoverGTIDSetStr)
c.Assert(err, IsNil)
c.Assert(latestGTIDs.Equal(recoverGTIDSet), IsTrue) // verifyMetadata is not enough
// no relay log file need to recover
c.Assert(r.SaveMeta(minCheckpoint, latestGTIDs), IsNil)
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
_, latestPos = r.meta.Pos()
c.Assert(latestPos, DeepEquals, minCheckpoint)
_, latestGTIDs = r.meta.GTID()
c.Assert(latestGTIDs.Contain(g.LatestGTID), IsTrue)
}
func (t *testRelaySuite) TestTryRecoverMeta(c *C) {
var (
uuid = "24ecd093-8cec-11e9-aa0d-0242ac170002"
previousGTIDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-14,53bfca22-690d-11e7-8a62-18ded7a37b78:1-495,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456"
latestGTIDStr1 = "3ccc475b-2343-11e7-be21-6c0b84d59f30:14"
latestGTIDStr2 = "53bfca22-690d-11e7-8a62-18ded7a37b78:495"
// if no @@gtid_purged, 406a3f61-690d-11e7-87c5-6c92bf46f384:123-456 should be not changed
recoverGTIDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-17,53bfca22-690d-11e7-8a62-18ded7a37b78:1-505,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456"
filename = "mysql-bin.000001"
startPos = gmysql.Position{Name: filename, Pos: 123}
parser2 = parser.New()
relayCfg = newRelayCfg(c, gmysql.MySQLFlavor)
r = NewRelay(relayCfg).(*Relay)
)
cfg := getDBConfigForTest()
conn.InitMockDB(c)
db, err := conn.DefaultDBProvider.Apply(cfg)
c.Assert(err, IsNil)
r.db = db
c.Assert(r.Init(context.Background()), IsNil)
recoverGTIDSet, err := gtid.ParserGTID(relayCfg.Flavor, recoverGTIDSetStr)
c.Assert(err, IsNil)
c.Assert(r.meta.AddDir(uuid, &startPos, nil, 0), IsNil)
c.Assert(r.meta.Load(), IsNil)
// use a generator to generate some binlog events
previousGTIDSet, err := gtid.ParserGTID(relayCfg.Flavor, previousGTIDSetStr)
c.Assert(err, IsNil)
latestGTID1, err := gtid.ParserGTID(relayCfg.Flavor, latestGTIDStr1)
c.Assert(err, IsNil)
latestGTID2, err := gtid.ParserGTID(relayCfg.Flavor, latestGTIDStr2)
c.Assert(err, IsNil)
g, _, data := genBinlogEventsWithGTIDs(c, relayCfg.Flavor, previousGTIDSet, latestGTID1, latestGTID2)
// write events into relay log file
err = os.WriteFile(filepath.Join(r.meta.Dir(), filename), data, 0o600)
c.Assert(err, IsNil)
// write some invalid data into the relay log file to trigger a recover.
f, err := os.OpenFile(filepath.Join(r.meta.Dir(), filename), os.O_WRONLY|os.O_APPEND, 0o600)
c.Assert(err, IsNil)
_, err = f.Write([]byte("invalid event data"))
c.Assert(err, IsNil)
f.Close()
// recover with empty GTIDs.
c.Assert(failpoint.Enable("github.com/pingcap/tiflow/dm/pkg/utils/GetGTIDPurged", `return("")`), IsNil)
//nolint:errcheck
defer failpoint.Disable("github.com/pingcap/tiflow/dm/pkg/utils/GetGTIDPurged")
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
_, latestPos := r.meta.Pos()
c.Assert(latestPos, DeepEquals, gmysql.Position{Name: filename, Pos: g.LatestPos})
_, latestGTIDs := r.meta.GTID()
c.Assert(latestGTIDs.Equal(recoverGTIDSet), IsTrue)
// write some invalid data into the relay log file again.
f, err = os.OpenFile(filepath.Join(r.meta.Dir(), filename), os.O_WRONLY|os.O_APPEND, 0o600)
c.Assert(err, IsNil)
_, err = f.Write([]byte("invalid event data"))
c.Assert(err, IsNil)
f.Close()
// recover with the subset of GTIDs (previous GTID set).
c.Assert(r.SaveMeta(startPos, previousGTIDSet), IsNil)
c.Assert(r.tryRecoverLatestFile(context.Background(), parser2), IsNil)
_, latestPos = r.meta.Pos()
c.Assert(latestPos, DeepEquals, gmysql.Position{Name: filename, Pos: g.LatestPos})
_, latestGTIDs = r.meta.GTID()
c.Assert(latestGTIDs.Equal(recoverGTIDSet), IsTrue)
}
type dummyListener bool
func (d *dummyListener) OnEvent(e *replication.BinlogEvent) {
*d = true
}
func (t *testRelaySuite) TestListener(c *C) {
relay := NewRelay(&Config{}).(*Relay)
c.Assert(len(relay.listeners), Equals, 0)
lis := dummyListener(false)
relay.RegisterListener(&lis)
c.Assert(len(relay.listeners), Equals, 1)
relay.notify(nil)
c.Assert(bool(lis), Equals, true)
relay.UnRegisterListener(&lis)
c.Assert(len(relay.listeners), Equals, 0)
lis = false
relay.notify(nil)
c.Assert(bool(lis), Equals, false)
}
// genBinlogEventsWithGTIDs generates some binlog events used by testFileUtilSuite and testFileWriterSuite.
// now, its generated events including 3 DDL and 10 DML.
func genBinlogEventsWithGTIDs(c *C, flavor string, previousGTIDSet, latestGTID1, latestGTID2 gmysql.GTIDSet) (*event.Generator, []*replication.BinlogEvent, []byte) {
var (
serverID uint32 = 11
latestPos uint32
latestXID uint64 = 10
allEvents = make([]*replication.BinlogEvent, 0, 50)
allData bytes.Buffer
)
// use a binlog event generator to generate some binlog events.
g, err := event.NewGenerator(flavor, serverID, latestPos, latestGTID1, previousGTIDSet, latestXID)
c.Assert(err, IsNil)
// file header with FormatDescriptionEvent and PreviousGTIDsEvent
events, data, err := g.GenFileHeader(0)
c.Assert(err, IsNil)
allEvents = append(allEvents, events...)
allData.Write(data)
// CREATE DATABASE/TABLE, 3 DDL
queries := []string{
"CREATE DATABASE `db`",
"CREATE TABLE `db`.`tbl1` (c1 INT)",
"CREATE TABLE `db`.`tbl2` (c1 INT)",
}
for _, query := range queries {
events, data, err = g.GenDDLEvents("db", query, 0)
c.Assert(err, IsNil)
allEvents = append(allEvents, events...)
allData.Write(data)
}
// DMLs, 10 DML
g.LatestGTID = latestGTID2 // use another latest GTID with different SID/DomainID
var (
tableID uint64 = 8
columnType = []byte{gmysql.MYSQL_TYPE_LONG}
eventType = replication.WRITE_ROWS_EVENTv2
schema = "db"
table = "tbl1"
)
for i := 0; i < 10; i++ {
insertRows := make([][]interface{}, 0, 1)
insertRows = append(insertRows, []interface{}{int32(i)})
dmlData := []*event.DMLData{
{
TableID: tableID,
Schema: schema,
Table: table,
ColumnType: columnType,
Rows: insertRows,
},
}
events, data, err = g.GenDMLEvents(eventType, dmlData, 0)
c.Assert(err, IsNil)
allEvents = append(allEvents, events...)
allData.Write(data)
}
return g, allEvents, allData.Bytes()
}
func (t *testRelaySuite) TestHandleEvent(c *C) {
// NOTE: we can test metrics later.
var (
reader2 = &mockReader{}
parser2 = parser.New()
writer2 = &mockWriter{}
relayCfg = newRelayCfg(c, gmysql.MariaDBFlavor)
r = NewRelay(relayCfg).(*Relay)
eventHeader = &replication.EventHeader{
Timestamp: uint32(time.Now().Unix()),
ServerID: 11,
}
binlogPos = gmysql.Position{Name: "mysql-bin.666888", Pos: 4}
rotateEv, _ = event.GenRotateEvent(eventHeader, 123, []byte(binlogPos.Name), uint64(binlogPos.Pos))
fakeRotateEv, _ = event.GenRotateEvent(eventHeader, 0, []byte(binlogPos.Name), uint64(1234))
queryEv, _ = event.GenQueryEvent(eventHeader, 123, 0, 0, 0, nil, nil, []byte("CREATE DATABASE db_relay_test"))
)
r.writer = writer2
cfg := getDBConfigForTest()
conn.InitMockDB(c)
db, err := conn.DefaultDBProvider.Apply(cfg)
c.Assert(err, IsNil)
r.db = db
c.Assert(r.Init(context.Background()), IsNil)
// NOTE: we can mock meta later.
c.Assert(r.meta.Load(), IsNil)
c.Assert(r.meta.AddDir("24ecd093-8cec-11e9-aa0d-0242ac170002", nil, nil, 0), IsNil)
// attach GTID sets to QueryEv
queryEv2 := queryEv.Event.(*replication.QueryEvent)
queryEv2.GSet, _ = gmysql.ParseGTIDSet(relayCfg.Flavor, "1-2-3")
// reader return with an error
for _, reader2.err = range []error{
errors.New("reader error for testing"),
replication.ErrChecksumMismatch,
replication.ErrSyncClosed,
replication.ErrNeedSyncAgain,
} {
handleErr := r.handleEvents(context.Background(), reader2, parser2)
c.Assert(errors.Cause(handleErr), Equals, reader2.err)
}
// reader return fake rotate event
reader2.err = nil
reader2.result.Event = fakeRotateEv
// writer return error to force handleEvents return
writer2.err = errors.New("writer error for testing")
// return with the annotated writer error
err = r.handleEvents(context.Background(), reader2, parser2)
c.Assert(errors.Cause(err), Equals, writer2.err)
// after handle rotate event, we save and flush the meta immediately
c.Assert(r.meta.Dirty(), Equals, false)
{
lm := r.meta.(*LocalMeta)
c.Assert(lm.BinLogName, Equals, "mysql-bin.666888")
c.Assert(lm.BinLogPos, Equals, uint32(1234))
filename := filepath.Join(lm.baseDir, lm.currentSubDir, utils.MetaFilename)
lm2 := &LocalMeta{}
_, err2 := toml.DecodeFile(filename, lm2)
c.Assert(err2, IsNil)
c.Assert(lm2.BinLogName, Equals, "mysql-bin.666888")
c.Assert(lm2.BinLogPos, Equals, uint32(1234))
}
{
lm := r.meta.(*LocalMeta)
backupUUID := lm.currentSubDir
lm.currentSubDir = "not exist"
err = r.handleEvents(context.Background(), reader2, parser2)
c.Assert(os.IsNotExist(errors.Cause(err)), Equals, true)
lm.currentSubDir = backupUUID
}
// reader return valid event
reader2.err = nil
reader2.result.Event = rotateEv
// writer return error
writer2.err = errors.New("writer error for testing")
// return with the annotated writer error
err = r.handleEvents(context.Background(), reader2, parser2)
c.Assert(errors.Cause(err), Equals, writer2.err)
c.Assert(r.meta.Dirty(), Equals, false)
// writer without error
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
writer2.err = nil
err = r.handleEvents(ctx, reader2, parser2) // returned when ctx timeout
c.Assert(errors.Cause(err), Equals, ctx.Err())
// check written event
c.Assert(writer2.latestEvent, Equals, reader2.result.Event)
// check meta
_, pos := r.meta.Pos()
_, gs := r.meta.GTID()
c.Assert(pos, DeepEquals, binlogPos)
c.Assert(gs.String(), Equals, "") // no GTID sets in event yet
ctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel2()
// write a QueryEvent with GTID sets
reader2.result.Event = queryEv
err = r.handleEvents(ctx2, reader2, parser2)
c.Assert(errors.Cause(err), Equals, ctx.Err())
// check written event
c.Assert(writer2.latestEvent, Equals, reader2.result.Event)
// check meta
_, pos = r.meta.Pos()
_, gs = r.meta.GTID()
c.Assert(pos.Name, Equals, binlogPos.Name)
c.Assert(pos.Pos, Equals, queryEv.Header.LogPos)
c.Assert(gs, DeepEquals, queryEv2.GSet) // got GTID sets
// transformer return ignorable for the event
reader2.err = nil
reader2.result.Event = &replication.BinlogEvent{
Header: &replication.EventHeader{EventType: replication.HEARTBEAT_EVENT},
Event: &replication.GenericEvent{},
}
ctx4, cancel4 := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel4()
err = r.handleEvents(ctx4, reader2, parser2)
c.Assert(errors.Cause(err), Equals, ctx.Err())
select {
case <-ctx4.Done():
default:
c.Fatalf("ignorable event for transformer not ignored")
}
// writer return ignorable for the event
reader2.result.Event = queryEv
writer2.result.Ignore = true
ctx5, cancel5 := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel5()
err = r.handleEvents(ctx5, reader2, parser2)
c.Assert(errors.Cause(err), Equals, ctx.Err())
select {
case <-ctx5.Done():
default:
c.Fatalf("ignorable event for writer not ignored")
}
}
func (t *testRelaySuite) TestReSetupMeta(c *C) {
ctx, cancel := context.WithTimeout(context.Background(), utils.DefaultDBTimeout)
defer cancel()
var (
relayCfg = newRelayCfg(c, gmysql.MySQLFlavor)
r = NewRelay(relayCfg).(*Relay)
)
cfg := getDBConfigForTest()
mockDB := conn.InitMockDB(c)
db, err := conn.DefaultDBProvider.Apply(cfg)
c.Assert(err, IsNil)
r.db = db
c.Assert(r.Init(context.Background()), IsNil)
// empty metadata
c.Assert(r.meta.Load(), IsNil)
t.verifyMetadata(c, r, "", minCheckpoint, "", nil)
// open connected DB and get its UUID
defer func() {
r.db.Close()
r.db = nil
}()
mockGetServerUUID(mockDB)
uuid, err := utils.GetServerUUID(ctx, r.db.DB, r.cfg.Flavor)
c.Assert(err, IsNil)
// re-setup meta with start pos adjusted
r.cfg.EnableGTID = true
r.cfg.BinlogGTID = "24ecd093-8cec-11e9-aa0d-0242ac170002:1-23"
r.cfg.BinLogName = "mysql-bin.000005"
c.Assert(r.setSyncConfig(), IsNil)
// all adjusted gset should be empty since we didn't flush logs
emptyGTID, err := gtid.ParserGTID(r.cfg.Flavor, "")
c.Assert(err, IsNil)
mockGetServerUUID(mockDB)
mockGetRandomServerID(mockDB)
// mock AddGSetWithPurged
mockDB.ExpectQuery("select @@GLOBAL.gtid_purged").WillReturnRows(sqlmock.NewRows([]string{"@@GLOBAL.gtid_purged"}).AddRow(""))
c.Assert(failpoint.Enable("github.com/pingcap/tiflow/dm/pkg/binlog/reader/MockGetEmptyPreviousGTIDFromGTIDSet", "return()"), IsNil)
//nolint:errcheck
defer failpoint.Disable("github.com/pingcap/tiflow/dm/pkg/binlog/reader/MockGetEmptyPreviousGTIDFromGTIDSet")
c.Assert(r.reSetupMeta(ctx), IsNil)
uuid001 := fmt.Sprintf("%s.000001", uuid)
t.verifyMetadata(c, r, uuid001, gmysql.Position{Name: r.cfg.BinLogName, Pos: 4}, emptyGTID.String(), []string{uuid001})
// re-setup meta again, often happen when connecting a server behind a VIP.
mockGetServerUUID(mockDB)
mockGetRandomServerID(mockDB)
mockDB.ExpectQuery("select @@GLOBAL.gtid_purged").WillReturnRows(sqlmock.NewRows([]string{"@@GLOBAL.gtid_purged"}).AddRow(""))
c.Assert(r.reSetupMeta(ctx), IsNil)
uuid002 := fmt.Sprintf("%s.000002", uuid)
t.verifyMetadata(c, r, uuid002, minCheckpoint, emptyGTID.String(), []string{uuid001, uuid002})
r.cfg.BinLogName = "mysql-bin.000002"
r.cfg.BinlogGTID = "24ecd093-8cec-11e9-aa0d-0242ac170002:1-50,24ecd093-8cec-11e9-aa0d-0242ac170003:1-50"
r.cfg.UUIDSuffix = 2
mockGetServerUUID(mockDB)
mockGetRandomServerID(mockDB)
mockDB.ExpectQuery("select @@GLOBAL.gtid_purged").WillReturnRows(sqlmock.NewRows([]string{"@@GLOBAL.gtid_purged"}).AddRow(""))
c.Assert(r.reSetupMeta(ctx), IsNil)
t.verifyMetadata(c, r, uuid002, gmysql.Position{Name: r.cfg.BinLogName, Pos: 4}, emptyGTID.String(), []string{uuid002})
// re-setup meta again, often happen when connecting a server behind a VIP.
mockGetServerUUID(mockDB)
mockGetRandomServerID(mockDB)
mockDB.ExpectQuery("select @@GLOBAL.gtid_purged").WillReturnRows(sqlmock.NewRows([]string{"@@GLOBAL.gtid_purged"}).AddRow(""))
c.Assert(r.reSetupMeta(ctx), IsNil)
uuid003 := fmt.Sprintf("%s.000003", uuid)
t.verifyMetadata(c, r, uuid003, minCheckpoint, emptyGTID.String(), []string{uuid002, uuid003})
c.Assert(mockDB.ExpectationsWereMet(), IsNil)
}
func (t *testRelaySuite) verifyMetadata(c *C, r *Relay, uuidExpected string,
posExpected gmysql.Position, gsStrExpected string, uuidsExpected []string,
) {
uuid, pos := r.meta.Pos()
_, gs := r.meta.GTID()
gsExpected, err := gtid.ParserGTID(gmysql.MySQLFlavor, gsStrExpected)
c.Assert(err, IsNil)
c.Assert(uuid, Equals, uuidExpected)
c.Assert(pos, DeepEquals, posExpected)
c.Assert(gs.Equal(gsExpected), IsTrue)
indexFile := filepath.Join(r.cfg.RelayDir, utils.UUIDIndexFilename)
UUIDs, err := utils.ParseUUIDIndex(indexFile)
c.Assert(err, IsNil)
c.Assert(UUIDs, DeepEquals, uuidsExpected)
}
func (t *testRelaySuite) TestPreprocessEvent(c *C) {
type Case struct {
event *replication.BinlogEvent
result preprocessResult
}
relay := &Relay{}
parser2 := parser.New()
var (
header = &replication.EventHeader{
Timestamp: uint32(time.Now().Unix()),
ServerID: 11,
Flags: 0x01,
}
latestPos uint32 = 456789
gtidStr = "9f61c5f9-1eef-11e9-b6cf-0242ac140003:5"
gtidSet, _ = gtid.ParserGTID(gmysql.MySQLFlavor, gtidStr)
schema = []byte("test_schema")
cases = make([]Case, 0, 10)
)
// RotateEvent
nextLogName := "mysql-bin.000123"
position := uint64(4)
ev, err := event.GenRotateEvent(header, latestPos, []byte(nextLogName), position)
c.Assert(err, IsNil)
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: uint32(position),
NextLogName: nextLogName,
},
})
// fake RotateEvent with zero timestamp
header.Timestamp = 0
ev, err = event.GenRotateEvent(header, latestPos, []byte(nextLogName), position)
c.Assert(err, IsNil)
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: uint32(position),
NextLogName: nextLogName,
},
})
header.Timestamp = uint32(time.Now().Unix()) // set to non-zero
// fake RotateEvent with zero logPos
fakeRotateHeader := *header
ev, err = event.GenRotateEvent(&fakeRotateHeader, latestPos, []byte(nextLogName), position)
c.Assert(err, IsNil)
ev.Header.LogPos = 0 // set to zero
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: uint32(position),
NextLogName: nextLogName,
},
})
// QueryEvent for DDL
query := []byte("CREATE TABLE test_tbl (c1 INT)")
ev, err = event.GenQueryEvent(header, latestPos, 0, 0, 0, nil, schema, query)
c.Assert(err, IsNil)
ev.Event.(*replication.QueryEvent).GSet = gtidSet // set GTIDs manually
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: ev.Header.LogPos,
GTIDSet: gtidSet,
CanSaveGTID: true,
},
})
// QueryEvent for non-DDL
query = []byte("BEGIN")
ev, err = event.GenQueryEvent(header, latestPos, 0, 0, 0, nil, schema, query)
c.Assert(err, IsNil)
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: ev.Header.LogPos,
},
})
// XIDEvent
xid := uint64(135)
ev, err = event.GenXIDEvent(header, latestPos, xid)
c.Assert(err, IsNil)
ev.Event.(*replication.XIDEvent).GSet = gtidSet // set GTIDs manually
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: ev.Header.LogPos,
GTIDSet: gtidSet,
CanSaveGTID: true,
},
})
// GenericEvent, non-HEARTBEAT_EVENT
ev = &replication.BinlogEvent{Header: header, Event: &replication.GenericEvent{}}
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: ev.Header.LogPos,
},
})
// GenericEvent, HEARTBEAT_EVENT
genericHeader := *header
ev = &replication.BinlogEvent{Header: &genericHeader, Event: &replication.GenericEvent{}}
ev.Header.EventType = replication.HEARTBEAT_EVENT
cases = append(cases, Case{
event: ev,
result: preprocessResult{
Ignore: true,
IgnoreReason: ignoreReasonHeartbeat,
LogPos: ev.Header.LogPos,
},
})
// other event type without LOG_EVENT_ARTIFICIAL_F
ev, err = event.GenCommonGTIDEvent(gmysql.MySQLFlavor, header.ServerID, latestPos, gtidSet, false, 0)
c.Assert(err, IsNil)
cases = append(cases, Case{
event: ev,
result: preprocessResult{
LogPos: ev.Header.LogPos,
},
})
// other event type with LOG_EVENT_ARTIFICIAL_F
ev, err = event.GenTableMapEvent(header, latestPos, 0, []byte("testdb"), []byte("testtbl"), []byte("INT"))
c.Assert(err, IsNil)
ev.Header.Flags |= replication.LOG_EVENT_ARTIFICIAL_F
cases = append(cases, Case{
event: ev,
result: preprocessResult{
Ignore: true,
IgnoreReason: ignoreReasonArtificialFlag,
LogPos: ev.Header.LogPos,
},
})
for _, cs := range cases {
c.Assert(relay.preprocessEvent(cs.event, parser2), DeepEquals, cs.result)
}
}
func (t *testRelaySuite) TestRecoverMySQL(c *C) {
var (
relayDir = c.MkDir()
filename = "test-mysql-bin.000001"
parser2 = parser.New()
flavor = gmysql.MySQLFlavor
previousGTIDSetStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-14,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456,53bfca22-690d-11e7-8a62-18ded7a37b78:1-495,686e1ab6-c47e-11e7-a42c-6c92bf46f384:234-567"
latestGTIDStr1 = "3ccc475b-2343-11e7-be21-6c0b84d59f30:14"
latestGTIDStr2 = "53bfca22-690d-11e7-8a62-18ded7a37b78:495"
)
r := NewRelay(&Config{Flavor: flavor}).(*Relay)
// different SIDs in GTID set
previousGTIDSet, err := gtid.ParserGTID(flavor, previousGTIDSetStr)
c.Assert(err, IsNil)
latestGTID1, err := gtid.ParserGTID(flavor, latestGTIDStr1)
c.Assert(err, IsNil)
latestGTID2, err := gtid.ParserGTID(flavor, latestGTIDStr2)
c.Assert(err, IsNil)
// generate binlog events
g, _, baseData := genBinlogEventsWithGTIDs(c, flavor, previousGTIDSet, latestGTID1, latestGTID2)
// expected latest pos/GTID set
expectedPos := gmysql.Position{Name: filename, Pos: uint32(len(baseData))}
// 3 DDL + 10 DML
expectedGTIDsStr := "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-17,53bfca22-690d-11e7-8a62-18ded7a37b78:1-505,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456,686e1ab6-c47e-11e7-a42c-6c92bf46f384:234-567"
expectedGTIDs, err := gtid.ParserGTID(flavor, expectedGTIDsStr)
c.Assert(err, IsNil)
// write the events to a file
fullName := filepath.Join(relayDir, filename)
err = os.WriteFile(fullName, baseData, 0o644)
c.Assert(err, IsNil)
// try recover, but in fact do nothing
result, err := r.doRecovering(context.Background(), relayDir, filename, parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsFalse)
c.Assert(result.LatestPos, DeepEquals, expectedPos)
c.Assert(result.LatestGTIDs, DeepEquals, expectedGTIDs)
// check file size, whether no recovering operation applied
fs, err := os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData)))
// generate another transaction, DDL
extraEvents, extraData, err := g.GenDDLEvents("db2", "CREATE DATABASE db2", 0)
c.Assert(err, IsNil)
c.Assert(extraEvents, HasLen, 2) // [GTID, Query]
// write an incomplete event to the file
corruptData := extraEvents[0].RawData[:len(extraEvents[0].RawData)-2]
f, err := os.OpenFile(fullName, os.O_WRONLY|os.O_APPEND, 0o644)
c.Assert(err, IsNil)
_, err = f.Write(corruptData)
c.Assert(err, IsNil)
c.Assert(f.Close(), IsNil)
// check file size, increased
fs, err = os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData)+len(corruptData)))
// try recover, truncate the incomplete event
result, err = r.doRecovering(context.Background(), relayDir, filename, parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsTrue)
c.Assert(result.LatestPos, DeepEquals, expectedPos)
c.Assert(result.LatestGTIDs, DeepEquals, expectedGTIDs)
// check file size, truncated
fs, err = os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData)))
// write an incomplete transaction
f, err = os.OpenFile(fullName, os.O_WRONLY|os.O_APPEND, 0o644)
c.Assert(err, IsNil)
var extraLen int64
for i := 0; i < len(extraEvents)-1; i++ {
_, err = f.Write(extraEvents[i].RawData)
c.Assert(err, IsNil)
extraLen += int64(len(extraEvents[i].RawData))
}
c.Assert(f.Close(), IsNil)
// check file size, increased
fs, err = os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData))+extraLen)
// try recover, truncate the incomplete transaction
result, err = r.doRecovering(context.Background(), relayDir, filename, parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsTrue)
c.Assert(result.LatestPos, DeepEquals, expectedPos)
c.Assert(result.LatestGTIDs, DeepEquals, expectedGTIDs)
// check file size, truncated
fs, err = os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData)))
// write an completed transaction
f, err = os.OpenFile(fullName, os.O_WRONLY|os.O_APPEND, 0o644)
c.Assert(err, IsNil)
for i := 0; i < len(extraEvents); i++ {
_, err = f.Write(extraEvents[i].RawData)
c.Assert(err, IsNil)
}
c.Assert(f.Close(), IsNil)
// check file size, increased
fs, err = os.Stat(fullName)
c.Assert(err, IsNil)
c.Assert(fs.Size(), Equals, int64(len(baseData)+len(extraData)))
// try recover, no operation applied
expectedPos.Pos += uint32(len(extraData))
// 4 DDL + 10 DML
expectedGTIDsStr = "3ccc475b-2343-11e7-be21-6c0b84d59f30:1-17,53bfca22-690d-11e7-8a62-18ded7a37b78:1-506,406a3f61-690d-11e7-87c5-6c92bf46f384:123-456,686e1ab6-c47e-11e7-a42c-6c92bf46f384:234-567"
expectedGTIDs, err = gtid.ParserGTID(flavor, expectedGTIDsStr)
c.Assert(err, IsNil)
result, err = r.doRecovering(context.Background(), relayDir, filename, parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsFalse)
c.Assert(result.LatestPos, DeepEquals, expectedPos)
c.Assert(result.LatestGTIDs, DeepEquals, expectedGTIDs)
// compare file data
var allData bytes.Buffer
allData.Write(baseData)
allData.Write(extraData)
fileData, err := os.ReadFile(fullName)
c.Assert(err, IsNil)
c.Assert(fileData, DeepEquals, allData.Bytes())
}
func (t *testRelaySuite) TestRecoverMySQLNone(c *C) {
relayDir := c.MkDir()
parser2 := parser.New()
r := NewRelay(&Config{Flavor: gmysql.MySQLFlavor}).(*Relay)
// no file specified to recover
result, err := r.doRecovering(context.Background(), relayDir, "", parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsFalse)
filename := "mysql-bin.000001"
// file not exist, no need to recover
result, err = r.doRecovering(context.Background(), relayDir, filename, parser2)
c.Assert(err, IsNil)
c.Assert(result.Truncated, IsFalse)
}
|
[
"\"MYSQL_HOST\"",
"\"MYSQL_PORT\"",
"\"MYSQL_USER\"",
"\"MYSQL_PSWD\""
] |
[] |
[
"MYSQL_PORT",
"MYSQL_USER",
"MYSQL_PSWD",
"MYSQL_HOST"
] |
[]
|
["MYSQL_PORT", "MYSQL_USER", "MYSQL_PSWD", "MYSQL_HOST"]
|
go
| 4 | 0 | |
pkg/ddevapp/ddevapp.go
|
package ddevapp
import (
"bytes"
"embed"
"fmt"
"github.com/drud/ddev/pkg/versionconstants"
"golang.org/x/term"
"gopkg.in/yaml.v2"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/drud/ddev/pkg/nodeps"
"github.com/lextoumbourou/goodhosts"
"github.com/mattn/go-isatty"
"github.com/otiai10/copy"
"github.com/pkg/errors"
osexec "os/exec"
"path"
"time"
"github.com/drud/ddev/pkg/appimport"
"github.com/drud/ddev/pkg/archive"
"github.com/drud/ddev/pkg/ddevhosts"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/exec"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/util"
docker "github.com/fsouza/go-dockerclient"
)
// containerWaitTimeout is the max time we wait for all containers to become ready.
var containerWaitTimeout = 61
// SiteRunning defines the string used to denote running sites.
const SiteRunning = "running"
// SiteStarting is the string for a project that is starting
const SiteStarting = "starting"
// SiteStopped defines the string used to denote a site where the containers were not found/do not exist, but the project is there.
const SiteStopped = "stopped"
// SiteDirMissing defines the string used to denote when a site is missing its application directory.
const SiteDirMissing = "project directory missing"
// SiteConfigMissing defines the string used to denote when a site is missing its .ddev/config.yml file.
const SiteConfigMissing = ".ddev/config.yaml missing"
// SitePaused defines the string used to denote when a site is in the paused (docker stopped) state.
const SitePaused = "paused"
// SiteUnhealthy is the status for a project whose services are not all running
const SiteUnhealthy = "unhealthy"
// DatabaseDefault is the default database/version
var DatabaseDefault = DatabaseDesc{nodeps.MariaDB, nodeps.MariaDBDefaultVersion}
type DatabaseDesc struct {
Type string `yaml:"type"`
Version string `yaml:"version"`
}
// DdevApp is the struct that represents a ddev app, mostly its config
// from config.yaml.
type DdevApp struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Docroot string `yaml:"docroot"`
PHPVersion string `yaml:"php_version"`
WebserverType string `yaml:"webserver_type"`
WebImage string `yaml:"webimage,omitempty"`
DBImage string `yaml:"dbimage,omitempty"`
DBAImage string `yaml:"dbaimage,omitempty"`
RouterHTTPPort string `yaml:"router_http_port"`
RouterHTTPSPort string `yaml:"router_https_port"`
XdebugEnabled bool `yaml:"xdebug_enabled"`
NoProjectMount bool `yaml:"no_project_mount,omitempty"`
AdditionalHostnames []string `yaml:"additional_hostnames"`
AdditionalFQDNs []string `yaml:"additional_fqdns"`
MariaDBVersion string `yaml:"mariadb_version,omitempty"`
MySQLVersion string `yaml:"mysql_version,omitempty"`
Database DatabaseDesc `yaml:"database"`
NFSMountEnabled bool `yaml:"nfs_mount_enabled"`
NFSMountEnabledGlobal bool `yaml:"-"`
MutagenEnabled bool `yaml:"mutagen_enabled"`
MutagenEnabledGlobal bool `yaml:"-"`
FailOnHookFail bool `yaml:"fail_on_hook_fail,omitempty"`
BindAllInterfaces bool `yaml:"bind_all_interfaces,omitempty"`
FailOnHookFailGlobal bool `yaml:"-"`
ConfigPath string `yaml:"-"`
AppRoot string `yaml:"-"`
DataDir string `yaml:"-"`
SiteSettingsPath string `yaml:"-"`
SiteDdevSettingsFile string `yaml:"-"`
ProviderInstance *Provider `yaml:"-"`
Hooks map[string][]YAMLTask `yaml:"hooks,omitempty"`
UploadDir string `yaml:"upload_dir,omitempty"`
WorkingDir map[string]string `yaml:"working_dir,omitempty"`
OmitContainers []string `yaml:"omit_containers,omitempty,flow"`
OmitContainersGlobal []string `yaml:"-"`
HostDBPort string `yaml:"host_db_port,omitempty"`
HostWebserverPort string `yaml:"host_webserver_port,omitempty"`
HostHTTPSPort string `yaml:"host_https_port,omitempty"`
MailhogPort string `yaml:"mailhog_port,omitempty"`
MailhogHTTPSPort string `yaml:"mailhog_https_port,omitempty"`
HostMailhogPort string `yaml:"host_mailhog_port,omitempty"`
PHPMyAdminPort string `yaml:"phpmyadmin_port,omitempty"`
PHPMyAdminHTTPSPort string `yaml:"phpmyadmin_https_port,omitempty"`
// HostPHPMyAdminPort is normally empty, as it is not normally bound
HostPHPMyAdminPort string `yaml:"host_phpmyadmin_port,omitempty"`
WebImageExtraPackages []string `yaml:"webimage_extra_packages,omitempty,flow"`
DBImageExtraPackages []string `yaml:"dbimage_extra_packages,omitempty,flow"`
ProjectTLD string `yaml:"project_tld,omitempty"`
UseDNSWhenPossible bool `yaml:"use_dns_when_possible"`
MkcertEnabled bool `yaml:"-"`
NgrokArgs string `yaml:"ngrok_args,omitempty"`
Timezone string `yaml:"timezone,omitempty"`
ComposerRoot string `yaml:"composer_root,omitempty"`
ComposerVersion string `yaml:"composer_version"`
DisableSettingsManagement bool `yaml:"disable_settings_management,omitempty"`
WebEnvironment []string `yaml:"web_environment"`
NodeJSVersion string `yaml:"nodejs_version"`
ComposeYaml map[string]interface{} `yaml:"-"`
}
// GetType returns the application type as a (lowercase) string
func (app *DdevApp) GetType() string {
return strings.ToLower(app.Type)
}
// Init populates DdevApp config based on the current working directory.
// It does not start the containers.
func (app *DdevApp) Init(basePath string) error {
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("app.Init(%s)", basePath))
defer runTime()
newApp, err := NewApp(basePath, true)
if err != nil {
return err
}
err = newApp.ValidateConfig()
if err != nil {
return err
}
*app = *newApp
web, err := app.FindContainerByType("web")
if err != nil {
return err
}
if web != nil {
containerApproot := web.Labels["com.ddev.approot"]
isSameFile, err := fileutil.IsSameFile(containerApproot, app.AppRoot)
if err != nil {
return err
}
if !isSameFile {
return fmt.Errorf("a project (web container) in %s state already exists for %s that was created at %s", web.State, app.Name, containerApproot).(webContainerExists)
}
return nil
}
// Init() is just putting together the DdevApp struct, the containers do
// not have to exist (app doesn't have to have been started), so the fact
// we didn't find any is not an error.
return nil
}
// FindContainerByType will find a container for this site denoted by the containerType if it is available.
func (app *DdevApp) FindContainerByType(containerType string) (*docker.APIContainers, error) {
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
"com.docker.compose.service": containerType,
}
return dockerutil.FindContainerByLabels(labels)
}
// Describe returns a map which provides detailed information on services associated with the running site.
func (app *DdevApp) Describe(short bool) (map[string]interface{}, error) {
app.DockerEnv()
err := app.ProcessHooks("pre-describe")
if err != nil {
return nil, fmt.Errorf("failed to process pre-describe hooks: %v", err)
}
shortRoot := RenderHomeRootedDir(app.GetAppRoot())
appDesc := make(map[string]interface{})
status, statusDesc := app.SiteStatus()
appDesc["name"] = app.GetName()
appDesc["status"] = status
appDesc["status_desc"] = statusDesc
appDesc["approot"] = app.GetAppRoot()
appDesc["docroot"] = app.GetDocroot()
appDesc["shortroot"] = shortRoot
appDesc["httpurl"] = app.GetHTTPURL()
appDesc["httpsurl"] = app.GetHTTPSURL()
appDesc["router_disabled"] = IsRouterDisabled(app)
appDesc["primary_url"] = app.GetPrimaryURL()
appDesc["type"] = app.GetType()
appDesc["mutagen_enabled"] = app.IsMutagenEnabled()
appDesc["nodejs_version"] = app.NodeJSVersion
if app.IsMutagenEnabled() {
appDesc["mutagen_status"], _, _, err = app.MutagenStatus()
if err != nil {
appDesc["mutagen_status"] = err.Error() + " " + appDesc["mutagen_status"].(string)
}
}
// if short is set, we don't need more information, so return what we have.
if short {
return appDesc, nil
}
appDesc["hostname"] = app.GetHostname()
appDesc["hostnames"] = app.GetHostnames()
appDesc["nfs_mount_enabled"] = (app.NFSMountEnabled || app.NFSMountEnabledGlobal) && !(app.IsMutagenEnabled())
appDesc["fail_on_hook_fail"] = app.FailOnHookFail || app.FailOnHookFailGlobal
httpURLs, httpsURLs, allURLs := app.GetAllURLs()
appDesc["httpURLs"] = httpURLs
appDesc["httpsURLs"] = httpsURLs
appDesc["urls"] = allURLs
appDesc["database_type"] = app.Database.Type
appDesc["database_version"] = app.Database.Version
// Only show extended status for running sites.
if status == SiteRunning {
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
dbinfo := make(map[string]interface{})
dbinfo["username"] = "db"
dbinfo["password"] = "db"
dbinfo["dbname"] = "db"
dbinfo["host"] = "db"
dbPublicPort, err := app.GetPublishedPort("db")
util.CheckErr(err)
dbinfo["dbPort"] = GetInternalPort(app, "db")
util.CheckErr(err)
dbinfo["published_port"] = dbPublicPort
dbinfo["database_type"] = "mariadb" // default
dbinfo["database_type"] = app.Database.Type
dbinfo["database_version"] = app.Database.Version
appDesc["dbinfo"] = dbinfo
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "dba") {
appDesc["phpmyadmin_https_url"] = "https://" + app.GetHostname() + ":" + app.PHPMyAdminHTTPSPort
appDesc["phpmyadmin_url"] = "http://" + app.GetHostname() + ":" + app.PHPMyAdminPort
}
}
appDesc["mailhog_https_url"] = "https://" + app.GetHostname() + ":" + app.MailhogHTTPSPort
appDesc["mailhog_url"] = "http://" + app.GetHostname() + ":" + app.MailhogPort
}
routerStatus, logOutput := GetRouterStatus()
appDesc["router_status"] = routerStatus
appDesc["router_status_log"] = logOutput
appDesc["ssh_agent_status"] = GetSSHAuthStatus()
appDesc["php_version"] = app.GetPhpVersion()
appDesc["webserver_type"] = app.GetWebserverType()
appDesc["router_http_port"] = app.RouterHTTPPort
appDesc["router_https_port"] = app.RouterHTTPSPort
appDesc["xdebug_enabled"] = app.XdebugEnabled
appDesc["webimg"] = app.WebImage
appDesc["dbimg"] = app.GetDBImage()
appDesc["services"] = map[string]map[string]string{}
containers, err := dockerutil.GetAppContainers(app.Name)
if err != nil {
return nil, err
}
services := appDesc["services"].(map[string]map[string]string)
for _, k := range containers {
serviceName := strings.TrimPrefix(k.Names[0], "/")
shortName := strings.Replace(serviceName, fmt.Sprintf("ddev-%s-", app.Name), "", 1)
c, err := dockerutil.InspectContainer(serviceName)
if err != nil || c == nil {
util.Warning("Could not get container info for %s", serviceName)
continue
}
fullName := strings.TrimPrefix(serviceName, "/")
services[shortName] = map[string]string{}
services[shortName]["status"] = c.State.Status
services[shortName]["full_name"] = fullName
services[shortName]["image"] = strings.TrimSuffix(c.Config.Image, fmt.Sprintf("-%s-built", app.Name))
var ports []string
for pk := range c.Config.ExposedPorts {
ports = append(ports, pk.Port())
}
services[shortName]["exposed_ports"] = strings.Join(ports, ",")
var hostPorts []string
for _, pv := range k.Ports {
if pv.PublicPort != 0 {
hostPorts = append(hostPorts, strconv.FormatInt(pv.PublicPort, 10))
}
}
services[shortName]["host_ports"] = strings.Join(hostPorts, ",")
// Extract HTTP_EXPOSE and HTTPS_EXPOSE for additional info
if !IsRouterDisabled(app) {
for _, e := range c.Config.Env {
split := strings.SplitN(e, "=", 2)
envName := split[0]
if len(split) == 2 && (envName == "HTTP_EXPOSE" || envName == "HTTPS_EXPOSE") {
envVal := split[1]
envValStr := fmt.Sprintf("%s", envVal)
portSpecs := strings.Split(envValStr, ",")
// There might be more than one exposed UI port, but this only handles the first listed,
// most often there's only one.
if len(portSpecs) > 0 {
// HTTPS portSpecs typically look like <exposed>:<containerPort>, for example - HTTPS_EXPOSE=1359:1358
ports := strings.Split(portSpecs[0], ":")
//services[shortName][envName.(string)] = ports[0]
switch envName {
case "HTTP_EXPOSE":
services[shortName]["http_url"] = "http://" + appDesc["hostname"].(string)
if ports[0] != "80" {
services[shortName]["http_url"] = services[shortName]["http_url"] + ":" + ports[0]
}
case "HTTPS_EXPOSE":
services[shortName]["https_url"] = "https://" + appDesc["hostname"].(string)
if ports[0] != "443" {
services[shortName]["https_url"] = services[shortName]["https_url"] + ":" + ports[0]
}
}
}
}
}
}
if shortName == "web" {
services[shortName]["host_http_url"] = app.GetWebContainerDirectHTTPURL()
services[shortName]["host_https_url"] = app.GetWebContainerDirectHTTPSURL()
}
}
err = app.ProcessHooks("post-describe")
if err != nil {
return nil, fmt.Errorf("failed to process post-describe hooks: %v", err)
}
return appDesc, nil
}
// GetPublishedPort returns the host-exposed public port of a container.
func (app *DdevApp) GetPublishedPort(serviceName string) (int, error) {
container, err := app.FindContainerByType(serviceName)
if err != nil || container == nil {
return -1, fmt.Errorf("failed to find container of type %s: %v", serviceName, err)
}
privatePort, _ := strconv.ParseInt(GetInternalPort(app, serviceName), 10, 16)
publishedPort := dockerutil.GetPublishedPort(privatePort, *container)
return publishedPort, nil
}
// GetOmittedContainers returns full list of global and local omitted containers
func (app *DdevApp) GetOmittedContainers() []string {
omitted := app.OmitContainersGlobal
omitted = append(omitted, app.OmitContainers...)
return omitted
}
// GetAppRoot return the full path from root to the app directory
func (app *DdevApp) GetAppRoot() string {
return app.AppRoot
}
// AppConfDir returns the full path to the app's .ddev configuration directory
func (app *DdevApp) AppConfDir() string {
return filepath.Join(app.AppRoot, ".ddev")
}
// GetDocroot returns the docroot path for ddev app
func (app DdevApp) GetDocroot() string {
return app.Docroot
}
// GetComposerRoot will determine the absolute composer root directory where
// all Composer related commands will be executed.
// If inContainer set to true, the absolute path in the container will be
// returned, else the absolute path on the host.
// If showWarning set to true, a warning containing the composer root will be
// shown to the user to avoid confusion.
func (app *DdevApp) GetComposerRoot(inContainer, showWarning bool) string {
basePath := ""
if inContainer {
basePath = app.DefaultWorkingDirMap()["web"]
} else {
basePath = app.AppRoot
}
absComposerRoot := path.Join(basePath, app.ComposerRoot)
// If requested, let the user know we are not using the default composer
// root directory to avoid confusion.
if app.ComposerRoot != "" && showWarning {
util.Warning("Using '%s' as composer root directory", absComposerRoot)
}
return absComposerRoot
}
// GetName returns the app's name
func (app *DdevApp) GetName() string {
return app.Name
}
// GetPhpVersion returns the app's php version
func (app *DdevApp) GetPhpVersion() string {
v := nodeps.PHPDefault
if app.PHPVersion != "" {
v = app.PHPVersion
}
return v
}
// GetWebserverType returns the app's webserver type (nginx-fpm/apache-fpm)
func (app *DdevApp) GetWebserverType() string {
v := nodeps.WebserverDefault
if app.WebserverType != "" {
v = app.WebserverType
}
return v
}
// ImportDB takes a source sql dump and imports it to an active site's database container.
func (app *DdevApp) ImportDB(imPath string, extPath string, progress bool, noDrop bool, targetDB string) error {
app.DockerEnv()
dockerutil.CheckAvailableSpace()
if targetDB == "" {
targetDB = "db"
}
var extPathPrompt bool
dbPath, err := os.MkdirTemp(filepath.Dir(app.ConfigPath), ".importdb")
if err != nil {
return err
}
err = os.Chmod(dbPath, 0777)
if err != nil {
return err
}
defer func() {
_ = os.RemoveAll(dbPath)
}()
err = app.ProcessHooks("pre-import-db")
if err != nil {
return err
}
// If they don't provide an import path and we're not on a tty (piped in stuff)
// then prompt for path to db
if imPath == "" && isatty.IsTerminal(os.Stdin.Fd()) {
// ensure we prompt for extraction path if an archive is provided, while still allowing
// non-interactive use of --src flag without providing a --extract-path flag.
if extPath == "" {
extPathPrompt = true
}
output.UserOut.Println("Provide the path to the database you want to import.")
fmt.Print("Pull path: ")
imPath = util.GetInput("")
}
if imPath != "" {
importPath, isArchive, err := appimport.ValidateAsset(imPath, "db")
if err != nil {
if isArchive && extPathPrompt {
output.UserOut.Println("You provided an archive. Do you want to extract from a specific path in your archive? You may leave this blank if you wish to use the full archive contents")
fmt.Print("Archive extraction path:")
extPath = util.GetInput("")
} else {
return fmt.Errorf("Unable to validate import asset %s: %s", imPath, err)
}
}
switch {
case strings.HasSuffix(importPath, "sql.gz") || strings.HasSuffix(importPath, "mysql.gz"):
err = archive.Ungzip(importPath, dbPath)
if err != nil {
return fmt.Errorf("failed to extract provided file: %v", err)
}
case strings.HasSuffix(importPath, "sql.bz2") || strings.HasSuffix(importPath, "mysql.bz2"):
err = archive.UnBzip2(importPath, dbPath)
if err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
case strings.HasSuffix(importPath, "sql.xz") || strings.HasSuffix(importPath, "mysql.xz"):
err = archive.UnXz(importPath, dbPath)
if err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
case strings.HasSuffix(importPath, "zip"):
err = archive.Unzip(importPath, dbPath, extPath)
if err != nil {
return fmt.Errorf("failed to extract provided archive: %v", err)
}
case strings.HasSuffix(importPath, "tar"):
fallthrough
case strings.HasSuffix(importPath, "tar.gz"):
fallthrough
case strings.HasSuffix(importPath, "tar.bz2"):
fallthrough
case strings.HasSuffix(importPath, "tar.xz"):
fallthrough
case strings.HasSuffix(importPath, "tgz"):
err := archive.Untar(importPath, dbPath, extPath)
if err != nil {
return fmt.Errorf("failed to extract provided archive: %v", err)
}
default:
err = fileutil.CopyFile(importPath, filepath.Join(dbPath, "db.sql"))
if err != nil {
return err
}
}
matches, err := filepath.Glob(filepath.Join(dbPath, "*.*sql"))
if err != nil {
return err
}
if len(matches) < 1 {
return fmt.Errorf("no .sql or .mysql files found to import")
}
}
// default insideContainerImportPath is the one mounted from .ddev directory
insideContainerImportPath := path.Join("/mnt/ddev_config/", filepath.Base(dbPath))
// But if we don't have bind mounts, we have to copy dump into the container
if globalconfig.DdevGlobalConfig.NoBindMounts {
dbContainerName := GetContainerName(app, "db")
if err != nil {
return err
}
uid, _, _ := util.GetContainerUIDGid()
// for postgres, must be written with postgres user
if app.Database.Type == nodeps.Postgres {
uid = "999"
}
insideContainerImportPath, _, err = dockerutil.Exec(dbContainerName, "mktemp -d", uid)
if err != nil {
return err
}
insideContainerImportPath = strings.Trim(insideContainerImportPath, "\n")
err = dockerutil.CopyIntoContainer(dbPath, dbContainerName, insideContainerImportPath, "")
if err != nil {
return err
}
}
err = app.MutagenSyncFlush()
if err != nil {
return err
}
// The perl manipulation removes statements like CREATE DATABASE and USE, which
// throw off imports. This is a scary manipulation, as it must not match actual content
// as has actually happened with https://www.ddevhq.org/ddev-local/ddev-local-database-management/
// and in https://github.com/drud/ddev/issues/2787
// The backtick after USE is inserted via fmt.Sprintf argument because it seems there's
// no way to escape a backtick in a string literal.
inContainerCommand := []string{}
preImportSQL := ""
switch app.Database.Type {
case nodeps.MySQL:
fallthrough
case nodeps.MariaDB:
preImportSQL = fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s; GRANT ALL ON %s.* TO 'db'@'%%';", targetDB, targetDB)
if !noDrop {
preImportSQL = fmt.Sprintf("DROP DATABASE IF EXISTS %s; ", targetDB) + preImportSQL
}
// Case for reading from file
inContainerCommand = []string{"bash", "-c", fmt.Sprintf(`set -eu -o pipefail && mysql -uroot -proot -e "%s" && pv %s/*.*sql | perl -p -e 's/^(CREATE DATABASE \/\*|USE %s)[^;]*;//' | mysql %s`, preImportSQL, insideContainerImportPath, "`", targetDB)}
// Alternate case where we are reading from stdin
if imPath == "" && extPath == "" {
inContainerCommand = []string{"bash", "-c", fmt.Sprintf(`set -eu -o pipefail && mysql -uroot -proot -e "%s" && perl -p -e 's/^(CREATE DATABASE \/\*|USE %s)[^;]*;//' | mysql %s`, preImportSQL, "`", targetDB)}
}
case nodeps.Postgres:
preImportSQL = ""
if !noDrop { // Normal case, drop and recreate database
preImportSQL = preImportSQL + fmt.Sprintf(`
DROP DATABASE IF EXISTS %s;
CREATE DATABASE %s;
`, targetDB, targetDB)
} else { // Leave database alone, but create if not exists
preImportSQL = preImportSQL + fmt.Sprintf(`
SELECT 'CREATE DATABASE %s' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '%s')\gexec
`, targetDB, targetDB)
}
preImportSQL = preImportSQL + fmt.Sprintf(`
GRANT ALL PRIVILEGES ON DATABASE %s TO db;`, targetDB)
// If there is no import path, we're getting it from stdin
if imPath == "" && extPath == "" {
inContainerCommand = []string{"bash", "-c", fmt.Sprintf(`set -eu -o pipefail && (echo '%s' | psql -d postgres) && psql -v ON_ERROR_STOP=1 -d %s`, preImportSQL, targetDB)}
} else { // otherwise getting it from mounted file
inContainerCommand = []string{"bash", "-c", fmt.Sprintf(`set -eu -o pipefail && (echo "%s" | psql -q -d postgres -v ON_ERROR_STOP=1) && pv %s/*.*sql | psql -q -v ON_ERROR_STOP=1 %s >/dev/null`, preImportSQL, insideContainerImportPath, targetDB)}
}
}
stdout, stderr, err := app.Exec(&ExecOpts{
Service: "db",
RawCmd: inContainerCommand,
Tty: progress && isatty.IsTerminal(os.Stdin.Fd()),
})
if err != nil {
return fmt.Errorf("failed to import database: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
}
// Wait for import to really complete
if app.Database.Type != nodeps.Postgres {
rowsImported := 0
for i := 0; i < 10; i++ {
stdout, _, err := app.Exec(&ExecOpts{
Cmd: `mysqladmin -uroot -proot extended -r 2>/dev/null | awk -F'|' '/Innodb_rows_inserted/ {print $3}'`,
Service: "db",
})
if err != nil {
util.Warning("mysqladmin command failed: %v", err)
}
stdout = strings.Trim(stdout, "\r\n\t ")
newRowsImported, err := strconv.Atoi(stdout)
if err != nil {
util.Warning("Error converting '%s' to int", stdout)
break
}
// See if mysqld is still importing. If it is, sleep and try again
if newRowsImported == rowsImported {
break
} else {
rowsImported = newRowsImported
time.Sleep(time.Millisecond * 500)
}
}
}
_, err = app.CreateSettingsFile()
if err != nil {
util.Warning("A custom settings file exists for your application, so ddev did not generate one.")
util.Warning("Run 'ddev describe' to find the database credentials for this application.")
}
err = app.PostImportDBAction()
if err != nil {
return fmt.Errorf("failed to execute PostImportDBAction: %v", err)
}
err = fileutil.PurgeDirectory(dbPath)
if err != nil {
return fmt.Errorf("failed to clean up %s after import: %v", dbPath, err)
}
err = app.ProcessHooks("post-import-db")
if err != nil {
return err
}
return nil
}
// ExportDB exports the db, with optional output to a file, default gzip
// targetDB is the db name if not default "db"
func (app *DdevApp) ExportDB(outFile string, compressionType string, targetDB string) error {
app.DockerEnv()
exportCmd := []string{"mysqldump"}
if app.Database.Type == "postgres" {
exportCmd = []string{"pg_dump", "-U", "db"}
}
if targetDB == "" {
targetDB = "db"
}
exportCmd = append(exportCmd, targetDB)
if compressionType != "" {
exportCmd = []string{"bash", "-c", fmt.Sprintf(`set -eu -o pipefail; %s | %s`, strings.Join(exportCmd, " "), compressionType)}
}
opts := &ExecOpts{
Service: "db",
RawCmd: exportCmd,
NoCapture: true,
}
if outFile != "" {
f, err := os.OpenFile(outFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to open %s: %v", outFile, err)
}
opts.Stdout = f
defer func() {
_ = f.Close()
}()
}
stdout, stderr, err := app.Exec(opts)
if err != nil {
return fmt.Errorf("unable to export db: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
}
confMsg := "Wrote database dump from project '" + app.Name + "' database '" + targetDB + "'"
if outFile != "" {
confMsg = confMsg + " to file " + outFile
} else {
confMsg = confMsg + " to stdout"
}
if compressionType != "" {
confMsg = fmt.Sprintf("%s in %s format", confMsg, compressionType)
} else {
confMsg = confMsg + " in plain text format"
}
_, err = fmt.Fprintf(os.Stderr, confMsg+".\n")
return err
}
// SiteStatus returns the current status of an application determined from web and db service health.
func (app *DdevApp) SiteStatus() (string, string) {
if !fileutil.FileExists(app.GetAppRoot()) {
return SiteDirMissing, fmt.Sprintf(`%s: %v; Please "ddev stop --unlist %s"`, SiteDirMissing, app.GetAppRoot(), app.Name)
}
_, err := CheckForConf(app.GetAppRoot())
if err != nil {
return SiteConfigMissing, fmt.Sprintf("%s", SiteConfigMissing)
}
statuses := map[string]string{"web": ""}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
statuses["db"] = ""
}
for service := range statuses {
container, err := app.FindContainerByType(service)
if err != nil {
util.Error("app.FindContainerByType(%v) failed", service)
return "", ""
}
if container == nil {
statuses[service] = SiteStopped
} else {
status, _ := dockerutil.GetContainerHealth(container)
switch status {
case "exited":
statuses[service] = SitePaused
case "healthy":
statuses[service] = SiteRunning
case "starting":
statuses[service] = SiteStarting
default:
statuses[service] = status
}
}
}
siteStatusDesc := ""
for serviceName, status := range statuses {
if status != statuses["web"] {
siteStatusDesc += serviceName + ": " + status + "\n"
}
}
// Base the siteStatus on web container. Then override it if others are not the same.
if siteStatusDesc == "" {
return app.determineStatus(statuses), statuses["web"]
}
return app.determineStatus(statuses), siteStatusDesc
}
// Return one of the Site* statuses to describe the overall status of the project
func (app *DdevApp) determineStatus(statuses map[string]string) string {
hasCommonStatus, commonStatus := app.getCommonStatus(statuses)
if hasCommonStatus {
return commonStatus
}
for status := range statuses {
if status == SiteStarting {
return SiteStarting
}
}
return SiteUnhealthy
}
// Check whether a common status applies to all services
func (app *DdevApp) getCommonStatus(statuses map[string]string) (bool, string) {
commonStatus := ""
for _, status := range statuses {
if commonStatus != "" && status != commonStatus {
return false, ""
}
commonStatus = status
}
return true, commonStatus
}
// ImportFiles takes a source directory or archive and copies to the uploaded files directory of a given app.
func (app *DdevApp) ImportFiles(importPath string, extPath string) error {
app.DockerEnv()
if err := app.ProcessHooks("pre-import-files"); err != nil {
return err
}
if err := app.ImportFilesAction(importPath, extPath); err != nil {
return err
}
//nolint: revive
if err := app.ProcessHooks("post-import-files"); err != nil {
return err
}
return nil
}
// ComposeFiles returns a list of compose files for a project.
// It has to put the .ddev/docker-compose.*.y*ml first
// It has to put the docker-compose.override.y*l last
func (app *DdevApp) ComposeFiles() ([]string, error) {
origDir, _ := os.Getwd()
defer func() {
_ = os.Chdir(origDir)
}()
err := os.Chdir(app.AppConfDir())
if err != nil {
return nil, err
}
files, err := filepath.Glob("docker-compose.*.y*ml")
if err != nil {
return []string{}, fmt.Errorf("unable to glob docker-compose.*.y*ml in %s: err=%v", app.AppConfDir(), err)
}
mainFile := app.DockerComposeYAMLPath()
if !fileutil.FileExists(mainFile) {
return nil, fmt.Errorf("failed to find %s", mainFile)
}
overrides, err := filepath.Glob("docker-compose.override.y*ml")
util.CheckErr(err)
orderedFiles := make([]string, 1)
// Make sure the main file goes first
orderedFiles[0] = mainFile
for _, file := range files {
// We already have the main file, and it's not in the list anyway, so skip when we hit it.
// We'll add the override later, so skip it.
if len(overrides) == 1 && file == overrides[0] {
continue
}
orderedFiles = append(orderedFiles, app.GetConfigPath(file))
}
if len(overrides) == 1 {
orderedFiles = append(orderedFiles, app.GetConfigPath(overrides[0]))
}
return orderedFiles, nil
}
// ProcessHooks executes Tasks defined in Hooks
func (app *DdevApp) ProcessHooks(hookName string) error {
if cmds := app.Hooks[hookName]; len(cmds) > 0 {
output.UserOut.Debugf("Executing %s hook...", hookName)
}
for _, c := range app.Hooks[hookName] {
a := NewTask(app, c)
if a == nil {
return fmt.Errorf("unable to create task from %v", c)
}
if hookName == "pre-start" {
for k := range c {
if k == "exec" || k == "composer" {
return fmt.Errorf("pre-start hooks cannot contain %v", k)
}
}
}
output.UserOut.Debugf("=== Running task: %s, output below", a.GetDescription())
err := a.Execute()
if err != nil {
if app.FailOnHookFail || app.FailOnHookFailGlobal {
output.UserOut.Errorf("Task failed: %v: %v", a.GetDescription(), err)
return fmt.Errorf("task failed: %v", err)
}
output.UserOut.Errorf("Task failed: %v: %v", a.GetDescription(), err)
output.UserOut.Warn("A task failure does not mean that ddev failed, but your hook configuration has a command that failed.")
}
}
return nil
}
// GetDBImage uses the available version info
func (app *DdevApp) GetDBImage() string {
dbImage := versionconstants.GetDBImage(app.Database.Type, app.Database.Version)
return dbImage
}
// Start initiates docker-compose up
func (app *DdevApp) Start() error {
var err error
if app.IsMutagenEnabled() && globalconfig.DdevGlobalConfig.UseHardenedImages {
return fmt.Errorf("mutagen-enabled is not compatible with use-hardened-images")
}
app.DockerEnv()
dockerutil.EnsureDdevNetwork()
volumesNeeded := []string{"ddev-global-cache", "ddev-" + app.Name + "-snapshots"}
for _, v := range volumesNeeded {
_, err = dockerutil.CreateVolume(v, "local", nil)
if err != nil {
return fmt.Errorf("unable to create docker volume %s: %v", v, err)
}
}
err = app.CheckExistingAppInApproot()
if err != nil {
return err
}
// This is done early here so users won't see gitignored contents of .ddev for too long
// It also gets done by `ddev config`
err = PrepDdevDirectory(filepath.Dir(app.ConfigPath))
if err != nil {
util.Warning("Unable to PrepDdevDirectory: %v", err)
}
// The .ddev directory may still need to be populated, especially in tests
err = PopulateExamplesCommandsHomeadditions(app.Name)
if err != nil {
return err
}
// Make sure that any ports allocated are available.
// and of course add to global project list as well
err = app.UpdateGlobalProjectList()
if err != nil {
return err
}
err = DownloadMutagenIfNeeded(app)
if err != nil {
return err
}
err = app.ProcessHooks("pre-start")
if err != nil {
return err
}
err = app.GenerateWebserverConfig()
if err != nil {
return err
}
err = app.GeneratePostgresConfig()
if err != nil {
return err
}
err = app.PullBaseContainerImages()
if err != nil {
util.Warning("Unable to pull docker images: %v", err)
}
dockerutil.CheckAvailableSpace()
// Copy any homeadditions content into .ddev/.homeadditions
tmpHomeadditionsPath := app.GetConfigPath(".homeadditions")
err = os.RemoveAll(tmpHomeadditionsPath)
if err != nil {
util.Warning("unable to remove %s: %v", tmpHomeadditionsPath, err)
}
globalHomeadditionsPath := filepath.Join(globalconfig.GetGlobalDdevDir(), "homeadditions")
if fileutil.IsDirectory(globalHomeadditionsPath) {
err = copy.Copy(globalHomeadditionsPath, tmpHomeadditionsPath)
if err != nil {
return err
}
}
projectHomeAdditionsPath := app.GetConfigPath("homeadditions")
if fileutil.IsDirectory(projectHomeAdditionsPath) {
err = copy.Copy(projectHomeAdditionsPath, tmpHomeadditionsPath)
if err != nil {
return err
}
}
// Make sure that important volumes to mount already have correct ownership set
// Additional volumes can be added here. This allows us to run a single privileged
// container with a single focus of changing ownership, instead of having to use sudo
// inside the container
uid, _, _ := util.GetContainerUIDGid()
if globalconfig.DdevGlobalConfig.NoBindMounts {
err = dockerutil.CopyIntoVolume(app.GetConfigPath(""), app.Name+"-ddev-config", "", uid, "db_snapshots", true)
if err != nil {
return fmt.Errorf("failed to copy project .ddev directory to volume: %v", err)
}
}
_, out, err := dockerutil.RunSimpleContainer(versionconstants.GetWebImage(), "", []string{"sh", "-c", fmt.Sprintf("chown -R %s /var/lib/mysql /mnt/ddev-global-cache", uid)}, []string{}, []string{}, []string{app.GetMariaDBVolumeName() + ":/var/lib/mysql", "ddev-global-cache:/mnt/ddev-global-cache"}, "", true, false, nil)
if err != nil {
return fmt.Errorf("failed to RunSimpleContainer to chown volumes: %v, output=%s", err, out)
}
// Chown the postgres volume; this shouldn't have to be a separate stanza, but the
// uid is 999 instead of current user
if app.Database.Type == nodeps.Postgres {
_, out, err := dockerutil.RunSimpleContainer(versionconstants.GetWebImage(), "", []string{"sh", "-c", fmt.Sprintf("chown -R %s /var/lib/postgresql/data", "999:999")}, []string{}, []string{}, []string{app.GetPostgresVolumeName() + ":/var/lib/postgresql/data"}, "", true, false, nil)
if err != nil {
return fmt.Errorf("failed to RunSimpleContainer to chown postgres volume: %v, output=%s", err, out)
}
}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "ddev-ssh-agent") {
err = app.EnsureSSHAgentContainer()
if err != nil {
return err
}
}
// Warn the user if there is any custom configuration in use.
app.CheckCustomConfig()
// Warn user if there are deprecated items used in the config
app.CheckDeprecations()
// Fix any obsolete things like old shell commands, etc.
app.FixObsolete()
if !IsRouterDisabled(app) {
caRoot := globalconfig.GetCAROOT()
if caRoot == "" {
util.Warning("mkcert may not be properly installed, we suggest installing it for trusted https support, `brew install mkcert nss`, `choco install -y mkcert`, etc. and then `mkcert -install`")
}
router, _ := FindDdevRouter()
// If the router doesn't exist, go ahead and push mkcert root ca certs into the ddev-global-cache/mkcert
// This will often be redundant
if router == nil {
// Copy ca certs into ddev-global-cache/mkcert
if caRoot != "" {
uid, _, _ := util.GetContainerUIDGid()
err = dockerutil.CopyIntoVolume(caRoot, "ddev-global-cache", "mkcert", uid, "", false)
if err != nil {
util.Warning("failed to copy root CA into docker volume ddev-global-cache/mkcert: %v", err)
} else {
util.Success("Pushed mkcert rootca certs to ddev-global-cache/mkcert")
}
}
}
certPath := app.GetConfigPath("custom_certs")
if fileutil.FileExists(certPath) {
uid, _, _ := util.GetContainerUIDGid()
err = dockerutil.CopyIntoVolume(certPath, "ddev-global-cache", "custom_certs", uid, "", false)
if err != nil {
util.Warning("failed to copy custom certs into docker volume ddev-global-cache/custom_certs: %v", err)
} else {
util.Success("Copied custom certs in %s to ddev-global-cache/custom_certs", certPath)
}
}
}
// WriteConfig .ddev-docker-compose-*.yaml
err = app.WriteDockerComposeYAML()
if err != nil {
return err
}
// This needs to be done after WriteDockerComposeYAML() to get the right images
err = app.PullContainerImages()
if err != nil {
util.Warning("Unable to pull docker images: %v", err)
}
err = app.CheckAddonIncompatibilities()
if err != nil {
return err
}
err = app.AddHostsEntriesIfNeeded()
if err != nil {
return err
}
// Delete the NFS volumes before we bring up docker-compose (and will be created again)
// We don't care if the volume wasn't there
_ = dockerutil.RemoveVolume(app.GetNFSMountVolumeName())
// The db_snapshots subdirectory may be created on docker-compose up, so
// we need to precreate it so permissions are correct (and not root:root)
if !fileutil.IsDirectory(app.GetConfigPath("db_snapshots")) {
err = os.MkdirAll(app.GetConfigPath("db_snapshots"), 0777)
if err != nil {
return err
}
}
// db_snapshots gets mounted into container, may have different user/group, so need 777
err = os.Chmod(app.GetConfigPath("db_snapshots"), 0777)
if err != nil {
return err
}
util.Debug("Executing docker-compose -f %s up --build -d", app.DockerComposeFullRenderedYAMLPath())
_, _, err = dockerutil.ComposeCmd([]string{app.DockerComposeFullRenderedYAMLPath()}, "up", "--build", "-d")
if err != nil {
return err
}
if app.IsMutagenEnabled() {
// Must wait for web container to be healthy before fiddling with mutagen
err = app.Wait([]string{"web"})
if err != nil {
return fmt.Errorf("web container failed to become ready: %v", err)
}
mounted, err := IsMutagenVolumeMounted(app)
if err != nil {
return err
}
if !mounted {
util.Failed("Mutagen docker volume is not mounted. Please use `ddev restart`")
}
output.UserOut.Printf("Starting mutagen sync process... This can take some time.")
mutagenDuration := util.ElapsedDuration(time.Now())
err = app.GenerateMutagenYml()
if err != nil {
return err
}
_ = TerminateMutagenSync(app)
err = SetMutagenVolumeOwnership(app)
if err != nil {
return err
}
err = CreateMutagenSync(app)
if err != nil {
return errors.Errorf("Failed to create mutagen sync session %s. You may be able to resolve this problem 'ddev mutagen reset' (err=%v)", MutagenSyncName(app.Name), err)
}
mStatus, _, _, err := app.MutagenStatus()
if err != nil {
return err
}
dur := util.FormatDuration(mutagenDuration())
if mStatus == "ok" {
util.Success("Mutagen sync flush completed in %s.\nFor details on sync status 'ddev mutagen status %s --verbose'", dur, MutagenSyncName(app.Name))
} else {
util.Error("Mutagen sync completed with problems in %s.\nFor details on sync status 'ddev mutagen status %s --verbose'", dur, MutagenSyncName(app.Name))
}
}
if !IsRouterDisabled(app) {
err = StartDdevRouter()
if err != nil {
return err
}
}
err = app.WaitByLabels(map[string]string{"com.ddev.site-name": app.GetName()})
if err != nil {
return err
}
if _, err = app.CreateSettingsFile(); err != nil {
return fmt.Errorf("failed to write settings file %s: %v", app.SiteDdevSettingsFile, err)
}
err = app.PostStartAction()
if err != nil {
return err
}
err = app.ProcessHooks("post-start")
if err != nil {
return err
}
return nil
}
// Restart does a Stop() and a Start
func (app *DdevApp) Restart() error {
err := app.Stop(false, false)
if err != nil {
return err
}
err = app.Start()
return err
}
// PullContainerImages configured docker images with full output, since docker-compose up doesn't have nice output
func (app *DdevApp) PullContainerImages() error {
images, err := app.FindAllImages()
if err != nil {
return err
}
images = append(images, versionconstants.GetRouterImage(), versionconstants.GetSSHAuthImage())
for _, i := range images {
err := dockerutil.Pull(i)
if err != nil {
return err
}
if globalconfig.DdevDebug {
output.UserOut.Printf("Pulling image for %s", i)
}
}
return nil
}
// PullCBaseontainerImages pulls only the fundamentally needed images so they can be available early
// We always need web image and busybox just for housekeeping.
func (app *DdevApp) PullBaseContainerImages() error {
images := []string{versionconstants.GetWebImage(), versionconstants.BusyboxImage}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), SSHAuthName) {
images = append(images, versionconstants.GetSSHAuthImage())
}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), RouterProjectName) {
images = append(images, versionconstants.GetRouterImage())
}
for _, i := range images {
err := dockerutil.Pull(i)
if err != nil {
return err
}
if globalconfig.DdevDebug {
output.UserOut.Printf("Pulling image for %s", i)
}
}
return nil
}
// FindAllImages returns an array of image tags for all containers in the compose file
func (app *DdevApp) FindAllImages() ([]string, error) {
var images []string
if app.ComposeYaml == nil {
return images, nil
}
if y, ok := app.ComposeYaml["services"]; ok {
for _, v := range y.(map[interface{}]interface{}) {
if i, ok := v.(map[interface{}]interface{})["image"]; ok {
if strings.HasSuffix(i.(string), "-built") {
i = strings.TrimSuffix(i.(string), "-built")
if strings.HasSuffix(i.(string), "-"+app.Name) {
i = strings.TrimSuffix(i.(string), "-"+app.Name)
}
}
images = append(images, i.(string))
}
}
}
return images, nil
}
// CheckExistingAppInApproot looks to see if we already have a project in this approot with different name
func (app *DdevApp) CheckExistingAppInApproot() error {
pList := globalconfig.GetGlobalProjectList()
for name, v := range pList {
if app.AppRoot == v.AppRoot && name != app.Name {
return fmt.Errorf(`this project root %s already contains a project named %s. You may want to remove the existing project with "ddev stop --unlist %s"`, v.AppRoot, name, name)
}
}
return nil
}
//go:embed webserver_config_assets
var webserverConfigAssets embed.FS
// GenerateWebserverConfig generates the default nginx and apache config files
func (app *DdevApp) GenerateWebserverConfig() error {
// Prevent running as root for most cases
// We really don't want ~/.ddev to have root ownership, breaks things.
if os.Geteuid() == 0 {
util.Warning("not generating webserver config files because running with root privileges")
return nil
}
var items = map[string]string{
"nginx": app.GetConfigPath(filepath.Join("nginx_full", "nginx-site.conf")),
"apache": app.GetConfigPath(filepath.Join("apache", "apache-site.conf")),
"nginx_second_docroot_example": app.GetConfigPath(filepath.Join("nginx_full", "seconddocroot.conf.example")),
"README.nginx_full.txt": app.GetConfigPath(filepath.Join("nginx_full", "README.nginx_full.txt")),
"README.apache.txt": app.GetConfigPath(filepath.Join("apache", "README.apache.txt")),
"apache_second_docroot_example": app.GetConfigPath(filepath.Join("apache", "seconddocroot.conf.example")),
}
for t, configPath := range items {
err := os.MkdirAll(filepath.Dir(configPath), 0755)
if err != nil {
return err
}
if fileutil.FileExists(configPath) {
sigExists, err := fileutil.FgrepStringInFile(configPath, nodeps.DdevFileSignature)
if err != nil {
return err
}
// If the signature doesn't exist, they have taken over the file, so return
if !sigExists {
return nil
}
}
cfgFile := fmt.Sprintf("%s-site-%s.conf", t, app.Type)
c, err := webserverConfigAssets.ReadFile(path.Join("webserver_config_assets", cfgFile))
if err != nil {
c, err = webserverConfigAssets.ReadFile(path.Join("webserver_config_assets", fmt.Sprintf("%s-site-php.conf", t)))
if err != nil {
return err
}
}
content := string(c)
docroot := path.Join("/var/www/html", app.Docroot)
err = fileutil.TemplateStringToFile(content, map[string]interface{}{"Docroot": docroot}, configPath)
if err != nil {
return err
}
}
return nil
}
func (app *DdevApp) GeneratePostgresConfig() error {
if app.Database.Type != nodeps.Postgres {
return nil
}
// Prevent running as root for most cases
// We really don't want ~/.ddev to have root ownership, breaks things.
if os.Geteuid() == 0 {
util.Warning("not generating postgres config files because running with root privileges")
return nil
}
var items = map[string]string{
"postgresql.conf": app.GetConfigPath(filepath.Join("postgres", "postgresql.conf")),
}
for _, configPath := range items {
err := os.MkdirAll(filepath.Dir(configPath), 0755)
if err != nil {
return err
}
if fileutil.FileExists(configPath) {
err = os.Chmod(configPath, 0666)
if err != nil {
return err
}
sigExists, err := fileutil.FgrepStringInFile(configPath, nodeps.DdevFileSignature)
if err != nil {
return err
}
// If the signature doesn't exist, they have taken over the file, so return
if !sigExists {
return nil
}
}
c, err := bundledAssets.ReadFile(path.Join("postgres", app.Database.Version, "postgresql.conf"))
if err != nil {
return err
}
err = fileutil.TemplateStringToFile(string(c), nil, configPath)
if err != nil {
return err
}
err = os.Chmod(configPath, 0666)
if err != nil {
return err
}
}
return nil
}
// ExecOpts contains options for running a command inside a container
type ExecOpts struct {
// Service is the service, as in 'web', 'db', 'dba'
Service string
// Dir is the full path to the working directory inside the container
Dir string
// Cmd is the string to execute via bash/sh
Cmd string
// RawCmd is the array to execute if not using
RawCmd []string
// Nocapture if true causes use of ComposeNoCapture, so the stdout and stderr go right to stdout/stderr
NoCapture bool
// Tty if true causes a tty to be allocated
Tty bool
// Stdout can be overridden with a File
Stdout *os.File
// Stderr can be overridden with a File
Stderr *os.File
}
// Exec executes a given command in the container of given type without allocating a pty
// Returns ComposeCmd results of stdout, stderr, err
// If Nocapture arg is true, stdout/stderr will be empty and output directly to stdout/stderr
func (app *DdevApp) Exec(opts *ExecOpts) (string, string, error) {
app.DockerEnv()
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("app.Exec %v", opts))
defer runTime()
if opts.Cmd == "" && len(opts.RawCmd) == 0 {
return "", "", fmt.Errorf("no command provided")
}
if opts.Service == "" {
opts.Service = "web"
}
state, err := dockerutil.GetContainerStateByName(fmt.Sprintf("ddev-%s-%s", app.Name, opts.Service))
if err != nil || state != "running" {
if state == "doesnotexist" {
return "", "", fmt.Errorf("service %s does not exist in project %s (state=%s)", opts.Service, app.Name, state)
}
return "", "", fmt.Errorf("service %s is not currently running in project %s (state=%s), use `ddev logs -s %s` to see what happened to it", opts.Service, app.Name, state, opts.Service)
}
err = app.ProcessHooks("pre-exec")
if err != nil {
return "", "", fmt.Errorf("failed to process pre-exec hooks: %v", err)
}
baseComposeExecCmd := []string{"exec"}
if opts.Dir != "" {
baseComposeExecCmd = append(baseComposeExecCmd, "-w", opts.Dir)
}
if !isatty.IsTerminal(os.Stdin.Fd()) || !opts.Tty {
baseComposeExecCmd = append(baseComposeExecCmd, "-T")
}
baseComposeExecCmd = append(baseComposeExecCmd, opts.Service)
// Cases to handle
// - Free form, all unquoted. Like `ls -l -a`
// - Quoted to delay pipes and other features to container, like `"ls -l -a | grep junk"`
// Note that a set quoted on the host in ddev e will come through as a single arg
if len(opts.RawCmd) == 0 { // Use opts.Cmd and prepend with bash
// Use bash for our containers, sh for 3rd-party containers
// that may not have bash.
shell := "bash"
if !nodeps.ArrayContainsString([]string{"web", "db", "dba"}, opts.Service) {
shell = "sh"
}
errcheck := "set -eu"
opts.RawCmd = []string{shell, "-c", errcheck + ` && ( ` + opts.Cmd + `)`}
}
files := []string{app.DockerComposeFullRenderedYAMLPath()}
if err != nil {
return "", "", err
}
stdout := os.Stdout
stderr := os.Stderr
if opts.Stdout != nil {
stdout = opts.Stdout
}
if opts.Stderr != nil {
stderr = opts.Stderr
}
var stdoutResult, stderrResult string
var outRes, errRes string
r := append(baseComposeExecCmd, opts.RawCmd...)
if opts.NoCapture || opts.Tty {
err = dockerutil.ComposeWithStreams(files, os.Stdin, stdout, stderr, r...)
} else {
outRes, errRes, err = dockerutil.ComposeCmd([]string{app.DockerComposeFullRenderedYAMLPath()}, r...)
stdoutResult = outRes
stderrResult = errRes
}
if err != nil {
return stdoutResult, stderrResult, err
}
hookErr := app.ProcessHooks("post-exec")
if hookErr != nil {
return stdoutResult, stderrResult, fmt.Errorf("failed to process post-exec hooks: %v", hookErr)
}
return stdoutResult, stderrResult, err
}
// ExecWithTty executes a given command in the container of given type.
// It allocates a pty for interactive work.
func (app *DdevApp) ExecWithTty(opts *ExecOpts) error {
app.DockerEnv()
if opts.Service == "" {
opts.Service = "web"
}
state, err := dockerutil.GetContainerStateByName(fmt.Sprintf("ddev-%s-%s", app.Name, opts.Service))
if err != nil || state != "running" {
return fmt.Errorf("service %s is not current running in project %s (state=%s)", opts.Service, app.Name, state)
}
args := []string{"exec"}
// In the case where this is being used without an available tty,
// make sure we use the -T to turn off tty to avoid panic in docker-compose v2.2.3
// see https://stackoverflow.com/questions/70855915/fix-panic-provided-file-is-not-a-console-from-docker-compose-in-github-action
if !term.IsTerminal(int(os.Stdin.Fd())) {
args = append(args, "-T")
}
if opts.Dir != "" {
args = append(args, "-w", opts.Dir)
}
args = append(args, opts.Service)
if opts.Cmd == "" {
return fmt.Errorf("no command provided")
}
// Cases to handle
// - Free form, all unquoted. Like `ls -l -a`
// - Quoted to delay pipes and other features to container, like `"ls -l -a | grep junk"`
// Note that a set quoted on the host in ddev exec will come through as a single arg
// Use bash for our containers, sh for 3rd-party containers
// that may not have bash.
shell := "bash"
if !nodeps.ArrayContainsString([]string{"web", "db", "dba"}, opts.Service) {
shell = "sh"
}
args = append(args, shell, "-c", opts.Cmd)
return dockerutil.ComposeWithStreams([]string{app.DockerComposeFullRenderedYAMLPath()}, os.Stdin, os.Stdout, os.Stderr, args...)
}
func (app *DdevApp) ExecOnHostOrService(service string, cmd string) error {
var err error
// Handle case on host
if service == "host" {
cwd, _ := os.Getwd()
err = os.Chdir(app.GetAppRoot())
if err != nil {
return fmt.Errorf("unable to GetAppRoot: %v", err)
}
bashPath := "bash"
if runtime.GOOS == "windows" {
bashPath = util.FindBashPath()
if bashPath == "" {
return fmt.Errorf("unable to find bash.exe on Windows")
}
}
args := []string{
"-c",
cmd,
}
app.DockerEnv()
err = exec.RunInteractiveCommand(bashPath, args)
_ = os.Chdir(cwd)
} else { // handle case in container
_, _, err = app.Exec(
&ExecOpts{
Service: service,
Cmd: cmd,
Tty: isatty.IsTerminal(os.Stdin.Fd()),
})
}
return err
}
// Logs returns logs for a site's given container.
// See docker.LogsOptions for more information about valid tailLines values.
func (app *DdevApp) Logs(service string, follow bool, timestamps bool, tailLines string) error {
client := dockerutil.GetDockerClient()
var container *docker.APIContainers
var err error
// Let people access ddev-router and ddev-ssh-agent logs as well.
if service == "ddev-router" || service == "ddev-ssh-agent" {
container, err = dockerutil.FindContainerByLabels(map[string]string{"com.docker.compose.service": service})
} else {
container, err = app.FindContainerByType(service)
}
if err != nil {
return err
}
if container == nil {
util.Warning("No running service container %s was found", service)
return nil
}
logOpts := docker.LogsOptions{
Container: container.ID,
Stdout: true,
Stderr: true,
OutputStream: output.UserOut.Out,
ErrorStream: output.UserOut.Out,
Follow: follow,
Timestamps: timestamps,
}
if tailLines != "" {
logOpts.Tail = tailLines
}
err = client.Logs(logOpts)
if err != nil {
return err
}
return nil
}
// CaptureLogs returns logs for a site's given container.
// See docker.LogsOptions for more information about valid tailLines values.
func (app *DdevApp) CaptureLogs(service string, timestamps bool, tailLines string) (string, error) {
client := dockerutil.GetDockerClient()
var container *docker.APIContainers
var err error
// Let people access ddev-router and ddev-ssh-agent logs as well.
if service == "ddev-router" || service == "ddev-ssh-agent" {
container, err = dockerutil.FindContainerByLabels(map[string]string{"com.docker.compose.service": service})
} else {
container, err = app.FindContainerByType(service)
}
if err != nil {
return "", err
}
if container == nil {
util.Warning("No running service container %s was found", service)
return "", nil
}
var out bytes.Buffer
logOpts := docker.LogsOptions{
Container: container.ID,
Stdout: true,
Stderr: true,
OutputStream: &out,
ErrorStream: &out,
Follow: false,
Timestamps: timestamps,
}
if tailLines != "" {
logOpts.Tail = tailLines
}
err = client.Logs(logOpts)
if err != nil {
return "", err
}
return out.String(), nil
}
// DockerEnv sets environment variables for a docker-compose run.
func (app *DdevApp) DockerEnv() {
uidStr, gidStr, _ := util.GetContainerUIDGid()
// Warn about running as root if we're not on Windows.
if uidStr == "0" || gidStr == "0" {
util.Warning("Warning: containers will run as root. This could be a security risk on Linux.")
}
isGitpod := "false"
// For gitpod,
// * provide IS_GITPOD environment variable
// * provide default host-side port bindings, assuming only one project running,
// as is usual on gitpod, but if more than one project, can override with normal
// config.yaml settings.
if nodeps.IsGitpod() {
isGitpod = "true"
if app.HostWebserverPort == "" {
app.HostWebserverPort = "8080"
}
if app.HostHTTPSPort == "" {
app.HostHTTPSPort = "8443"
}
if app.HostDBPort == "" {
app.HostDBPort = "3306"
}
if app.HostMailhogPort == "" {
app.HostMailhogPort = "8027"
}
if app.HostPHPMyAdminPort == "" {
app.HostPHPMyAdminPort = "8036"
}
app.BindAllInterfaces = true
}
isWSL2 := "false"
if nodeps.IsWSL2() {
isWSL2 = "true"
}
// DDEV_HOST_DB_PORT is actually used for 2 things.
// 1. To specify via base docker-compose file the value of host_db_port config. And it's expected to be empty
// there if the host_db_port is empty.
// 2. To tell custom commands the db port. And it's expected always to be populated for them.
dbPort, err := app.GetPublishedPort("db")
dbPortStr := strconv.Itoa(dbPort)
if dbPortStr == "-1" || err != nil {
dbPortStr = ""
}
if app.HostDBPort != "" {
dbPortStr = app.HostDBPort
}
envVars := map[string]string{
// Without COMPOSE_DOCKER_CLI_BUILD=0, docker-compose makes all kinds of mess
// of output. BUILDKIT_PROGRESS doesn't help either.
"COMPOSE_DOCKER_CLI_BUILD": "0",
// The compose project name can no longer contain dots
// https://github.com/compose-spec/compose-go/pull/197
"COMPOSE_PROJECT_NAME": "ddev-" + strings.Replace(app.Name, `.`, "", -1),
"COMPOSE_CONVERT_WINDOWS_PATHS": "true",
"DDEV_SITENAME": app.Name,
"DDEV_TLD": app.ProjectTLD,
"DDEV_DBIMAGE": app.GetDBImage(),
"DDEV_DBAIMAGE": versionconstants.GetDBAImage(),
"DDEV_PROJECT": app.Name,
"DDEV_WEBIMAGE": app.WebImage,
"DDEV_APPROOT": app.AppRoot,
"DDEV_FILES_DIR": app.GetContainerUploadDirFullPath(),
"DDEV_HOST_DB_PORT": dbPortStr,
"DDEV_HOST_WEBSERVER_PORT": app.HostWebserverPort,
"DDEV_HOST_HTTPS_PORT": app.HostHTTPSPort,
"DDEV_PHPMYADMIN_PORT": app.PHPMyAdminPort,
"DDEV_PHPMYADMIN_HTTPS_PORT": app.PHPMyAdminHTTPSPort,
"DDEV_MAILHOG_PORT": app.MailhogPort,
"DDEV_MAILHOG_HTTPS_PORT": app.MailhogHTTPSPort,
"DDEV_DOCROOT": app.Docroot,
"DDEV_HOSTNAME": app.HostName(),
"DDEV_UID": uidStr,
"DDEV_GID": gidStr,
"DDEV_PHP_VERSION": app.PHPVersion,
"DDEV_WEBSERVER_TYPE": app.WebserverType,
"DDEV_PROJECT_TYPE": app.Type,
"DDEV_ROUTER_HTTP_PORT": app.RouterHTTPPort,
"DDEV_ROUTER_HTTPS_PORT": app.RouterHTTPSPort,
"DDEV_XDEBUG_ENABLED": strconv.FormatBool(app.XdebugEnabled),
"DDEV_PRIMARY_URL": app.GetPrimaryURL(),
"DOCKER_SCAN_SUGGEST": "false",
"IS_DDEV_PROJECT": "true",
"IS_GITPOD": isGitpod,
"IS_WSL2": isWSL2,
}
// Set the DDEV_DB_CONTAINER_COMMAND command to empty to prevent docker-compose from complaining normally.
// It's used for special startup on restoring to a snapshot or for postgres.
if len(os.Getenv("DDEV_DB_CONTAINER_COMMAND")) == 0 {
v := ""
if app.Database.Type == nodeps.Postgres { // config_file spec for postgres
v = fmt.Sprintf("-c config_file=%s/postgresql.conf -c hba_file=%s/pg_hba.conf", nodeps.PostgresConfigDir, nodeps.PostgresConfigDir)
}
envVars["DDEV_DB_CONTAINER_COMMAND"] = v
}
// Find out terminal dimensions
columns, lines := nodeps.GetTerminalWidthHeight()
envVars["COLUMNS"] = strconv.Itoa(columns)
envVars["LINES"] = strconv.Itoa(lines)
if len(app.AdditionalHostnames) > 0 || len(app.AdditionalFQDNs) > 0 {
envVars["DDEV_HOSTNAME"] = strings.Join(app.GetHostnames(), ",")
}
// Only set values if they don't already exist in env.
for k, v := range envVars {
if err := os.Setenv(k, v); err != nil {
util.Error("Failed to set the environment variable %s=%s: %v", k, v, err)
}
}
}
// Pause initiates docker-compose stop
func (app *DdevApp) Pause() error {
app.DockerEnv()
status, _ := app.SiteStatus()
if status == SiteStopped {
return nil
}
err := app.ProcessHooks("pre-pause")
if err != nil {
return err
}
_ = SyncAndTerminateMutagenSession(app)
if _, _, err := dockerutil.ComposeCmd([]string{app.DockerComposeFullRenderedYAMLPath()}, "stop"); err != nil {
return err
}
err = app.ProcessHooks("post-pause")
if err != nil {
return err
}
return StopRouterIfNoContainers()
}
// WaitForServices waits for all the services in docker-compose to come up
func (app *DdevApp) WaitForServices() error {
var requiredContainers []string
if services, ok := app.ComposeYaml["services"].(map[interface{}]interface{}); ok {
for k := range services {
requiredContainers = append(requiredContainers, k.(string))
}
} else {
util.Failed("unable to get required startup services to wait for")
}
output.UserOut.Printf("Waiting for these services to become ready: %v", requiredContainers)
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
}
waitTime := containerWaitTimeout
_, err := dockerutil.ContainerWait(waitTime, labels)
if err != nil {
return fmt.Errorf("timed out waiting for containers (%v) to start: err=%v", requiredContainers, err)
}
return nil
}
// Wait ensures that the app service containers are healthy.
func (app *DdevApp) Wait(requiredContainers []string) error {
for _, containerType := range requiredContainers {
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
"com.docker.compose.service": containerType,
}
waitTime := containerWaitTimeout
logOutput, err := dockerutil.ContainerWait(waitTime, labels)
if err != nil {
return fmt.Errorf("%s container failed: log=%s, err=%v", containerType, logOutput, err)
}
}
return nil
}
// WaitByLabels waits for containers found by list of labels to be
// ready
func (app *DdevApp) WaitByLabels(labels map[string]string) error {
waitTime := containerWaitTimeout
err := dockerutil.ContainersWait(waitTime, labels)
if err != nil {
return fmt.Errorf("container(s) failed to become healthy after %d seconds. This may be just a problem with the healthcheck and not a functional problem. %v", waitTime, err)
}
return nil
}
// StartAndWait is primarily for use in tests.
// It does app.Start() but then waits for extra seconds
// before returning.
// extraSleep arg in seconds is the time to wait if > 0
func (app *DdevApp) StartAndWait(extraSleep int) error {
err := app.Start()
if err != nil {
return err
}
if extraSleep > 0 {
time.Sleep(time.Duration(extraSleep) * time.Second)
}
return nil
}
// DetermineSettingsPathLocation figures out the path to the settings file for
// an app based on the contents/existence of app.SiteSettingsPath and
// app.SiteDdevSettingsFile.
func (app *DdevApp) DetermineSettingsPathLocation() (string, error) {
possibleLocations := []string{app.SiteSettingsPath, app.SiteDdevSettingsFile}
for _, loc := range possibleLocations {
// If the file doesn't exist, it's safe to use
if !fileutil.FileExists(loc) {
return loc, nil
}
// If the file does exist, check for a signature indicating it's managed by ddev.
signatureFound, err := fileutil.FgrepStringInFile(loc, nodeps.DdevFileSignature)
util.CheckErr(err) // Really can't happen as we already checked for the file existence
// If the signature was found, it's safe to use.
if signatureFound {
return loc, nil
}
}
return "", fmt.Errorf("settings files already exist and are being managed by the user")
}
// Snapshot causes a snapshot of the db to be written into the snapshots volume
// Returns the name of the snapshot and err
func (app *DdevApp) Snapshot(snapshotName string) (string, error) {
containerSnapshotDirBase := "/var/tmp"
err := app.ProcessHooks("pre-snapshot")
if err != nil {
return "", fmt.Errorf("failed to process pre-stop hooks: %v", err)
}
if snapshotName == "" {
t := time.Now()
snapshotName = app.Name + "_" + t.Format("20060102150405")
}
snapshotFile := snapshotName + "-" + app.Database.Type + "_" + app.Database.Version + ".gz"
existingSnapshots, err := app.ListSnapshots()
if err != nil {
return "", err
}
if nodeps.ArrayContainsString(existingSnapshots, snapshotName) {
return "", fmt.Errorf("snapshot %s already exists, please use another snapshot name or clean up snapshots with `ddev snapshot --cleanup`", snapshotFile)
}
// Container side has to use path.Join instead of filepath.Join because they are
// targeted at the linux filesystem, so won't work with filepath on Windows
containerSnapshotDir := containerSnapshotDirBase
// Ensure that db container is up.
err = app.Wait([]string{"db"})
if err != nil {
return "", fmt.Errorf("unable to snapshot database, \nyour db container in project %v is not running. \nPlease start the project if you want to snapshot it. \nIf deleting project, you can delete without a snapshot using \n'ddev delete --remove-data --yes', \nwhich will destroy your database", app.Name)
}
util.Success("Creating database snapshot %s", snapshotName)
c := getBackupCommand(app, path.Join(containerSnapshotDir, snapshotFile))
stdout, stderr, err := app.Exec(&ExecOpts{
Service: "db",
Cmd: fmt.Sprintf(`set -eu -o pipefail; %s `, c),
})
if err != nil {
util.Warning("Failed to create snapshot: %v, stdout=%s, stderr=%s", err, stdout, stderr)
return "", err
}
dbContainer, err := GetContainer(app, "db")
if err != nil {
return "", err
}
if globalconfig.DdevGlobalConfig.NoBindMounts {
// If we're not using bind-mounts, we have to copy the snapshot back into
// the host project's .ddev/db_snapshots directory
elapsed := util.TimeTrack(time.Now(), "CopySnapshotFromContainer")
// Copy snapshot back to the host
err = dockerutil.CopyFromContainer(GetContainerName(app, "db"), path.Join(containerSnapshotDir, snapshotFile), app.GetConfigPath("db_snapshots"))
if err != nil {
return "", err
}
elapsed()
} else {
// But if we are using bind-mounts, we can just copy it to where the snapshot is
// mounted into the db container (/mnt/ddev_config/db_snapshots)
c := fmt.Sprintf("cp -r %s/%s /mnt/ddev_config/db_snapshots", containerSnapshotDir, snapshotFile)
uid, _, _ := util.GetContainerUIDGid()
if app.Database.Type == nodeps.Postgres {
uid = "999"
}
stdout, stderr, err = dockerutil.Exec(dbContainer.ID, c, uid)
if err != nil {
return "", fmt.Errorf("failed to '%s': %v, stdout=%s, stderr=%s", c, err, stdout, stderr)
}
}
// Clean up the in-container dir that we just used
_, _, err = dockerutil.Exec(dbContainer.ID, fmt.Sprintf("rm -f %s/%s", containerSnapshotDir, snapshotFile), "")
if err != nil {
return "", err
}
err = app.ProcessHooks("post-snapshot")
if err != nil {
return snapshotFile, fmt.Errorf("failed to process pre-stop hooks: %v", err)
}
return snapshotName, nil
}
// getBackupCommand returns the command to dump the entire db system for the various databases
func getBackupCommand(app *DdevApp, targetFile string) string {
c := fmt.Sprintf(`mariabackup --backup --stream=mbstream --user=root --password=root --socket=/var/tmp/mysql.sock 2>/tmp/snapshot_%s.log | gzip > "%s"`, path.Base(targetFile), targetFile)
oldMariaVersions := []string{"5.5", "10.0"}
switch {
// Old mariadb versions don't have mariabackup, use xtrabackup for them as well as MySQL
case app.Database.Type == nodeps.MariaDB && nodeps.ArrayContainsString(oldMariaVersions, app.Database.Version):
fallthrough
case app.Database.Type == nodeps.MySQL:
c = fmt.Sprintf(`xtrabackup --backup --stream=xbstream --user=root --password=root --socket=/var/tmp/mysql.sock 2>/tmp/snapshot_%s.log | gzip > "%s"`, path.Base(targetFile), targetFile)
case app.Database.Type == nodeps.Postgres:
c = fmt.Sprintf("rm -rf /var/tmp/pgbackup && pg_basebackup -D /var/tmp/pgbackup 2>/tmp/snapshot_%s.log && tar -czf %s -C /var/tmp/pgbackup/ .", path.Base(targetFile), targetFile)
}
return c
}
// fullDBFromVersion takes just a mariadb or mysql version number
// in x.xx format and returns something like mariadb-10.5
func fullDBFromVersion(v string) string {
snapshotDBVersion := ""
// The old way (when we only had mariadb and then when had mariadb and also mysql)
// was to just have the version number and derive the database type from it,
// so that's what is going on here. But we create a string like "mariadb_10.3" from
// the version number
switch {
case v == "5.6" || v == "5.7" || v == "8.0":
snapshotDBVersion = "mysql_" + v
// 5.5 isn't actually necessarily correct, because could be
// mysql 5.5. But maria and mysql 5.5 databases were compatible anyway.
case v == "5.5" || v >= "10.0":
snapshotDBVersion = "mariadb_" + v
}
return snapshotDBVersion
}
// Stop stops and Removes the docker containers for the project in current directory.
func (app *DdevApp) Stop(removeData bool, createSnapshot bool) error {
app.DockerEnv()
var err error
if app.Name == "" {
return fmt.Errorf("invalid app.Name provided to app.Stop(), app=%v", app)
}
err = app.ProcessHooks("pre-stop")
if err != nil {
return fmt.Errorf("failed to process pre-stop hooks: %v", err)
}
status, _ := app.SiteStatus()
if createSnapshot == true {
if status != SiteRunning {
util.Warning("Must start non-running project to do database snapshot")
err = app.Start()
if err != nil {
return fmt.Errorf("failed to start project to perform database snapshot")
}
}
t := time.Now()
_, err = app.Snapshot(app.Name + "_remove_data_snapshot_" + t.Format("20060102150405"))
if err != nil {
return err
}
}
err = SyncAndTerminateMutagenSession(app)
if err != nil {
util.Warning("Unable to SyncAndterminateMutagenSession: %v", err)
}
if status == SiteRunning {
err = app.Pause()
if err != nil {
util.Warning("Failed to pause containers for %s: %v", app.GetName(), err)
}
}
// Remove all the containers and volumes for app.
err = Cleanup(app)
if err != nil {
return err
}
// Remove data/database/projectInfo/hostname if we need to.
if removeData {
if err = app.RemoveHostsEntries(); err != nil {
return fmt.Errorf("failed to remove hosts entries: %v", err)
}
app.RemoveGlobalProjectInfo()
err = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)
if err != nil {
util.Warning("could not WriteGlobalConfig: %v", err)
}
vols := []string{app.GetMariaDBVolumeName(), app.GetPostgresVolumeName(), GetMutagenVolumeName(app)}
if globalconfig.DdevGlobalConfig.NoBindMounts {
vols = append(vols, app.Name+"-ddev-config")
}
for _, volName := range vols {
err = dockerutil.RemoveVolume(volName)
if err != nil {
util.Warning("could not remove volume %s: %v", volName, err)
} else {
util.Success("Volume %s for project %s was deleted", volName, app.Name)
}
}
deleteServiceVolumes(app)
dbBuilt := app.GetDBImage() + "-" + app.Name + "-built"
_ = dockerutil.RemoveImage(dbBuilt)
webBuilt := versionconstants.GetWebImage() + "-" + app.Name + "-built"
_ = dockerutil.RemoveImage(webBuilt)
util.Success("Project %s was deleted. Your code and configuration are unchanged.", app.Name)
}
err = app.ProcessHooks("post-stop")
if err != nil {
return fmt.Errorf("failed to process post-stop hooks: %v", err)
}
return nil
}
// deleteServiceVolumes finds all the volumes created by services and removes them.
// All volumes that are not external (likely not global) are removed.
func deleteServiceVolumes(app *DdevApp) {
var err error
y := app.ComposeYaml
if s, ok := y["volumes"]; ok {
for _, v := range s.(map[interface{}]interface{}) {
vol := v.(map[interface{}]interface{})
if vol["external"] == true {
continue
}
if vol["name"] == nil {
continue
}
volName := vol["name"].(string)
if dockerutil.VolumeExists(volName) {
err = dockerutil.RemoveVolume(volName)
if err != nil {
util.Warning("could not remove volume %s: %v", volName, err)
} else {
util.Success("Deleting third-party persistent volume %s", volName)
}
}
}
}
}
// RemoveGlobalProjectInfo deletes the project from ProjectList
func (app *DdevApp) RemoveGlobalProjectInfo() {
_ = globalconfig.RemoveProjectInfo(app.Name)
}
// GetHTTPURL returns the HTTP URL for an app.
func (app *DdevApp) GetHTTPURL() string {
url := ""
if !IsRouterDisabled(app) {
url = "http://" + app.GetHostname()
if app.RouterHTTPPort != "80" {
url = url + ":" + app.RouterHTTPPort
}
} else {
url = app.GetWebContainerDirectHTTPURL()
}
return url
}
// GetHTTPSURL returns the HTTPS URL for an app.
func (app *DdevApp) GetHTTPSURL() string {
url := ""
if !IsRouterDisabled(app) {
url = "https://" + app.GetHostname()
if app.RouterHTTPSPort != "443" {
url = url + ":" + app.RouterHTTPSPort
}
} else {
url = app.GetWebContainerDirectHTTPSURL()
}
return url
}
// GetAllURLs returns an array of all the URLs for the project
func (app *DdevApp) GetAllURLs() (httpURLs []string, httpsURLs []string, allURLs []string) {
if nodeps.IsGitpod() {
url, err := exec.RunHostCommand("gp", "url", app.HostWebserverPort)
if err == nil {
url = strings.Trim(url, "\n")
httpsURLs = append(httpsURLs, url)
}
}
// Get configured URLs
for _, name := range app.GetHostnames() {
httpPort := ""
httpsPort := ""
if app.RouterHTTPPort != "80" {
httpPort = ":" + app.RouterHTTPPort
}
if app.RouterHTTPSPort != "443" {
httpsPort = ":" + app.RouterHTTPSPort
}
httpsURLs = append(httpsURLs, "https://"+name+httpsPort)
httpURLs = append(httpURLs, "http://"+name+httpPort)
}
if !IsRouterDisabled(app) {
httpsURLs = append(httpsURLs, app.GetWebContainerDirectHTTPSURL())
}
httpURLs = append(httpURLs, app.GetWebContainerDirectHTTPURL())
allURLs = append(httpsURLs, httpURLs...)
return httpURLs, httpsURLs, allURLs
}
// GetPrimaryURL returns the primary URL that can be used, https or http
func (app *DdevApp) GetPrimaryURL() string {
httpURLs, httpsURLs, _ := app.GetAllURLs()
urlList := httpsURLs
// If no mkcert trusted https, use the httpURLs instead
if !nodeps.IsGitpod() && (globalconfig.GetCAROOT() == "" || IsRouterDisabled(app)) {
urlList = httpURLs
}
if len(urlList) > 0 {
return urlList[0]
}
// Failure mode, just return empty string
return ""
}
// GetWebContainerDirectHTTPURL returns the URL that can be used without the router to get to web container.
func (app *DdevApp) GetWebContainerDirectHTTPURL() string {
// Get direct address of web container
dockerIP, err := dockerutil.GetDockerIP()
if err != nil {
util.Warning("Unable to get Docker IP: %v", err)
}
port, _ := app.GetWebContainerPublicPort()
return fmt.Sprintf("http://%s:%d", dockerIP, port)
}
// GetWebContainerDirectHTTPSURL returns the URL that can be used without the router to get to web container via https.
func (app *DdevApp) GetWebContainerDirectHTTPSURL() string {
// Get direct address of web container
dockerIP, err := dockerutil.GetDockerIP()
if err != nil {
util.Warning("Unable to get Docker IP: %v", err)
}
port, _ := app.GetWebContainerHTTPSPublicPort()
return fmt.Sprintf("https://%s:%d", dockerIP, port)
}
// GetWebContainerPublicPort returns the direct-access public tcp port for http
func (app *DdevApp) GetWebContainerPublicPort() (int, error) {
webContainer, err := app.FindContainerByType("web")
if err != nil || webContainer == nil {
return -1, fmt.Errorf("unable to find web container for app: %s, err %v", app.Name, err)
}
for _, p := range webContainer.Ports {
if p.PrivatePort == 80 {
return int(p.PublicPort), nil
}
}
return -1, fmt.Errorf("no public port found for private port 80")
}
// GetWebContainerHTTPSPublicPort returns the direct-access public tcp port for https
func (app *DdevApp) GetWebContainerHTTPSPublicPort() (int, error) {
webContainer, err := app.FindContainerByType("web")
if err != nil || webContainer == nil {
return -1, fmt.Errorf("unable to find https web container for app: %s, err %v", app.Name, err)
}
for _, p := range webContainer.Ports {
if p.PrivatePort == 443 {
return int(p.PublicPort), nil
}
}
return -1, fmt.Errorf("no public https port found for private port 443")
}
// HostName returns the hostname of a given application.
func (app *DdevApp) HostName() string {
return app.GetHostname()
}
// AddHostsEntriesIfNeeded will (optionally) add the site URL to the host's /etc/hosts.
func (app *DdevApp) AddHostsEntriesIfNeeded() error {
dockerIP, err := dockerutil.GetDockerIP()
if err != nil {
return fmt.Errorf("could not get Docker IP: %v", err)
}
hosts, err := ddevhosts.New()
if err != nil {
util.Failed("could not open hostfile: %v", err)
}
ipPosition := hosts.GetIPPosition(dockerIP)
if ipPosition != -1 && runtime.GOOS == "windows" {
hostsLine := hosts.Lines[ipPosition]
if len(hostsLine.Hosts) >= 10 {
util.Error("You have more than 9 entries in your (windows) hostsfile entry for %s", dockerIP)
util.Error("Please use `ddev hostname --remove-inactive` or edit the hosts file manually")
util.Error("Please see %s for more information", "https://ddev.readthedocs.io/en/stable/users/troubleshooting/#windows-hosts-file-limited")
}
}
for _, name := range app.GetHostnames() {
if app.UseDNSWhenPossible && globalconfig.IsInternetActive() {
// If they have provided "*.<name>" then look up the suffix
checkName := strings.TrimPrefix(name, "*.")
hostIPs, err := net.LookupHost(checkName)
// If we had successful lookup and dockerIP matches
// with adding to hosts file.
if err == nil && len(hostIPs) > 0 && hostIPs[0] == dockerIP {
continue
}
}
// We likely won't hit the hosts.Has() as true because
// we already did a lookup. But check anyway.
if hosts.Has(dockerIP, name) {
continue
}
util.Warning("The hostname %s is not currently resolvable, trying to add it to the hosts file", name)
err = addHostEntry(name, dockerIP)
if err != nil {
return err
}
}
return nil
}
// addHostEntry adds an entry to /etc/hosts
// We would have hoped to use DNS or have found the entry already in hosts
// But if it's not, try to add one.
func addHostEntry(name string, ip string) error {
_, err := osexec.LookPath("sudo")
if (os.Getenv("DDEV_NONINTERACTIVE") != "") || err != nil {
util.Warning("You must manually add the following entry to your hosts file:\n%s %s\nOr with root/administrative privileges execute 'ddev hostname %s %s'", ip, name, name, ip)
if nodeps.IsWSL2() {
util.Warning("For WSL2, if you use a Windows browser, execute 'sudo ddev hostname %s %s' on Windows", name, ip)
}
return nil
}
ddevFullpath, err := os.Executable()
util.CheckErr(err)
output.UserOut.Printf("ddev needs to add an entry to your hostfile.\nIt will require administrative privileges via the sudo command, so you may be required\nto enter your password for sudo. ddev is about to issue the command:")
if nodeps.IsWSL2() {
util.Warning("You are on WSL2, so should also manually execute 'sudo ddev hostname %s %s' on Windows if you use a Windows browser.", name, ip)
}
hostnameArgs := []string{ddevFullpath, "hostname", name, ip}
command := strings.Join(hostnameArgs, " ")
util.Warning(fmt.Sprintf(" sudo %s", command))
output.UserOut.Println("Please enter your password if prompted.")
_, err = exec.RunCommandPipe("sudo", hostnameArgs)
if err != nil {
util.Warning("Failed to execute sudo command, you will need to manually execute '%s' with administrative privileges", command)
}
return nil
}
// RemoveHostsEntries will remote the site URL from the host's /etc/hosts.
func (app *DdevApp) RemoveHostsEntries() error {
dockerIP, err := dockerutil.GetDockerIP()
if err != nil {
return fmt.Errorf("could not get Docker IP: %v", err)
}
hosts, err := goodhosts.NewHosts()
if err != nil {
util.Failed("could not open hostfile: %v", err)
}
for _, name := range app.GetHostnames() {
if !hosts.Has(dockerIP, name) {
continue
}
_, err = osexec.LookPath("sudo")
if os.Getenv("DDEV_NONINTERACTIVE") != "" || err != nil {
util.Warning("You must manually remove the following entry from your hosts file:\n%s %s\nOr with root/administrative privileges execute 'ddev hostname --remove %s %s", dockerIP, name, name, dockerIP)
return nil
}
ddevFullPath, err := os.Executable()
util.CheckErr(err)
output.UserOut.Printf("ddev needs to remove an entry from your hosts file.\nIt will require administrative privileges via the sudo command, so you may be required\nto enter your password for sudo. ddev is about to issue the command:")
hostnameArgs := []string{ddevFullPath, "hostname", "--remove", name, dockerIP}
command := strings.Join(hostnameArgs, " ")
util.Warning(fmt.Sprintf(" sudo %s", command))
output.UserOut.Println("Please enter your password if prompted.")
if _, err = exec.RunCommandPipe("sudo", hostnameArgs); err != nil {
util.Warning("Failed to execute sudo command, you will need to manually execute '%s' with administrative privileges", command)
}
}
return nil
}
// GetActiveAppRoot returns the fully rooted directory of the active app, or an error
func GetActiveAppRoot(siteName string) (string, error) {
var siteDir string
var err error
if siteName == "" {
siteDir, err = os.Getwd()
if err != nil {
return "", fmt.Errorf("error determining the current directory: %s", err)
}
_, err = CheckForConf(siteDir)
if err != nil {
return "", fmt.Errorf("could not find a project in %s. Have you run 'ddev config'? Please specify a project name or change directories: %s", siteDir, err)
}
// Handle the case where it's registered globally but stopped
} else if p := globalconfig.GetProject(siteName); p != nil {
return p.AppRoot, nil
// Or find it by looking at docker containers
} else {
var ok bool
labels := map[string]string{
"com.ddev.site-name": siteName,
"com.docker.compose.service": "web",
}
webContainer, err := dockerutil.FindContainerByLabels(labels)
if err != nil {
return "", err
}
if webContainer == nil {
return "", fmt.Errorf("could not find a project named '%s'. Run 'ddev list' to see currently active projects", siteName)
}
siteDir, ok = webContainer.Labels["com.ddev.approot"]
if !ok {
return "", fmt.Errorf("could not determine the location of %s from container: %s", siteName, dockerutil.ContainerName(*webContainer))
}
}
appRoot, err := CheckForConf(siteDir)
if err != nil {
return siteDir, err
}
return appRoot, nil
}
// GetActiveApp returns the active App based on the current working directory or running siteName provided.
// To use the current working directory, siteName should be ""
func GetActiveApp(siteName string) (*DdevApp, error) {
app := &DdevApp{}
activeAppRoot, err := GetActiveAppRoot(siteName)
if err != nil {
return app, err
}
// Mostly ignore app.Init() error, since app.Init() fails if no directory found. Some errors should be handled though.
// We already were successful with *finding* the app, and if we get an
// incomplete one we have to add to it.
if err = app.Init(activeAppRoot); err != nil {
switch err.(type) {
case webContainerExists, invalidConfigFile, invalidHostname, invalidAppType, invalidPHPVersion, invalidWebserverType, invalidProvider:
return app, err
}
}
if app.Name == "" {
err = restoreApp(app, siteName)
if err != nil {
return app, err
}
}
return app, nil
}
// restoreApp recreates an AppConfig's Name and returns an error
// if it cannot restore them.
func restoreApp(app *DdevApp, siteName string) error {
if siteName == "" {
return fmt.Errorf("error restoring AppConfig: no project name given")
}
app.Name = siteName
return nil
}
// GetProvider returns a pointer to the provider instance interface.
func (app *DdevApp) GetProvider(providerName string) (*Provider, error) {
var p Provider
var err error
if providerName != "" && providerName != nodeps.ProviderDefault {
p = Provider{
ProviderType: providerName,
app: app,
}
err = p.Init(providerName, app)
}
app.ProviderInstance = &p
return app.ProviderInstance, err
}
// GetWorkingDir will determine the appropriate working directory for an Exec/ExecWithTty command
// by consulting with the project configuration. If no dir is specified for the service, an
// empty string will be returned.
func (app *DdevApp) GetWorkingDir(service string, dir string) string {
// Highest preference is for directories passed into the command directly
if dir != "" {
return dir
}
// The next highest preference is for directories defined in config.yaml
if app.WorkingDir != nil {
if workingDir := app.WorkingDir[service]; workingDir != "" {
return workingDir
}
}
// The next highest preference is for app type defaults
return app.DefaultWorkingDirMap()[service]
}
// GetNFSMountVolumeName returns the docker volume name of the nfs mount volume
func (app *DdevApp) GetNFSMountVolumeName() string {
// This is lowercased because the automatic naming in docker-compose v1/2
// defaulted to lowercase the name
// Although some volume names are auto-lowercased by docker, this one
// is explicitly specified by us and is not lowercased.
return "ddev-" + app.Name + "_nfsmount"
}
// GetMariaDBVolumeName returns the docker volume name of the mariadb/database volume
// For historical reasons this isn't lowercased.
func (app *DdevApp) GetMariaDBVolumeName() string {
return app.Name + "-mariadb"
}
// GetPostgresVolumeName returns the docker volume name of the Postgres/database volume
// For historical reasons this isn't lowercased.
func (app *DdevApp) GetPostgresVolumeName() string {
return app.Name + "-postgres"
}
// StartAppIfNotRunning is intended to replace much-duplicated code in the commands.
func (app *DdevApp) StartAppIfNotRunning() error {
var err error
status, _ := app.SiteStatus()
if status != SiteRunning {
err = app.Start()
}
return err
}
// CheckAddonIncompatibilities looks for problems with docker-compose.*.yaml 3rd-party services
func (app *DdevApp) CheckAddonIncompatibilities() error {
if _, ok := app.ComposeYaml["services"]; !ok {
util.Warning("Unable to check 3rd-party services for missing networks stanza")
return nil
}
// Look for missing "networks" stanza and request it.
for s, v := range app.ComposeYaml["services"].(map[interface{}]interface{}) {
x := v.(map[interface{}]interface{})
errMsg := fmt.Errorf("service '%s' does not have the 'networks: [default, ddev_default]' stanza, required since v1.19, please add it, see %s", s, "https://ddev.readthedocs.io/en/latest/users/extend/custom-compose-files/#docker-composeyaml-examples")
var nets map[interface{}]interface{}
ok := false
if nets, ok = x["networks"].(map[interface{}]interface{}); !ok {
return errMsg
}
// Make sure both "default" and "ddev" networks are in there.
for _, requiredNetwork := range []string{"default", "ddev_default"} {
if _, ok := nets[requiredNetwork]; !ok {
return errMsg
}
}
}
return nil
}
// UpdateComposeYaml updates app.ComposeYaml from available content
func (app *DdevApp) UpdateComposeYaml(content string) error {
err := yaml.Unmarshal([]byte(content), &app.ComposeYaml)
if err != nil {
return err
}
return nil
}
// GetContainerName returns the contructed container name of the
// service provided.
func GetContainerName(app *DdevApp, service string) string {
return "ddev-" + app.Name + "-" + service
}
// GetContainer returns the containerID of the app service name provided.
func GetContainer(app *DdevApp, service string) (*docker.APIContainers, error) {
name := GetContainerName(app, service)
cid, err := dockerutil.FindContainerByName(name)
if err != nil || cid == nil {
return nil, fmt.Errorf("unable to find container %s: %v", name, err)
}
return cid, nil
}
// FormatSiteStatus formats "paused" or "running" with color
func FormatSiteStatus(status string) string {
if status == SiteRunning {
status = "OK"
}
formattedStatus := status
switch {
case strings.Contains(status, SitePaused):
formattedStatus = util.ColorizeText(formattedStatus, "yellow")
case strings.Contains(status, SiteStopped) || strings.Contains(status, SiteDirMissing) || strings.Contains(status, SiteConfigMissing):
formattedStatus = util.ColorizeText(formattedStatus, "red")
default:
formattedStatus = util.ColorizeText(formattedStatus, "green")
}
return formattedStatus
}
// GetHostUploadDirFullPath returns the full path to the upload directory on the host or "" if there is none
func (app *DdevApp) GetHostUploadDirFullPath() string {
if app.GetUploadDir() != "" {
return path.Join(app.AppRoot, app.Docroot, app.GetUploadDir())
}
return ""
}
// GetContainerUploadDirFullPath returns the full path to the upload directory in container or "" if there is none
func (app *DdevApp) GetContainerUploadDirFullPath() string {
if app.GetUploadDir() != "" {
return path.Join("/var/www/html", app.Docroot, app.GetUploadDir())
}
return ""
}
|
[
"\"DDEV_DB_CONTAINER_COMMAND\"",
"\"DDEV_NONINTERACTIVE\"",
"\"DDEV_NONINTERACTIVE\""
] |
[] |
[
"DDEV_DB_CONTAINER_COMMAND",
"DDEV_NONINTERACTIVE"
] |
[]
|
["DDEV_DB_CONTAINER_COMMAND", "DDEV_NONINTERACTIVE"]
|
go
| 2 | 0 | |
src/nninst/backend/tensorflow/attack/foolbox_attack_resnet_50_v2.py
|
import itertools
import os
from functools import partial
from foolbox.attacks import (
FGSM,
DeepFoolAttack,
IterativeGradientSignAttack,
SaliencyMapAttack,
)
from nninst import mode
from nninst.backend.tensorflow.attack.calc_density import trace_density
from nninst.backend.tensorflow.attack.calc_per_layer_metrics import (
get_per_layer_metrics,
)
from nninst.backend.tensorflow.attack.common import (
resnet_50_imagenet_real_metrics_per_layer,
resnet_50_imagenet_real_metrics_per_layer_targeted,
)
from nninst.backend.tensorflow.attack.cw_attack import cw_generate_adversarial_example
from nninst.backend.tensorflow.attack.cw_attacks import CarliniL2
from nninst.backend.tensorflow.attack.foolbox_attack import (
foolbox_generate_adversarial_example,
)
from nninst.backend.tensorflow.attack.random_attack import RandomAttack
from nninst.backend.tensorflow.dataset import imagenet
from nninst.backend.tensorflow.dataset.imagenet_preprocessing import _CHANNEL_MEANS
from nninst.backend.tensorflow.model.config import RESNET_50
from nninst.backend.tensorflow.trace.resnet_50_imagenet_class_trace_v3 import (
resnet_50_imagenet_class_trace_compact,
)
from nninst.backend.tensorflow.trace.utils import get_variant
from nninst.statistics import calc_trace_side_overlap_both_compact
from nninst.trace import (
TraceKey,
density_name,
early_stop_hook,
get_trace,
get_type2_trace,
get_type4_trace,
)
from nninst.utils.alternative import alt, alts
from nninst.utils.numpy import arg_approx
from nninst.utils.ray import ray_init
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1"
if __name__ == "__main__":
# mode.debug()
mode.distributed()
# mode.local()
# ray_init("dell")
ray_init()
label = None
# label = "best_in_10"
# label = "worst_in_10"
# label = "import"
# label = "norm"
variant = None
# variant = "intersect"
use_weight = False
# use_weight = True
print(f"attack model with label {label} using Foolbox")
attack_name = alt(
"normal",
"DeepFool",
# "Adaptive_layer1",
# "Adaptive_layer2",
# "Adaptive_layer3",
# "Adaptive_layer4",
# "Adaptive_layer5",
# "Adaptive_layer6",
# "Adaptive_layer7",
# "Adaptive_layer8",
# "Adaptive_layer9",
# "Adaptive_cos_layer9",
# "Adaptive_layer4",
# "Adaptive_return_late",
# "Adaptive_random_start",
# "Adaptive_iterations_400",
# "Adaptive_layer4_iterations_400",
"FGSM",
# "FGSM_targeted",
# "FGSM_iterative_targeted",
"BIM",
"JSMA",
"CWL2",
# "CWL2_confidence=3.5",
# "CWL2_confidence=14",
# "CWL2_confidence=28",
# "CWL2_target=500",
# "CWL2_confidence=28_target=500",
# "CWL2_confidence=28_target=500",
# "patch",
# "patch_scale=0.1",
# "patch_scale=0.2",
# "patch_scale=0.3",
# "patch_scale=0.4",
# "patch_scale=0.5",
# "new_patch_scale=0.1",
# "new_patch_scale=0.2",
# "new_patch_scale=0.3",
# "new_patch_scale=0.4",
# "new_patch_scale=0.5",
# "negative_example",
# "negative_example_top5",
# "negative_example_out_of_top5",
# "Random",
)
topk_share_range = alt(
# 2,
# 3,
# 5,
# 6,
# 7,
# 8,
9,
# 10,
# 20,
)
example_num = alt(
# 100,
# 400,
# 700,
# 1000,
0
)
rank = alt(
# None,
1,
2,
# 3,
# 4,
# 5,
# 6,
# 7,
# 8,
# 9,
# 10,
)
early_stop_layer_num = alt(
# None,
# 10,
12,
)
use_point = alt(
# True,
False
)
compare_with_full = alt(
False,
# True,
)
for threshold, absolute_threshold in itertools.product(
[
# 1.0,
# 0.9,
# 0.7,
0.5,
# 0.3,
# 0.1,
],
[
None,
# 0.05,
# 0.1,
# 0.2,
# 0.3,
# 0.4,
],
):
per_layer_metrics = lambda: get_per_layer_metrics(
RESNET_50, threshold=threshold, absolute_threshold=absolute_threshold
)
trace_fn, trace_label, trace_type, trace_parameter = alts(
[get_trace, None, None, None],
# [get_channel_trace, "per_channel", "class_channel_trace", None],
# [
# partial(get_type2_trace, output_threshold=per_layer_metrics()),
# f"type2_density_from_{threshold:.1f}",
# "type2_trace",
# f"density_from_{threshold:.1f}",
# ],
# [
# partial(get_type3_trace, input_threshold=per_layer_metrics()),
# f"type3_density_from_{threshold:.1f}",
# "type3_trace",
# f"density_from_{threshold:.1f}",
# ],
[
partial(
get_type4_trace,
output_threshold=per_layer_metrics(),
input_threshold=per_layer_metrics(),
),
f"type4_density_from_{threshold:.1f}",
"type4_trace",
f"density_from_{threshold:.1f}",
],
# [
# partial(
# get_type4_trace,
# output_threshold=per_layer_metrics(),
# input_threshold=per_layer_metrics(),
# ),
# f"type4_density_from_{threshold:.1f}_absolute_{absolute_threshold:.2f}",
# "type4_trace",
# f"density_from_{threshold:.1f}_absolute_{absolute_threshold:.2f}",
# ],
# [
# partial(get_unstructured_trace, density=per_layer_metrics()),
# f"unstructured_density_from_{threshold:.1f}",
# "unstructured_class_trace",
# f"density_from_{threshold:.1f}",
# ],
# [
# partial(
# get_per_receptive_field_unstructured_trace,
# output_threshold=per_layer_metrics(),
# ),
# f"per_receptive_field_unstructured_density_from_{threshold:.1f}",
# "per_receptive_field_unstructured_class_trace",
# f"density_from_{threshold:.1f}",
# ],
# [
# partial(
# get_type7_trace,
# density=per_layer_metrics(),
# input_threshold=per_layer_metrics(),
# ),
# f"type7_density_from_{threshold:.1f}",
# "type7_trace",
# f"density_from_{threshold:.1f}",
# ],
# [
# partial(
# get_per_input_unstructured_trace,
# output_threshold=per_layer_metrics(),
# input_threshold=per_layer_metrics(),
# ),
# f"per_input_unstructured_density_from_{threshold:.1f}",
# "per_input_unstructured_class_trace",
# f"density_from_{threshold:.1f}",
# ],
# *hybrid_backward_traces
)
for config in (
attack_name
* (trace_fn | trace_label | trace_type | trace_parameter)
* topk_share_range
* example_num
* rank
* use_point
* compare_with_full
* early_stop_layer_num
):
with config:
print(f"config: {list(config.values())}")
topk_calc_range = 2
variant = get_variant(
example_num=example_num.value,
early_stop_layer_num=early_stop_layer_num.value,
)
if variant is not None:
label_name = f"{label}_{variant}"
else:
label_name = label
if use_weight:
label_name = f"{label_name}_weight"
elif use_point.value:
label_name = f"{label_name}_point"
if compare_with_full.value:
label_name = f"{label_name}_vs_full"
if trace_label.value is not None:
label_name = f"{label_name}_{trace_label.value}"
if rank.value is not None:
label_name = f"{label_name}_rank{rank.value}"
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio(
# attack_fn=attacks[attack_name][0],
# generate_adversarial_fn=generate_adversarial_example,
# class_trace_fn=lambda class_id: alexnet_imagenet_class_trace_compact(class_id, threshold, label=label),
# # class_trace_fn=lambda class_id: lenet_mnist_class_trace(class_id, threshold),
# select_fn=lambda input: arg_approx(input, threshold),
# overlap_fn=calc_trace_side_overlap_compact,
# # overlap_fn=calc_iou,
# # overlap_fn=calc_class_trace_side_overlap,
# # overlap_fn=calc_class_trace_side_overlap_norm,
# # overlap_fn=calc_weighted_iou,
# path='alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.csv'.format(
# threshold, attack_name, label),
# # path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.iou.csv'.format(threshold, attack_name, label),
# # path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.class_side.csv'.format(
# # path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.wo_pool.csv'.format(
# # path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.class_side_norm.csv'.format(
# # path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.weighted_iou.csv'.format(
# # threshold, attack_name, label),
# preprocessing=(_CHANNEL_MEANS, 1),
# **(attacks[attack_name][1] if len(attacks[attack_name]) == 2 else {}),
# )
# alexnet_overlap_ratio.save()
# print("edge:")
# summary = get_overlay_summary(lenet_overlap_ratio.load(), TraceKey.EDGE)
# summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.csv".format(
# threshold=threshold, label=label)
# file_exists = os.path.exists(summary_file)
# with open(summary_file, "a") as csv_file:
# headers = ["attack"] + list(summary.keys())
# writer = csv.DictWriter(csv_file, delimiter=',', lineterminator='\n', fieldnames=headers)
# if not file_exists:
# writer.writeheader()
# writer.writerow({"attack": attack_name, **summary})
# print(summary)
# print("weight:")
# print(get_overlay_summary(lenet_overlap_ratio.load(), TraceKey.WEIGHT))
# print("point:")
# print(get_overlay_summary(lenet_overlap_ratio.load(), TraceKey.POINT))
# for overlay_threshold in np.arange(0, 1.01, 0.01):
# # summary = get_overlay_summary(alexnet_overlap_ratio.load(), TraceKey.EDGE, overlay_threshold)
# summary = get_overlay_summary(alexnet_overlap_ratio.load(), TraceKey.WEIGHT, overlay_threshold)
# summary_file = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.iou.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.class_side.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.wo_pool.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.class_side_norm.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.weighted_iou.csv".format(
# threshold=threshold, attack=attack_name, label=label)
# file_exists = os.path.exists(summary_file)
# with open(summary_file, "a") as csv_file:
# headers = ["attack"] + list(summary.keys())
# writer = csv.DictWriter(csv_file, delimiter=',', lineterminator='\n', fieldnames=headers)
# if not file_exists:
# writer.writeheader()
# writer.writerow({"attack": attack_name, **summary})
# overlap_fn = calc_trace_side_overlap_compact
overlap_fn = calc_trace_side_overlap_both_compact
# overlap_fn = calc_weighted_iou
# overlap_fn = calc_class_trace_side_overlap_compact
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff_same_class_trace.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff_all.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff_all.foolbox.csv"
# path_template = ("alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top"
# + str(topk_share_range)
# + "_diff_all_uint8.foolbox.csv")
# path_template = ("alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top"
# + str(topk_share_range)
# + "_diff_all.foolbox.csv")
# path_template = ("alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top"
# + str(topk_share_range)
# + "_logit_diff.foolbox.csv")
# path_template = "alexnet_imagenet_ideal_metrics_{0:.1f}_{1}_{2}.csv"
# path_template = "alexnet_imagenet_fc_layer_path_ideal_metrics_{0:.1f}_{1}_{2}.csv"
# path_template = "alexnet_imagenet_ideal_metrics_per_layer_{0:.1f}_{1}_{2}.csv"
path_template = (
"resnet_50_imagenet_real_metrics_per_layer_{0:.1f}_{1}_{2}.csv"
)
# path_template = "resnet_50_imagenet_real_metrics_per_layer_targeted0_{0:.1f}_{1}_{2}.csv"
# path_template = "resnet_50_imagenet_real_metrics_per_layer_targeted500_{0:.1f}_{1}_{2}.csv"
# path_template = "resnet_50_imagenet_real_metrics_per_layer_targeted800_{0:.1f}_{1}_{2}.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top2_diff_all.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_unique.foolbox.csv"
# path_template = "alexnet_imagenet_train_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_unique.weight.foolbox.csv"
# path_template = "alexnet_imagenet_train_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_unique.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff_all_online.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_per_node_{0:.1f}_{1}_{2}_top5_diff.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_top5_diff_train.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_weighted_iou.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_weighted_iou_class_0.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_per_node_{0:.1f}_{1}_{2}_weighted_iou_class_0.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_per_node_{0:.1f}_{1}_{2}_weighted_iou_class_0.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_per_node_{0:.1f}_{1}_{2}_weighted_iou.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_per_node_{0:.1f}_{1}_{2}_weighted_iou.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_per_node_{0:.1f}_{1}_{2}.foolbox.csv"
# path_template = "alexnet_imagenet_class_channel_overlap_ratio_{0:.1f}_{1}_{2}_class_0.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_full.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_train_in_trace.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_train_not_merged.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top5.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_all.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_error.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_rand.foolbox.csv"
# path_template = "alexnet_imagenet_class_overlap_ratio_{0:.1f}_{1}_{2}_top5_rand.foolbox.csv"
per_node = False
# per_node = True
# per_channel = True
per_channel = False
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_top5_diff_uint8(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_top5_diff(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_logit_diff(
# alexnet_overlap_ratio = alexnet_imagenet_ideal_metrics(
# alexnet_overlap_ratio = alexnet_imagenet_fc_layer_path_ideal_metrics(
# alexnet_overlap_ratio = alexnet_imagenet_negative_example_ideal_metrics_per_layer(
# alexnet_overlap_ratio = alexnet_imagenet_ideal_metrics_per_layer(
resnet_50_overlap_ratio = resnet_50_imagenet_real_metrics_per_layer(
# resnet_50_overlap_ratio = resnet_50_imagenet_real_metrics_per_layer_targeted(target_class=0)(
# resnet_50_overlap_ratio = resnet_50_imagenet_real_metrics_per_layer_targeted(target_class=500)(
# resnet_50_overlap_ratio = resnet_50_imagenet_real_metrics_per_layer_targeted(target_class=800)(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_top5_unique(
attack_name=attack_name.value,
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_top5(
trace_fn=partial(
trace_fn.value,
select_fn=lambda input: arg_approx(input, threshold),
stop_hook=early_stop_hook(early_stop_layer_num.value)
if early_stop_layer_num.value is not None
else None,
),
# class_trace_fn=lambda class_id: alexnet_imagenet_class_trace(class_id, threshold, label=label),
# class_trace_fn=lambda class_id: alexnet_imagenet_class_trace_compact(class_id, threshold, label=label),
# class_trace_fn=lambda class_id: alexnet_imagenet_class_channel_trace_compact(
class_trace_fn=lambda class_id: resnet_50_imagenet_class_trace_compact(
# class_trace_fn=lambda class_id: alexnet_imagenet_class_unique_trace_compact(
# class_trace_fn=lambda class_id: alexnet_imagenet_class_channel_trace(
# class_trace_fn=lambda class_id: alexnet_imagenet_class_trace(
class_id,
threshold,
label=label,
variant=variant,
trace_type=None
if compare_with_full.value
else trace_type.value,
trace_parameter=None
if compare_with_full.value
else trace_parameter.value,
),
# class_trace_fn=lambda class_id: lenet_mnist_class_trace(class_id, threshold),
# overlap_fn=calc_trace_side_overlap,
overlap_fn=overlap_fn,
# overlap_fn=calc_iou,
# overlap_fn=calc_class_trace_side_overlap,
# overlap_fn=calc_class_trace_side_overlap_norm,
# overlap_fn=calc_weighted_iou,
path="metrics/"
+ path_template.format(
# path='alexnet_imagenet_class_overlap_ratio_per_node_{0:.1f}_{1}_{2}.foolbox.csv'.format(
threshold,
attack_name.value,
label_name,
),
# path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.iou.csv'.format(threshold, attack_name, label),
# path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.class_side.csv'.format(
# path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.wo_pool.csv'.format(
# path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.class_side_norm.csv'.format(
# path='lenet_class_overlap_ratio_{0:.1f}_{1}_{2}.foolbox.weighted_iou.csv'.format(
# threshold, attack_name, label),
preprocessing=(_CHANNEL_MEANS, 1),
bounds=(0, 255),
channel_axis=3,
image_size=224,
class_num=1001,
norm_fn=imagenet.normalize,
data_format="channels_last",
per_node=per_node,
per_channel=per_channel,
topk_share_range=topk_share_range.value,
topk_calc_range=topk_calc_range,
use_weight=use_weight,
threshold=threshold,
rank=rank.value,
use_point=use_point.value,
label=label,
)
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_error(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_rand(
# alexnet_overlap_ratio = alexnet_imagenet_overlap_ratio_top5_rand(
# class_trace_fn=lambda class_id: alexnet_imagenet_class_trace_compact(class_id, threshold, label=label),
# select_fn=lambda input: arg_approx(input, threshold),
# overlap_fn=overlap_fn,
# path=path_template.format(threshold, attack_name, label),
# )
resnet_50_overlap_ratio.save()
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_same_class_trace.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_all.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_all_compare.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_all_compare.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top2_diff_all_compare.{key}.csv"
summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_unique_compare.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_all_compare_online.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_all_compare_filter.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_diff_train.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_weighted_iou.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_weighted_iou_class_0.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_channel_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_class_0.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_full.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_train_in_trace.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_train_not_merged.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_all.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_error.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_rand.{key}.csv"
# summary_path_template = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}_top5_rand.{key}.csv"
# key = TraceKey.EDGE
# # summary_file = "alexnet_imagenet_class_overlap_ratio_summary_{threshold:.1f}_{attack}_{label}.{key}.csv".format(
# summary_file = summary_path_template.format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.iou.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.class_side.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.wo_pool.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.class_side_norm.csv".format(
# # summary_file = "lenet_class_overlap_ratio_summary_{threshold:.1f}_{label}.weighted_iou.csv".format(
# threshold=threshold, attack=attack_name, label=label_name, key=key)
# with open(summary_file, "w") as csv_file:
# has_header = False
# for overlay_threshold in np.linspace(-1, 1, 201):
# # summary = get_overlay_summary(alexnet_overlap_ratio.load(), key, overlay_threshold)
# # summary = get_overlay_summary_top1(alexnet_overlap_ratio.load(), key, overlay_threshold)
# summary = get_overlay_summary_compare(alexnet_overlap_ratio.load(), key, float(overlay_threshold))
# # summary = get_overlay_summary_compare_filter(alexnet_overlap_ratio.load(), key, float(overlay_threshold))
# # summary = get_overlay_summary_one_side(alexnet_overlap_ratio.load(), key, overlay_threshold)
# if not has_header:
# headers = ["attack"] + list(summary.keys())
# writer = csv.DictWriter(csv_file, delimiter=',', lineterminator='\n', fieldnames=headers)
# writer.writeheader()
# has_header = True
# writer.writerow({"attack": attack_name, **summary})
#
# summary_file = summary_path_template.format(
# threshold=threshold, attack=attack_name, label=label_name, key="detail")
# get_overlay_summary_compare_detail(summary_file, alexnet_overlap_ratio.load(), from_zero=True).save()
|
[] |
[] |
[
"TF_CPP_MIN_LOG_LEVEL"
] |
[]
|
["TF_CPP_MIN_LOG_LEVEL"]
|
python
| 1 | 0 | |
controllers/main.go
|
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"os"
networkingv1alpha1 "code.cloudfoundry.org/cf-k8s-controllers/controllers/apis/networking/v1alpha1"
workloadsv1alpha1 "code.cloudfoundry.org/cf-k8s-controllers/controllers/apis/workloads/v1alpha1"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/config"
networkingcontrollers "code.cloudfoundry.org/cf-k8s-controllers/controllers/controllers/networking"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/controllers/shared"
workloadscontrollers "code.cloudfoundry.org/cf-k8s-controllers/controllers/controllers/workloads"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/controllers/workloads/imageprocessfetcher"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/coordination"
"code.cloudfoundry.org/cf-k8s-controllers/controllers/webhooks/workloads"
eiriniv1 "code.cloudfoundry.org/eirini-controller/pkg/apis/eirini/v1"
buildv1alpha2 "github.com/pivotal/kpack/pkg/apis/build/v1alpha2"
contourv1 "github.com/projectcontour/contour/apis/projectcontour/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
k8sclient "k8s.io/client-go/kubernetes"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
hnsv1alpha2 "sigs.k8s.io/hierarchical-namespaces/api/v1alpha2"
servicesv1alpha1 "code.cloudfoundry.org/cf-k8s-controllers/controllers/apis/services/v1alpha1"
servicescontrollers "code.cloudfoundry.org/cf-k8s-controllers/controllers/controllers/services"
//+kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(workloadsv1alpha1.AddToScheme(scheme))
utilruntime.Must(networkingv1alpha1.AddToScheme(scheme))
utilruntime.Must(buildv1alpha2.AddToScheme(scheme))
utilruntime.Must(contourv1.AddToScheme(scheme))
utilruntime.Must(eiriniv1.AddToScheme(scheme))
utilruntime.Must(hnsv1alpha2.AddToScheme(scheme))
utilruntime.Must(servicesv1alpha1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "13c200ec.cloudfoundry.org",
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
configPath, found := os.LookupEnv("CONTROLLERSCONFIG")
if !found {
panic("CONTROLLERSCONFIG must be set")
}
controllerConfig, err := config.LoadFromPath(configPath)
if err != nil {
errorMessage := fmt.Sprintf("Config could not be read: %v", err)
panic(errorMessage)
}
k8sClientConfig := ctrl.GetConfigOrDie()
privilegedK8sClient, err := k8sclient.NewForConfig(k8sClientConfig)
if err != nil {
panic(fmt.Sprintf("could not create privileged k8s client: %v", err))
}
// Setup with manager
if err = (&workloadscontrollers.CFAppReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Log: ctrl.Log.WithName("controllers").WithName("CFApp"),
ControllerConfig: controllerConfig,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFApp")
os.Exit(1)
}
cfBuildImageProcessFetcher := &imageprocessfetcher.ImageProcessFetcher{
Log: ctrl.Log.WithName("controllers").WithName("CFBuildImageProcessFetcher"),
}
if err = (&workloadscontrollers.CFBuildReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Log: ctrl.Log.WithName("controllers").WithName("CFBuild"),
ControllerConfig: controllerConfig,
RegistryAuthFetcher: workloadscontrollers.NewRegistryAuthFetcher(privilegedK8sClient),
ImageProcessFetcher: cfBuildImageProcessFetcher.Fetch,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFBuild")
os.Exit(1)
}
if err = (&networkingcontrollers.CFDomainReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFDomain")
os.Exit(1)
}
if err = (&workloadscontrollers.CFPackageReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Log: ctrl.Log.WithName("controllers").WithName("CFPackage"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFPackage")
os.Exit(1)
}
if err = (&workloadscontrollers.CFProcessReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Log: ctrl.Log.WithName("controllers").WithName("CFProcess"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFProcess")
os.Exit(1)
}
if err = (&networkingcontrollers.CFRouteReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Log: ctrl.Log.WithName("controllers").WithName("CFRoute"),
ControllerConfig: controllerConfig,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFRoute")
os.Exit(1)
}
// Setup Index with Manager
err = shared.SetupIndexWithManager(mgr)
if err != nil {
setupLog.Error(err, "unable to setup index on manager")
os.Exit(1)
}
// Setup webhooks with manager
if os.Getenv("ENABLE_WEBHOOKS") != "false" {
if err = (&workloadsv1alpha1.CFApp{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFApp")
os.Exit(1)
}
if err = (&workloadsv1alpha1.CFPackage{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFPackage")
os.Exit(1)
}
if err = (&workloadsv1alpha1.CFBuild{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFBuild")
os.Exit(1)
}
if err = (&workloadsv1alpha1.CFProcess{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFProcess")
os.Exit(1)
}
if err = workloads.NewCFAppValidation(
coordination.NewNameRegistry(mgr.GetClient(), workloads.AppEntityType),
).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFApp")
os.Exit(1)
}
if err = workloads.NewSubnamespaceAnchorValidation(
coordination.NewNameRegistry(mgr.GetClient(), workloads.OrgEntityType),
coordination.NewNameRegistry(mgr.GetClient(), workloads.SpaceEntityType),
).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "SubnamespaceAnchors")
os.Exit(1)
}
if err = (&networkingv1alpha1.CFRoute{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "CFRoute")
os.Exit(1)
}
} else {
setupLog.Info("Skipping webhook setup because ENABLE_WEBHOOKS set to false.")
}
if err = (&servicescontrollers.CFServiceInstanceReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFServiceInstance")
os.Exit(1)
}
if err = (&servicescontrollers.CFServiceBindingReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CFServiceBinding")
os.Exit(1)
}
//+kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
|
[
"\"ENABLE_WEBHOOKS\""
] |
[] |
[
"ENABLE_WEBHOOKS"
] |
[]
|
["ENABLE_WEBHOOKS"]
|
go
| 1 | 0 | |
cmd/root.go
|
package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/ory/viper"
"github.com/pborman/uuid"
"github.com/spf13/cobra"
)
func check(err error) {
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "go-acc <flags> <packages...>",
Short: "Receive accurate code coverage reports for Golang (Go)",
Args: cobra.MinimumNArgs(1),
Example: `$ go-acc github.com/some/package
$ go-acc -o my-coverfile.txt github.com/some/package
$ go-acc ./...
$ go-acc $(glide novendor)
$ go-acc --ignore pkga,pkgb .
You can pass all flags defined by "go test" after "--":
$ go-acc . -- -short -v -failfast
You can pick an alternative go test binary using:
GO_TEST_BINARY="go test"
GO_TEST_BINARY="gotest"
`,
RunE: func(cmd *cobra.Command, args []string) error {
mode, err := cmd.Flags().GetString("covermode")
if err != nil {
return err
}
if verbose, err := cmd.Flags().GetBool("verbose"); err != nil {
return err
} else if verbose {
fmt.Println("Flag -v has been deprecated, use `go-acc -- -v` instead!")
}
ignores, err := cmd.Flags().GetStringSlice("ignore")
if err != nil {
return err
}
tagsArg := ""
tags, err := cmd.Flags().GetStringSlice("tags")
if err != nil {
return err
} else if len(tags) != 0 {
tagsArg = "-tags=" + strings.Join(tags, ",")
}
payload := "mode: " + mode + "\n"
var packages []string
var passthrough []string
for _, a := range args {
if len(a) == 0 {
continue
}
// The first tag indicates that we're now passing through all tags
if a[0] == '-' || len(passthrough) > 0 {
passthrough = append(passthrough, a)
continue
}
if len(a) > 4 && a[len(a)-4:] == "/..." {
var buf bytes.Buffer
c := newCmdBuilder("go list").argNoBlank(tagsArg).arg(a).exec()
c.Stdout = &buf
c.Stderr = &buf
if err := c.Run(); err != nil {
check(fmt.Errorf("unable to run go list: %w", err))
}
var add []string
for _, s := range strings.Split(buf.String(), "\n") {
// Remove go system messages, e.g. messages from go mod like
// go: finding ...
// go: downloading ...
// go: extracting ...
if len(s) > 0 && !strings.HasPrefix(s, "go: ") {
// Test if package name contains ignore string
ignore := false
for _, ignoreStr := range ignores {
if strings.Contains(s, ignoreStr) {
ignore = true
break
}
}
if !ignore {
add = append(add, s)
}
}
}
packages = append(packages, add...)
} else {
packages = append(packages, a)
}
}
files := make([]string, len(packages))
for k, pkg := range packages {
files[k] = filepath.Join(os.TempDir(), uuid.New()) + ".cc.tmp"
gotest := os.Getenv("GO_TEST_BINARY")
if gotest == "" {
gotest = "go test"
}
c := newCmdBuilder(gotest).arg(
"-covermode=" + mode,
"-coverprofile=" + files[k],
"-coverpkg=" + strings.Join(packages, ","),
).argNoBlank(tagsArg).arg(passthrough...).arg(pkg).exec()
stderr, err := c.StderrPipe()
check(err)
stdout, err := c.StdoutPipe()
check(err)
check(c.Start())
var wg sync.WaitGroup
wg.Add(2)
go scan(&wg, stderr)
go scan(&wg, stdout)
check(c.Wait())
wg.Wait()
}
for _, file := range files {
if _, err := os.Stat(file); os.IsNotExist(err) {
continue
}
p, err := ioutil.ReadFile(file)
check(err)
ps := strings.Split(string(p), "\n")
payload += strings.Join(ps[1:], "\n")
}
output, err := cmd.Flags().GetString("output")
check(err)
check(ioutil.WriteFile(output, []byte(payload), 0644))
return nil
},
}
func scan(wg *sync.WaitGroup, r io.ReadCloser) {
defer wg.Done()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "warning: no packages being tested depend on matches for pattern") {
continue
}
fmt.Println(strings.Split(line, "% of statements in")[0])
}
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize(initConfig)
RootCmd.Flags().BoolP("verbose", "v", false, "Does nothing, there for compatibility")
RootCmd.Flags().StringP("output", "o", "coverage.txt", "Location for the output file")
RootCmd.Flags().String("covermode", "atomic", "Which code coverage mode to use")
RootCmd.Flags().StringSlice("ignore", []string{}, "Will ignore packages that contains any of these strings")
RootCmd.Flags().StringSlice("tags", []string{}, "Tags to include")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
viper.AutomaticEnv() // read in environment variables that match
}
type filter struct {
dtl io.Writer
}
func (f *filter) Write(p []byte) (n int, err error) {
for _, ppp := range strings.Split(string(p), "\n") {
if strings.Contains(ppp, "warning: no packages being tested depend on matches for pattern") {
continue
} else {
nn, err := f.dtl.Write(p)
n = n + nn
if err != nil {
return n, err
}
}
}
return len(p), nil
}
type cmdBuilder struct {
cmd string
args []string
}
func newCmdBuilder(cmd string) *cmdBuilder {
c := strings.Split(cmd, " ")
b := &cmdBuilder{cmd: c[0]}
for i := 1; i < len(c); i++ {
b = b.argNoBlank(c[i])
}
return b
}
func (b *cmdBuilder) argNoBlank(args ...string) *cmdBuilder {
for _, a := range args {
if a != "" {
b.args = append(b.args, a)
}
}
return b
}
func (b *cmdBuilder) arg(args ...string) *cmdBuilder {
b.args = append(b.args, args...)
return b
}
func (b *cmdBuilder) exec() *exec.Cmd {
return exec.Command(b.cmd, b.args...)
}
|
[
"\"GO_TEST_BINARY\""
] |
[] |
[
"GO_TEST_BINARY"
] |
[]
|
["GO_TEST_BINARY"]
|
go
| 1 | 0 | |
eval.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Calculate mAP for YOLO model on some annotation dataset
"""
import os, argparse, time
import numpy as np
import operator
from operator import mul
from functools import reduce
from PIL import Image
from collections import OrderedDict
import matplotlib.pyplot as plt
from tqdm import tqdm
from tensorflow.keras.models import load_model
import tensorflow.keras.backend as K
import tensorflow as tf
import MNN
import onnxruntime
from yolo5.postprocess_np import yolo5_postprocess_np
from yolo3.postprocess_np import yolo3_postprocess_np
from yolo2.postprocess_np import yolo2_postprocess_np
from common.data_utils import preprocess_image
from common.utils import get_dataset, get_classes, get_anchors, get_colors, draw_boxes, optimize_tf_gpu, get_custom_objects
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
optimize_tf_gpu(tf, K)
def annotation_parse(annotation_lines, class_names):
'''
parse annotation lines to get image dict and ground truth class dict
image dict would be like:
annotation_records = {
'/path/to/000001.jpg': {'100,120,200,235':'dog', '85,63,156,128':'car', ...},
...
}
ground truth class dict would be like:
classes_records = {
'car': [
['000001.jpg','100,120,200,235'],
['000002.jpg','85,63,156,128'],
...
],
...
}
'''
annotation_records = OrderedDict()
classes_records = OrderedDict({class_name: [] for class_name in class_names})
for line in annotation_lines:
box_records = {}
image_name = line.split(' ')[0]
boxes = line.split(' ')[1:]
for box in boxes:
#strip box coordinate and class
class_name = class_names[int(box.split(',')[-1])]
coordinate = ','.join(box.split(',')[:-1])
box_records[coordinate] = class_name
#append or add ground truth class item
record = [os.path.basename(image_name), coordinate]
if class_name in classes_records:
classes_records[class_name].append(record)
else:
classes_records[class_name] = list([record])
annotation_records[image_name] = box_records
return annotation_records, classes_records
def transform_gt_record(gt_records, class_names):
'''
Transform the Ground Truth records of a image to prediction format, in
order to show & compare in result pic.
Ground Truth records is a dict with format:
{'100,120,200,235':'dog', '85,63,156,128':'car', ...}
Prediction format:
(boxes, classes, scores)
'''
if gt_records is None or len(gt_records) == 0:
return [], [], []
gt_boxes = []
gt_classes = []
gt_scores = []
for (coordinate, class_name) in gt_records.items():
gt_box = [int(x) for x in coordinate.split(',')]
gt_class = class_names.index(class_name)
gt_boxes.append(gt_box)
gt_classes.append(gt_class)
gt_scores.append(1.0)
return np.array(gt_boxes), np.array(gt_classes), np.array(gt_scores)
def yolo_predict_tflite(interpreter, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# check the type of the input tensor
#if input_details[0]['dtype'] == np.float32:
#floating_model = True
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
model_input_shape = (height, width)
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
interpreter.set_tensor(input_details[0]['index'], image_data)
interpreter.invoke()
prediction = []
for output_detail in output_details:
output_data = interpreter.get_tensor(output_detail['index'])
prediction.append(output_data)
prediction.sort(key=lambda x: len(x[0]))
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_mnn(interpreter, session, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
# assume only 1 input tensor for image
input_tensor = interpreter.getSessionInput(session)
# get input shape
input_shape = input_tensor.getShape()
if input_tensor.getDimensionType() == MNN.Tensor_DimensionType_Tensorflow:
batch, height, width, channel = input_shape
elif input_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe:
batch, channel, height, width = input_shape
else:
# should be MNN.Tensor_DimensionType_Caffe_C4, unsupported now
raise ValueError('unsupported input tensor dimension type')
model_input_shape = (height, width)
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
# create a temp tensor to copy data
# use TF NHWC layout to align with image data array
# TODO: currently MNN python binding have mem leak when creating MNN.Tensor
# from numpy array, only from tuple is good. So we convert input image to tuple
tmp_input_shape = (batch, height, width, channel)
input_elementsize = reduce(mul, tmp_input_shape)
tmp_input = MNN.Tensor(tmp_input_shape, input_tensor.getDataType(),\
tuple(image_data.reshape(input_elementsize, -1)), MNN.Tensor_DimensionType_Tensorflow)
input_tensor.copyFrom(tmp_input)
interpreter.runSession(session)
def get_tensor_list(output_tensors):
# transform the output tensor dict to ordered tensor list, for further postprocess
#
# output tensor list should be like (for YOLOv3):
# [
# (name, tensor) for (13, 13, 3, num_classes+5),
# (name, tensor) for (26, 26, 3, num_classes+5),
# (name, tensor) for (52, 52, 3, num_classes+5)
# ]
output_list = []
for (output_tensor_name, output_tensor) in output_tensors.items():
tensor_shape = output_tensor.getShape()
dim_type = output_tensor.getDimensionType()
tensor_height, tensor_width = tensor_shape[2:4] if dim_type == MNN.Tensor_DimensionType_Caffe else tensor_shape[1:3]
if len(anchors) == 6:
# Tiny YOLOv3
if tensor_height == height//32:
output_list.insert(0, (output_tensor_name, output_tensor))
elif tensor_height == height//16:
output_list.insert(1, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid tensor shape')
elif len(anchors) == 9:
# YOLOv3
if tensor_height == height//32:
output_list.insert(0, (output_tensor_name, output_tensor))
elif tensor_height == height//16:
output_list.insert(1, (output_tensor_name, output_tensor))
elif tensor_height == height//8:
output_list.insert(2, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid tensor shape')
elif len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(output_tensors) == 1, 'YOLOv2 model should have only 1 output tensor.'
output_list.insert(0, (output_tensor_name, output_tensor))
else:
raise ValueError('invalid anchor number')
return output_list
output_tensors = interpreter.getSessionOutputAll(session)
output_tensor_list = get_tensor_list(output_tensors)
prediction = []
for (output_tensor_name, output_tensor) in output_tensor_list:
output_shape = output_tensor.getShape()
output_elementsize = reduce(mul, output_shape)
assert output_tensor.getDataType() == MNN.Halide_Type_Float
# copy output tensor to host, for further postprocess
tmp_output = MNN.Tensor(output_shape, output_tensor.getDataType(),\
#np.zeros(output_shape, dtype=float), output_tensor.getDimensionType())
tuple(np.zeros(output_shape, dtype=float).reshape(output_elementsize, -1)), output_tensor.getDimensionType())
output_tensor.copyToHostTensor(tmp_output)
#tmp_output.printTensorData()
output_data = np.array(tmp_output.getData(), dtype=float).reshape(output_shape)
# our postprocess code based on TF NHWC layout, so if the output format
# doesn't match, we need to transpose
if output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe:
output_data = output_data.transpose((0,2,3,1))
elif output_tensor.getDimensionType() == MNN.Tensor_DimensionType_Caffe_C4:
raise ValueError('unsupported output tensor dimension type')
prediction.append(output_data)
prediction.sort(key=lambda x: len(x[0]))
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_pb(model, image, anchors, num_classes, model_input_shape, conf_threshold, elim_grid_sense, v5_decode):
# NOTE: TF 1.x frozen pb graph need to specify input/output tensor name
# so we hardcode the input/output tensor names here to get them from model
if len(anchors) == 6:
output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0']
elif len(anchors) == 9:
output_tensor_names = ['graph/predict_conv_1/BiasAdd:0', 'graph/predict_conv_2/BiasAdd:0', 'graph/predict_conv_3/BiasAdd:0']
elif len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
output_tensor_names = ['graph/predict_conv/BiasAdd:0']
else:
raise ValueError('invalid anchor number')
# assume only 1 input tensor for image
input_tensor_name = 'graph/image_input:0'
# get input/output tensors
image_input = model.get_tensor_by_name(input_tensor_name)
output_tensors = [model.get_tensor_by_name(output_tensor_name) for output_tensor_name in output_tensor_names]
batch, height, width, channel = image_input.shape
model_input_shape = (int(height), int(width))
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
with tf.Session(graph=model) as sess:
prediction = sess.run(output_tensors, feed_dict={
image_input: image_data
})
prediction.sort(key=lambda x: len(x[0]))
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_onnx(model, image, anchors, num_classes, conf_threshold, elim_grid_sense, v5_decode):
input_tensors = []
for i, input_tensor in enumerate(model.get_inputs()):
input_tensors.append(input_tensor)
# assume only 1 input tensor for image
assert len(input_tensors) == 1, 'invalid input tensor number.'
# check if input layout is NHWC or NCHW
if input_tensors[0].shape[1] == 3:
batch, channel, height, width = input_tensors[0].shape #NCHW
else:
batch, height, width, channel = input_tensors[0].shape #NHWC
model_input_shape = (height, width)
# prepare input image
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
if input_tensors[0].shape[1] == 3:
# transpose image for NCHW layout
image_data = image_data.transpose((0,3,1,2))
feed = {input_tensors[0].name: image_data}
prediction = model.run(None, feed)
prediction.sort(key=lambda x: len(x[0]))
if len(anchors) == 5:
# YOLOv2 use 5 anchors and have only 1 prediction
assert len(prediction) == 1, 'invalid YOLOv2 prediction number.'
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction[0], image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def yolo_predict_keras(model, image, anchors, num_classes, model_input_shape, conf_threshold, elim_grid_sense, v5_decode):
image_data = preprocess_image(image, model_input_shape)
#origin image shape, in (height, width) format
image_shape = image.size[::-1]
prediction = model.predict([image_data])
if len(anchors) == 5:
# YOLOv2 use 5 anchors
pred_boxes, pred_classes, pred_scores = yolo2_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
else:
if v5_decode:
pred_boxes, pred_classes, pred_scores = yolo5_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=True) #enable "elim_grid_sense" by default
else:
pred_boxes, pred_classes, pred_scores = yolo3_postprocess_np(prediction, image_shape, anchors, num_classes, model_input_shape, max_boxes=100, confidence=conf_threshold, elim_grid_sense=elim_grid_sense)
return pred_boxes, pred_classes, pred_scores
def get_prediction_class_records(model, model_format, annotation_records, anchors, class_names, model_input_shape, conf_threshold, elim_grid_sense, v5_decode, save_result):
'''
Do the predict with YOLO model on annotation images to get predict class dict
predict class dict would contain image_name, coordinary and score, and
sorted by score:
pred_classes_records = {
'car': [
['000001.jpg','94,115,203,232',0.98],
['000002.jpg','82,64,154,128',0.93],
...
],
...
}
'''
if model_format == 'MNN':
#MNN inference engine need create session
session = model.createSession()
# create txt file to save prediction result, with
# save format as annotation file but adding score, like:
#
# path/to/img1.jpg 50,100,150,200,0,0.86 30,50,200,120,3,0.95
#
os.makedirs('result', exist_ok=True)
result_file = open(os.path.join('result','detection_result.txt'), 'w')
pred_classes_records = OrderedDict()
pbar = tqdm(total=len(annotation_records), desc='Eval model')
for (image_name, gt_records) in annotation_records.items():
image = Image.open(image_name)
if image.mode != 'RGB':
image = image.convert('RGB')
image_array = np.array(image, dtype='uint8')
# support of tflite model
if model_format == 'TFLITE':
pred_boxes, pred_classes, pred_scores = yolo_predict_tflite(model, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# support of MNN model
elif model_format == 'MNN':
pred_boxes, pred_classes, pred_scores = yolo_predict_mnn(model, session, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# support of TF 1.x frozen pb model
elif model_format == 'PB':
pred_boxes, pred_classes, pred_scores = yolo_predict_pb(model, image, anchors, len(class_names), model_input_shape, conf_threshold, elim_grid_sense, v5_decode)
# support of ONNX model
elif model_format == 'ONNX':
pred_boxes, pred_classes, pred_scores = yolo_predict_onnx(model, image, anchors, len(class_names), conf_threshold, elim_grid_sense, v5_decode)
# normal keras h5 model
elif model_format == 'H5':
pred_boxes, pred_classes, pred_scores = yolo_predict_keras(model, image, anchors, len(class_names), model_input_shape, conf_threshold, elim_grid_sense, v5_decode)
else:
raise ValueError('invalid model format')
#print('Found {} boxes for {}'.format(len(pred_boxes), image_name))
image.close()
pbar.update(1)
# save prediction result to txt
result_file.write(image_name)
for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):
xmin, ymin, xmax, ymax = box
box_annotation = " %d,%d,%d,%d,%d,%f" % (
xmin, ymin, xmax, ymax, cls, score)
result_file.write(box_annotation)
result_file.write('\n')
result_file.flush()
if save_result:
gt_boxes, gt_classes, gt_scores = transform_gt_record(gt_records, class_names)
result_dir=os.path.join('result','detection')
os.makedirs(result_dir, exist_ok=True)
colors = get_colors(len(class_names))
image_array = draw_boxes(image_array, gt_boxes, gt_classes, gt_scores, class_names, colors=None, show_score=False)
image_array = draw_boxes(image_array, pred_boxes, pred_classes, pred_scores, class_names, colors)
image = Image.fromarray(image_array)
# here we handle the RGBA image
if(len(image.split()) == 4):
r, g, b, a = image.split()
image = Image.merge("RGB", (r, g, b))
image.save(os.path.join(result_dir, image_name.split(os.path.sep)[-1]))
# Nothing detected
if pred_boxes is None or len(pred_boxes) == 0:
continue
for box, cls, score in zip(pred_boxes, pred_classes, pred_scores):
pred_class_name = class_names[cls]
xmin, ymin, xmax, ymax = box
coordinate = "{},{},{},{}".format(xmin, ymin, xmax, ymax)
#append or add predict class item
record = [os.path.basename(image_name), coordinate, score]
if pred_class_name in pred_classes_records:
pred_classes_records[pred_class_name].append(record)
else:
pred_classes_records[pred_class_name] = list([record])
# sort pred_classes_records for each class according to score
for pred_class_list in pred_classes_records.values():
pred_class_list.sort(key=lambda ele: ele[2], reverse=True)
pbar.close()
result_file.close()
return pred_classes_records
def box_iou(pred_box, gt_box):
'''
Calculate iou for predict box and ground truth box
Param
pred_box: predict box coordinate
(xmin,ymin,xmax,ymax) format
gt_box: ground truth box coordinate
(xmin,ymin,xmax,ymax) format
Return
iou value
'''
# get intersection box
inter_box = [max(pred_box[0], gt_box[0]), max(pred_box[1], gt_box[1]), min(pred_box[2], gt_box[2]), min(pred_box[3], gt_box[3])]
inter_w = max(0.0, inter_box[2] - inter_box[0] + 1)
inter_h = max(0.0, inter_box[3] - inter_box[1] + 1)
# compute overlap (IoU) = area of intersection / area of union
pred_area = (pred_box[2] - pred_box[0] + 1) * (pred_box[3] - pred_box[1] + 1)
gt_area = (gt_box[2] - gt_box[0] + 1) * (gt_box[3] - gt_box[1] + 1)
inter_area = inter_w * inter_h
union_area = pred_area + gt_area - inter_area
return 0 if union_area == 0 else float(inter_area) / float(union_area)
def match_gt_box(pred_record, gt_records, iou_threshold=0.5):
'''
Search gt_records list and try to find a matching box for the predict box
Param
pred_record: with format ['image_file', 'xmin,ymin,xmax,ymax', score]
gt_records: record list with format
[
['image_file', 'xmin,ymin,xmax,ymax', 'usage'],
['image_file', 'xmin,ymin,xmax,ymax', 'usage'],
...
]
iou_threshold:
pred_record and gt_records should be from same annotation image file
Return
matching gt_record index. -1 when there's no matching gt
'''
max_iou = 0.0
max_index = -1
#get predict box coordinate
pred_box = [float(x) for x in pred_record[1].split(',')]
for i, gt_record in enumerate(gt_records):
#get ground truth box coordinate
gt_box = [float(x) for x in gt_record[1].split(',')]
iou = box_iou(pred_box, gt_box)
# if the ground truth has been assigned to other
# prediction, we couldn't reuse it
if iou > max_iou and gt_record[2] == 'unused' and pred_record[0] == gt_record[0]:
max_iou = iou
max_index = i
# drop the prediction if couldn't match iou threshold
if max_iou < iou_threshold:
max_index = -1
return max_index
def voc_ap(rec, prec):
"""
--- Official matlab code VOC2012---
mrec=[0 ; rec ; 1];
mpre=[0 ; prec ; 0];
for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
end
i=find(mrec(2:end)~=mrec(1:end-1))+1;
ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
"""
rec.insert(0, 0.0) # insert 0.0 at begining of list
rec.append(1.0) # insert 1.0 at end of list
mrec = rec[:]
prec.insert(0, 0.0) # insert 0.0 at begining of list
prec.append(0.0) # insert 0.0 at end of list
mpre = prec[:]
"""
This part makes the precision monotonically decreasing
(goes from the end to the beginning)
"""
# matlab indexes start in 1 but python in 0, so I have to do:
# range(start=(len(mpre) - 2), end=0, step=-1)
# also the python function range excludes the end, resulting in:
# range(start=(len(mpre) - 2), end=-1, step=-1)
for i in range(len(mpre) - 2, -1, -1):
mpre[i] = max(mpre[i], mpre[i + 1])
"""
This part creates a list of indexes where the recall changes
"""
# matlab: i=find(mrec(2:end)~=mrec(1:end-1))+1;
i_list = []
for i in range(1, len(mrec)):
if mrec[i] != mrec[i - 1]:
i_list.append(i) # if it was matlab would be i + 1
"""
The Average Precision (AP) is the area under the curve
(numerical integration)
"""
# matlab: ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
ap = 0.0
for i in i_list:
ap += ((mrec[i] - mrec[i - 1]) * mpre[i])
return ap, mrec, mpre
'''
def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
i = np.where(mrec[1:] != mrec[:-1])[0]
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap, mrec, mpre
'''
def get_rec_prec(true_positive, false_positive, gt_records):
'''
Calculate precision/recall based on true_positive, false_positive
result.
'''
cumsum = 0
for idx, val in enumerate(false_positive):
false_positive[idx] += cumsum
cumsum += val
cumsum = 0
for idx, val in enumerate(true_positive):
true_positive[idx] += cumsum
cumsum += val
rec = true_positive[:]
for idx, val in enumerate(true_positive):
rec[idx] = (float(true_positive[idx]) / len(gt_records)) if len(gt_records) != 0 else 0
prec = true_positive[:]
for idx, val in enumerate(true_positive):
prec[idx] = float(true_positive[idx]) / (false_positive[idx] + true_positive[idx])
return rec, prec
def draw_rec_prec(rec, prec, mrec, mprec, class_name, ap):
"""
Draw plot
"""
plt.plot(rec, prec, '-o')
# add a new penultimate point to the list (mrec[-2], 0.0)
# since the last line segment (and respective area) do not affect the AP value
area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]
area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]
plt.fill_between(area_under_curve_x, 0, area_under_curve_y, alpha=0.2, edgecolor='r')
# set window title
fig = plt.gcf() # gcf - get current figure
fig.canvas.set_window_title('AP ' + class_name)
# set plot title
plt.title('class: ' + class_name + ' AP = {}%'.format(ap*100))
#plt.suptitle('This is a somewhat long figure title', fontsize=16)
# set axis titles
plt.xlabel('Recall')
plt.ylabel('Precision')
# optional - set axes
axes = plt.gca() # gca - get current axes
axes.set_xlim([0.0,1.0])
axes.set_ylim([0.0,1.05]) # .05 to give some extra space
# Alternative option -> wait for button to be pressed
#while not plt.waitforbuttonpress(): pass # wait for key display
# Alternative option -> normal display
#plt.show()
# save the plot
rec_prec_plot_path = os.path.join('result','classes')
os.makedirs(rec_prec_plot_path, exist_ok=True)
fig.savefig(os.path.join(rec_prec_plot_path, class_name + ".png"))
plt.cla() # clear axes for next plot
import bokeh
import bokeh.io as bokeh_io
import bokeh.plotting as bokeh_plotting
def generate_rec_prec_html(mrec, mprec, scores, class_name, ap):
"""
generate dynamic P-R curve HTML page for each class
"""
# bypass invalid class
if len(mrec) == 0 or len(mprec) == 0 or len(scores) == 0:
return
rec_prec_plot_path = os.path.join('result' ,'classes')
os.makedirs(rec_prec_plot_path, exist_ok=True)
bokeh_io.output_file(os.path.join(rec_prec_plot_path, class_name + '.html'), title='P-R curve for ' + class_name)
# prepare curve data
area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]
area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]
score_on_curve = [0.0] + scores[:-1] + [0.0] + [scores[-1]] + [1.0]
source = bokeh.models.ColumnDataSource(data={
'rec' : area_under_curve_x,
'prec' : area_under_curve_y,
'score' : score_on_curve,
})
# prepare plot figure
plt_title = 'class: ' + class_name + ' AP = {}%'.format(ap*100)
plt = bokeh_plotting.figure(plot_height=200 ,plot_width=200, tools="", toolbar_location=None,
title=plt_title, sizing_mode="scale_width")
plt.background_fill_color = "#f5f5f5"
plt.grid.grid_line_color = "white"
plt.xaxis.axis_label = 'Recall'
plt.yaxis.axis_label = 'Precision'
plt.axis.axis_line_color = None
# draw curve data
plt.line(x='rec', y='prec', line_width=2, color='#ebbd5b', source=source)
plt.add_tools(bokeh.models.HoverTool(
tooltips=[
( 'score', '@score{0.0000 a}'),
( 'Prec', '@prec'),
( 'Recall', '@rec'),
],
formatters={
'rec' : 'printf',
'prec' : 'printf',
},
mode='vline'
))
bokeh_io.save(plt)
return
def adjust_axes(r, t, fig, axes):
"""
Plot - adjust axes
"""
# get text width for re-scaling
bb = t.get_window_extent(renderer=r)
text_width_inches = bb.width / fig.dpi
# get axis width in inches
current_fig_width = fig.get_figwidth()
new_fig_width = current_fig_width + text_width_inches
propotion = new_fig_width / current_fig_width
# get axis limit
x_lim = axes.get_xlim()
axes.set_xlim([x_lim[0], x_lim[1]*propotion])
def draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):
"""
Draw plot using Matplotlib
"""
# sort the dictionary by decreasing value, into a list of tuples
sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))
# unpacking the list of tuples into two lists
sorted_keys, sorted_values = zip(*sorted_dic_by_value)
#
if true_p_bar != "":
"""
Special case to draw in (green=true predictions) & (red=false predictions)
"""
fp_sorted = []
tp_sorted = []
for key in sorted_keys:
fp_sorted.append(dictionary[key] - true_p_bar[key])
tp_sorted.append(true_p_bar[key])
plt.barh(range(n_classes), fp_sorted, align='center', color='crimson', label='False Predictions')
plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Predictions', left=fp_sorted)
# add legend
plt.legend(loc='lower right')
"""
Write number on side of bar
"""
fig = plt.gcf() # gcf - get current figure
axes = plt.gca()
r = fig.canvas.get_renderer()
for i, val in enumerate(sorted_values):
fp_val = fp_sorted[i]
tp_val = tp_sorted[i]
fp_str_val = " " + str(fp_val)
tp_str_val = fp_str_val + " " + str(tp_val)
# trick to paint multicolor with offset:
# first paint everything and then repaint the first number
t = plt.text(val, i, tp_str_val, color='forestgreen', va='center', fontweight='bold')
plt.text(val, i, fp_str_val, color='crimson', va='center', fontweight='bold')
if i == (len(sorted_values)-1): # largest bar
adjust_axes(r, t, fig, axes)
else:
plt.barh(range(n_classes), sorted_values, color=plot_color)
"""
Write number on side of bar
"""
fig = plt.gcf() # gcf - get current figure
axes = plt.gca()
r = fig.canvas.get_renderer()
for i, val in enumerate(sorted_values):
str_val = " " + str(val) # add a space before
if val < 1.0:
str_val = " {0:.2f}".format(val)
t = plt.text(val, i, str_val, color=plot_color, va='center', fontweight='bold')
# re-set axes to show number inside the figure
if i == (len(sorted_values)-1): # largest bar
adjust_axes(r, t, fig, axes)
# set window title
fig.canvas.set_window_title(window_title)
# write classes in y axis
tick_font_size = 12
plt.yticks(range(n_classes), sorted_keys, fontsize=tick_font_size)
"""
Re-scale height accordingly
"""
init_height = fig.get_figheight()
# comput the matrix height in points and inches
dpi = fig.dpi
height_pt = n_classes * (tick_font_size * 1.4) # 1.4 (some spacing)
height_in = height_pt / dpi
# compute the required figure height
top_margin = 0.15 # in percentage of the figure height
bottom_margin = 0.05 # in percentage of the figure height
figure_height = height_in / (1 - top_margin - bottom_margin)
# set new height
if figure_height > init_height:
fig.set_figheight(figure_height)
# set plot title
plt.title(plot_title, fontsize=14)
# set axis titles
# plt.xlabel('classes')
plt.xlabel(x_label, fontsize='large')
# adjust size of window
fig.tight_layout()
# save the plot
fig.savefig(output_path)
# show image
if to_show:
plt.show()
# close the plot
plt.close()
def calc_AP(gt_records, pred_records, class_name, iou_threshold, show_result):
'''
Calculate AP value for one class records
Param
gt_records: ground truth records list for one class, with format:
[
['image_file', 'xmin,ymin,xmax,ymax'],
['image_file', 'xmin,ymin,xmax,ymax'],
...
]
pred_records: predict records for one class, with format (in score descending order):
[
['image_file', 'xmin,ymin,xmax,ymax', score],
['image_file', 'xmin,ymin,xmax,ymax', score],
...
]
Return
AP value for the class
'''
# append usage flag in gt_records for matching gt search
gt_records = [gt_record + ['unused'] for gt_record in gt_records]
# prepare score list for generating P-R html page
scores = [pred_record[2] for pred_record in pred_records]
# init true_positive and false_positive list
nd = len(pred_records) # number of predict data
true_positive = [0] * nd
false_positive = [0] * nd
true_positive_count = 0
# assign predictions to ground truth objects
for idx, pred_record in enumerate(pred_records):
# filter out gt record from same image
image_gt_records = [ gt_record for gt_record in gt_records if gt_record[0] == pred_record[0]]
i = match_gt_box(pred_record, image_gt_records, iou_threshold=iou_threshold)
if i != -1:
# find a valid gt obj to assign, set
# true_positive list and mark image_gt_records.
#
# trick: gt_records will also be marked
# as 'used', since image_gt_records is a
# reference list
image_gt_records[i][2] = 'used'
true_positive[idx] = 1
true_positive_count += 1
else:
false_positive[idx] = 1
# compute precision/recall
rec, prec = get_rec_prec(true_positive, false_positive, gt_records)
ap, mrec, mprec = voc_ap(rec, prec)
if show_result:
draw_rec_prec(rec, prec, mrec, mprec, class_name, ap)
generate_rec_prec_html(mrec, mprec, scores, class_name, ap)
return ap, true_positive_count
def plot_Pascal_AP_result(count_images, count_true_positives, num_classes,
gt_counter_per_class, pred_counter_per_class,
precision_dict, recall_dict, mPrec, mRec,
APs, mAP, iou_threshold):
'''
Plot the total number of occurences of each class in the ground-truth
'''
window_title = "Ground-Truth Info"
plot_title = "Ground-Truth\n" + "(" + str(count_images) + " files and " + str(num_classes) + " classes)"
x_label = "Number of objects per class"
output_path = os.path.join('result','Ground-Truth_Info.png')
draw_plot_func(gt_counter_per_class, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar='')
'''
Plot the total number of occurences of each class in the "predicted" folder
'''
window_title = "Predicted Objects Info"
# Plot title
plot_title = "Predicted Objects\n" + "(" + str(count_images) + " files and "
count_non_zero_values_in_dictionary = sum(int(x) > 0 for x in list(pred_counter_per_class.values()))
plot_title += str(count_non_zero_values_in_dictionary) + " detected classes)"
# end Plot title
x_label = "Number of objects per class"
output_path = os.path.join('result','Predicted_Objects_Info.png')
draw_plot_func(pred_counter_per_class, len(pred_counter_per_class), window_title, plot_title, x_label, output_path, to_show=False, plot_color='forestgreen', true_p_bar=count_true_positives)
'''
Draw mAP plot (Show AP's of all classes in decreasing order)
'''
window_title = "mAP"
plot_title = "mAP@IoU={0}: {1:.2f}%".format(iou_threshold, mAP)
x_label = "Average Precision"
output_path = os.path.join('result','mAP.png')
draw_plot_func(APs, num_classes, window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
'''
Draw Precision plot (Show Precision of all classes in decreasing order)
'''
window_title = "Precision"
plot_title = "mPrec@IoU={0}: {1:.2f}%".format(iou_threshold, mPrec)
x_label = "Precision rate"
output_path = os.path.join('result','Precision.png')
draw_plot_func(precision_dict, len(precision_dict), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
'''
Draw Recall plot (Show Recall of all classes in decreasing order)
'''
window_title = "Recall"
plot_title = "mRec@IoU={0}: {1:.2f}%".format(iou_threshold, mRec)
x_label = "Recall rate"
output_path = os.path.join('result','Recall.png')
draw_plot_func(recall_dict, len(recall_dict), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
def get_mean_metric(metric_records, gt_classes_records):
'''
Calculate mean metric, but only count classes which have ground truth object
Param
metric_records: metric dict like:
metric_records = {
'aeroplane': 0.79,
'bicycle': 0.79,
...
'tvmonitor': 0.71,
}
gt_classes_records: ground truth class dict like:
gt_classes_records = {
'car': [
['000001.jpg','100,120,200,235'],
['000002.jpg','85,63,156,128'],
...
],
...
}
Return
mean_metric: float value of mean metric
'''
mean_metric = 0.0
count = 0
for (class_name, metric) in metric_records.items():
if (class_name in gt_classes_records) and (len(gt_classes_records[class_name]) != 0):
mean_metric += metric
count += 1
mean_metric = (mean_metric/count)*100 if count != 0 else 0.0
return mean_metric
def compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold, show_result=True):
'''
Compute PascalVOC style mAP
'''
APs = {}
count_true_positives = {class_name: 0 for class_name in list(gt_classes_records.keys())}
#get AP value for each of the ground truth classes
for _, class_name in enumerate(class_names):
#if there's no gt obj for a class, record 0
if class_name not in gt_classes_records:
APs[class_name] = 0.
continue
gt_records = gt_classes_records[class_name]
#if we didn't detect any obj for a class, record 0
if class_name not in pred_classes_records:
APs[class_name] = 0.
continue
pred_records = pred_classes_records[class_name]
ap, true_positive_count = calc_AP(gt_records, pred_records, class_name, iou_threshold, show_result)
APs[class_name] = ap
count_true_positives[class_name] = true_positive_count
#sort AP result by value, in descending order
APs = OrderedDict(sorted(APs.items(), key=operator.itemgetter(1), reverse=True))
#get mAP percentage value
#mAP = np.mean(list(APs.values()))*100
mAP = get_mean_metric(APs, gt_classes_records)
#get GroundTruth count per class
gt_counter_per_class = {}
for (class_name, info_list) in gt_classes_records.items():
gt_counter_per_class[class_name] = len(info_list)
#get Precision count per class
pred_counter_per_class = {class_name: 0 for class_name in list(gt_classes_records.keys())}
for (class_name, info_list) in pred_classes_records.items():
pred_counter_per_class[class_name] = len(info_list)
#get the precision & recall
precision_dict = {}
recall_dict = {}
for (class_name, gt_count) in gt_counter_per_class.items():
if (class_name not in pred_counter_per_class) or (class_name not in count_true_positives) or pred_counter_per_class[class_name] == 0:
precision_dict[class_name] = 0.
else:
precision_dict[class_name] = float(count_true_positives[class_name]) / pred_counter_per_class[class_name]
if class_name not in count_true_positives or gt_count == 0:
recall_dict[class_name] = 0.
else:
recall_dict[class_name] = float(count_true_positives[class_name]) / gt_count
#get mPrec, mRec
#mPrec = np.mean(list(precision_dict.values()))*100
#mRec = np.mean(list(recall_dict.values()))*100
mPrec = get_mean_metric(precision_dict, gt_classes_records)
mRec = get_mean_metric(recall_dict, gt_classes_records)
if show_result:
plot_Pascal_AP_result(len(annotation_records), count_true_positives, len(gt_classes_records),
gt_counter_per_class, pred_counter_per_class,
precision_dict, recall_dict, mPrec, mRec,
APs, mAP, iou_threshold)
#show result
print('\nPascal VOC AP evaluation')
for (class_name, AP) in APs.items():
print('%s: AP %.4f, precision %.4f, recall %.4f' % (class_name, AP, precision_dict[class_name], recall_dict[class_name]))
print('mAP@IoU=%.2f result: %f' % (iou_threshold, mAP))
print('mPrec@IoU=%.2f result: %f' % (iou_threshold, mPrec))
print('mRec@IoU=%.2f result: %f' % (iou_threshold, mRec))
#return mAP percentage value
return mAP, APs
def compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names, class_filter=None, show_result=True):
'''
Compute MSCOCO AP list on AP 0.5:0.05:0.95
'''
iou_threshold_list = [x/100 for x in range(50, 100, 5)]
APs = {}
pbar = tqdm(total=len(iou_threshold_list), desc='Eval COCO')
for iou_threshold in iou_threshold_list:
iou_threshold = round(iou_threshold, 2)
mAP, mAPs = compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold, show_result=False)
if class_filter is not None:
mAP = get_filter_class_mAP(mAPs, class_filter, show_result=False)
APs[iou_threshold] = round(mAP, 6)
pbar.update(1)
pbar.close()
#sort AP result by value, in descending order
APs = OrderedDict(sorted(APs.items(), key=operator.itemgetter(1), reverse=True))
#get overall AP percentage value
AP = np.mean(list(APs.values()))
if show_result:
'''
Draw MS COCO AP plot
'''
os.makedirs('result', exist_ok=True)
window_title = "MSCOCO AP on different IOU"
plot_title = "COCO AP = {0:.2f}%".format(AP)
x_label = "Average Precision"
output_path = os.path.join('result','COCO_AP.png')
draw_plot_func(APs, len(APs), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
print('\nMS COCO AP evaluation')
for (iou_threshold, AP_value) in APs.items():
print('IOU %.2f: AP %f' % (iou_threshold, AP_value))
print('total AP: %f' % (AP))
#return AP percentage value
return AP, APs
def compute_AP_COCO_Scale(annotation_records, scale_gt_classes_records, pred_classes_records, class_names):
'''
Compute MSCOCO AP on different scale object: small, medium, large
'''
scale_APs = {}
for scale_key in ['small','medium','large']:
gt_classes_records = scale_gt_classes_records[scale_key]
scale_AP, _ = compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names, show_result=False)
scale_APs[scale_key] = round(scale_AP, 4)
#get overall AP percentage value
scale_mAP = np.mean(list(scale_APs.values()))
'''
Draw Scale AP plot
'''
os.makedirs('result', exist_ok=True)
window_title = "MSCOCO AP on different scale"
plot_title = "scale mAP = {0:.2f}%".format(scale_mAP)
x_label = "Average Precision"
output_path = os.path.join('result','COCO_scale_AP.png')
draw_plot_func(scale_APs, len(scale_APs), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
'''
Draw Scale Object Sum plot
'''
for scale_key in ['small','medium','large']:
gt_classes_records = scale_gt_classes_records[scale_key]
gt_classes_sum = {}
for _, class_name in enumerate(class_names):
# summarize the gt object number for every class on different scale
gt_classes_sum[class_name] = np.sum(len(gt_classes_records[class_name])) if class_name in gt_classes_records else 0
total_sum = np.sum(list(gt_classes_sum.values()))
window_title = "{} object number".format(scale_key)
plot_title = "total {} object number = {}".format(scale_key, total_sum)
x_label = "Object Number"
output_path = os.path.join('result','{}_object_number.png'.format(scale_key))
draw_plot_func(gt_classes_sum, len(gt_classes_sum), window_title, plot_title, x_label, output_path, to_show=False, plot_color='royalblue', true_p_bar='')
print('\nMS COCO AP evaluation on different scale')
for (scale, AP_value) in scale_APs.items():
print('%s scale: AP %f' % (scale, AP_value))
print('total AP: %f' % (scale_mAP))
def add_gt_record(gt_records, gt_record, class_name):
# append or add ground truth class item
if class_name in gt_records:
gt_records[class_name].append(gt_record)
else:
gt_records[class_name] = list([gt_record])
return gt_records
def get_scale_gt_dict(gt_classes_records, class_names):
'''
Get ground truth class dict on different object scales, according to MS COCO metrics definition:
small objects: area < 32^2
medium objects: 32^2 < area < 96^2
large objects: area > 96^2
input gt_classes_records would be like:
gt_classes_records = {
'car': [
['000001.jpg','100,120,200,235'],
['000002.jpg','85,63,156,128'],
...
],
...
}
return a record dict with following format, for AP/AR eval on different scale:
scale_gt_classes_records = {
'small': {
'car': [
['000001.jpg','100,120,200,235'],
['000002.jpg','85,63,156,128'],
...
],
...
},
'medium': {
'car': [
['000003.jpg','100,120,200,235'],
['000004.jpg','85,63,156,128'],
...
],
...
},
'large': {
'car': [
['000005.jpg','100,120,200,235'],
['000006.jpg','85,63,156,128'],
...
],
...
}
}
'''
scale_gt_classes_records = {}
small_gt_records = {}
medium_gt_records = {}
large_gt_records = {}
for _, class_name in enumerate(class_names):
gt_records = gt_classes_records[class_name]
for (image_file, box) in gt_records:
# get box area based on coordinate
box_coord = [int(p) for p in box.split(',')]
box_area = (box_coord[2] - box_coord[0]) * (box_coord[3] - box_coord[1])
# add to corresponding gt records dict according to area size
if box_area <= 32*32:
small_gt_records = add_gt_record(small_gt_records, [image_file, box], class_name)
elif box_area > 32*32 and box_area <= 96*96:
medium_gt_records = add_gt_record(medium_gt_records, [image_file, box], class_name)
elif box_area > 96*96:
large_gt_records = add_gt_record(large_gt_records, [image_file, box], class_name)
# form up scale_gt_classes_records
scale_gt_classes_records['small'] = small_gt_records
scale_gt_classes_records['medium'] = medium_gt_records
scale_gt_classes_records['large'] = large_gt_records
return scale_gt_classes_records
def get_filter_class_mAP(APs, class_filter, show_result=True):
filtered_mAP = 0.0
filtered_APs = OrderedDict()
for (class_name, AP) in APs.items():
if class_name in class_filter:
filtered_APs[class_name] = AP
filtered_mAP = np.mean(list(filtered_APs.values()))*100
if show_result:
print('\nfiltered classes AP')
for (class_name, AP) in filtered_APs.items():
print('%s: AP %.4f' % (class_name, AP))
print('mAP:', filtered_mAP, '\n')
return filtered_mAP
def eval_AP(model, model_format, annotation_lines, anchors, class_names, model_input_shape, eval_type, iou_threshold, conf_threshold, elim_grid_sense, v5_decode, save_result, class_filter=None):
'''
Compute AP for detection model on annotation dataset
'''
annotation_records, gt_classes_records = annotation_parse(annotation_lines, class_names)
pred_classes_records = get_prediction_class_records(model, model_format, annotation_records, anchors, class_names, model_input_shape, conf_threshold, elim_grid_sense, v5_decode, save_result)
AP = 0.0
if eval_type == 'VOC':
AP, APs = compute_mAP_PascalVOC(annotation_records, gt_classes_records, pred_classes_records, class_names, iou_threshold)
if class_filter is not None:
get_filter_class_mAP(APs, class_filter)
elif eval_type == 'COCO':
AP, _ = compute_AP_COCO(annotation_records, gt_classes_records, pred_classes_records, class_names, class_filter)
# get AP for different scale: small, medium, large
scale_gt_classes_records = get_scale_gt_dict(gt_classes_records, class_names)
compute_AP_COCO_Scale(annotation_records, scale_gt_classes_records, pred_classes_records, class_names)
else:
raise ValueError('Unsupported evaluation type')
return AP
#load TF 1.x frozen pb graph
def load_graph(model_path):
# check tf version to be compatible with TF 2.x
global tf
if tf.__version__.startswith('2'):
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
# We parse the graph_def file
with tf.gfile.GFile(model_path, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
# We load the graph_def in the default graph
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
name="graph",
op_dict=None,
producer_op_list=None
)
return graph
def load_eval_model(model_path):
# support of tflite model
if model_path.endswith('.tflite'):
from tensorflow.lite.python import interpreter as interpreter_wrapper
model = interpreter_wrapper.Interpreter(model_path=model_path)
model.allocate_tensors()
model_format = 'TFLITE'
# support of MNN model
elif model_path.endswith('.mnn'):
model = MNN.Interpreter(model_path)
model_format = 'MNN'
# support of TF 1.x frozen pb model
elif model_path.endswith('.pb'):
model = load_graph(model_path)
model_format = 'PB'
# support of ONNX model
elif model_path.endswith('.onnx'):
model = onnxruntime.InferenceSession(model_path)
model_format = 'ONNX'
# normal keras h5 model
elif model_path.endswith('.h5'):
custom_object_dict = get_custom_objects()
model = load_model(model_path, compile=False, custom_objects=custom_object_dict)
model_format = 'H5'
K.set_learning_phase(0)
else:
raise ValueError('invalid model file')
return model, model_format
def main():
# class YOLO defines the default value, so suppress any default here
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, description='evaluate YOLO model (h5/pb/onnx/tflite/mnn) with test dataset')
'''
Command line options
'''
parser.add_argument(
'--model_path', type=str, required=True,
help='path to model file')
parser.add_argument(
'--anchors_path', type=str, required=True,
help='path to anchor definitions')
parser.add_argument(
'--classes_path', type=str, required=False,
help='path to class definitions, default=%(default)s', default=os.path.join('configs' , 'voc_classes.txt'))
parser.add_argument(
'--classes_filter_path', type=str, required=False,
help='path to class filter definitions, default=%(default)s', default=None)
parser.add_argument(
'--annotation_file', type=str, required=True,
help='test annotation txt file')
parser.add_argument(
'--eval_type', type=str, required=False, choices=['VOC', 'COCO'],
help='evaluation type (VOC/COCO), default=%(default)s', default='VOC')
parser.add_argument(
'--iou_threshold', type=float,
help='IOU threshold for PascalVOC mAP, default=%(default)s', default=0.5)
parser.add_argument(
'--conf_threshold', type=float,
help='confidence threshold for filtering box in postprocess, default=%(default)s', default=0.001)
parser.add_argument(
'--model_input_shape', type=str,
help='model image input shape as <height>x<width>, default=%(default)s', default='416x416')
parser.add_argument(
'--elim_grid_sense', default=False, action="store_true",
help = "Eliminate grid sensitivity")
parser.add_argument(
'--v5_decode', default=False, action="store_true",
help = "Use YOLOv5 prediction decode")
parser.add_argument(
'--save_result', default=False, action="store_true",
help='Save the detection result image in result/detection dir'
)
args = parser.parse_args()
# param parse
anchors = get_anchors(args.anchors_path)
class_names = get_classes(args.classes_path)
height, width = args.model_input_shape.split('x')
model_input_shape = (int(height), int(width))
assert (model_input_shape[0]%32 == 0 and model_input_shape[1]%32 == 0), 'model_input_shape should be multiples of 32'
# class filter parse
if args.classes_filter_path is not None:
class_filter = get_classes(args.classes_filter_path)
else:
class_filter = None
annotation_lines = get_dataset(args.annotation_file, shuffle=False)
model, model_format = load_eval_model(args.model_path)
start = time.time()
eval_AP(model, model_format, annotation_lines, anchors, class_names, model_input_shape, args.eval_type, args.iou_threshold, args.conf_threshold, args.elim_grid_sense, args.v5_decode, args.save_result, class_filter=class_filter)
end = time.time()
print("Evaluation time cost: {:.6f}s".format(end - start))
if __name__ == '__main__':
main()
|
[] |
[] |
[
"TF_CPP_MIN_LOG_LEVEL"
] |
[]
|
["TF_CPP_MIN_LOG_LEVEL"]
|
python
| 1 | 0 | |
proj.android/build_native.py
|
#!/usr/bin/python
# build_native.py
# Build native codes
import sys
import os, os.path
import shutil
from optparse import OptionParser
def check_environment_variables_sdk():
''' Checking the environment ANDROID_SDK_ROOT, which will be used for building
'''
try:
SDK_ROOT = os.environ['ANDROID_SDK_ROOT']
except Exception:
print "ANDROID_SDK_ROOT not defined. Please define ANDROID_SDK_ROOT in your environment"
sys.exit(1)
return SDK_ROOT
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment"
sys.exit(1)
return NDK_ROOT
def select_toolchain_version():
'''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when
using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist.
Conclution:
ndk-r8e -> use gcc4.7
ndk-r9 -> use gcc4.8
'''
ndk_root = check_environment_variables()
if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8'
print "The Selected NDK toolchain version was 4.8 !"
elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7'
print "The Selected NDK toolchain version was 4.7 !"
else:
print "Couldn't find the gcc toolchain."
exit(1)
def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,android_platform,build_mode):
ndk_path = os.path.join(ndk_root, "ndk-build")
# windows should use ";" to seperate module paths
platform = sys.platform
if platform == 'win32':
ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root)
else:
ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root)
if ndk_build_param == None:
command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path)
else:
command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path)
if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
elif android_platform is not None:
sdk_tool_path = os.path.join(sdk_root, "tools/android")
cocoslib_path = os.path.join(cocos_root, "cocos/2d/platform/android/java")
command = '%s update lib-project -t %s -p %s' % (sdk_tool_path,android_platform,cocoslib_path)
if os.system(command) != 0:
raise Exception("update cocos lib-project [ " + cocoslib_path + " ] fails!")
command = '%s update project -t %s -p %s -s' % (sdk_tool_path,android_platform,app_android_root)
if os.system(command) != 0:
raise Exception("update project [ " + app_android_root + " ] fails!")
buildfile_path = os.path.join(app_android_root, "build.xml")
command = 'ant clean %s -f %s -Dsdk.dir=%s' % (build_mode,buildfile_path,sdk_root)
os.system(command)
def copy_files(src, dst):
for item in os.listdir(src):
path = os.path.join(src, item)
# Android can not package the file that ends with ".gz"
if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path):
shutil.copy(path, dst)
if os.path.isdir(path):
new_dst = os.path.join(dst, item)
os.mkdir(new_dst)
copy_files(path, new_dst)
def copy_resources(app_android_root):
# remove app_android_root/assets if it exists
assets_dir = os.path.join(app_android_root, "assets")
if os.path.isdir(assets_dir):
shutil.rmtree(assets_dir)
# copy resources
os.mkdir(assets_dir)
resources_dir = os.path.join(app_android_root, "../Resources")
if os.path.isdir(resources_dir):
copy_files(resources_dir, assets_dir)
def build(ndk_build_param,android_platform,build_mode):
ndk_root = check_environment_variables()
sdk_root = None
select_toolchain_version()
current_dir = os.path.dirname(os.path.realpath(__file__))
cocos_root = os.path.join(current_dir, "../cocos2d")
app_android_root = current_dir
copy_resources(app_android_root)
if android_platform is not None:
sdk_root = check_environment_variables_sdk()
if android_platform.isdigit():
android_platform = 'android-'+android_platform
else:
print 'please use vaild android platform'
exit(1)
if build_mode is None:
build_mode = 'debug'
elif build_mode != 'release':
build_mode = 'debug'
do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,android_platform,build_mode)
# -------------- main --------------
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
(opts, args) = parser.parse_args()
build(opts.ndk_build_param,opts.android_platform,opts.build_mode)
|
[] |
[] |
[
"NDK_TOOLCHAIN_VERSION",
"ANDROID_SDK_ROOT",
"NDK_ROOT"
] |
[]
|
["NDK_TOOLCHAIN_VERSION", "ANDROID_SDK_ROOT", "NDK_ROOT"]
|
python
| 3 | 0 | |
auth.go
|
package gopherb2
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/spf13/viper"
"github.com/uber-go/zap"
)
// APIAuthorization.Minimum Part Size deprecated and will match recommended part size
type APIAuthorization struct {
AccountID string `json:"accountId"`
ApiURL string `json:"apiUrl"`
AuthorizationToken string `json:"authorizationToken"`
DownloadURL string `json:"downloadURL"`
MinimumPartSize int `json:"minimumPartSize"`
RecommendedPartSize int `json:"recommendedPartSize"`
AbsoluteMinPartSize int `json:"absoluteMinimumPartSize"`
}
// Calling this function reads settings.toml file in "/config" , calls B2 API , then returns the response as APIAuthorization struct
func AuthorizeAcct() APIAuthorization {
var Config Configuration
viper.SetConfigName("settings") // no need to include file extension
viper.AddConfigPath("$GOPATH/src/github.com/dwin/gopherb2/config") // set the path of your config file
err := viper.ReadInConfig()
viper.AddConfigPath("config") // set the path of your config file
err = viper.ReadInConfig()
if err != nil {
logger.Debug("No Configuration file found, Cannot Attempt Authorization with API. Checking ENV.")
Config.AcctID = os.Getenv("B2AcctID")
Config.AppID = os.Getenv("B2AppID")
Config.APIURL = os.Getenv("B2APIURL")
} else {
Config.AcctID = viper.GetString("Account1.AcctID")
logger.Debug("Obtained Account ID from Configuration file",
zap.String("Account ID:", Config.AcctID),
)
Config.AppID = viper.GetString("Account1.AppID")
logger.Debug("Obtained Account ID from Configuration file",
zap.String("Application ID:", Config.AppID),
)
Config.APIURL = viper.GetString("Account1.APIURL")
logger.Debug("Obtained Account ID from Configuration file",
zap.String("API URL:", Config.APIURL),
)
}
if Config.AcctID == "" {
logger.Fatal("Account ID set to default. Update with your Account Id from Backblaze Settings.")
} else if Config.AppID == "" {
logger.Fatal("Application ID set to default. Update with your Application Id from Backblaze Settings.")
}
// Encode credentials to base64
credentials := base64.StdEncoding.EncodeToString([]byte(Config.AcctID + ":" + Config.AppID))
// Request (POST https://api.backblazeb2.com/b2api/v1/b2_authorize_account)
body := bytes.NewBuffer([]byte(`{}`))
logger.Debug("Preparing to send API Auth Request")
// Create client
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", Config.APIURL+"b2_authorize_account", body)
if err != nil {
logger.Fatal("Creating API Auth Request Failed.",
zap.Error(err),
)
}
// Headers
req.Header.Add("Authorization", "Basic "+credentials)
req.Header.Add("Content-Type", "application/json; charset=utf-8")
// Fetch Request
resp, err := client.Do(req)
if err != nil {
logger.Fatal("API Auth Request Failed.",
zap.Error(err),
)
}
logger.Debug("Received API Authorization response.")
var apiAuth APIAuthorization
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
err = json.Unmarshal(respBody, &apiAuth)
if err != nil {
fmt.Println("API Auth JSON Parse Failed", err)
logger.Fatal("Cannot parse API Auth Response JSON.",
zap.Error(err),
)
}
if resp.Status != "200 OK" {
logger.Fatal("Authorization with Backblaze B2 API Failed",
zap.String("API Resp Body:", string(respBody)),
)
}
// Check API Response matches config
if apiAuth.AccountID != Config.AcctID {
logger.Fatal("API Account ID Response does not match Account ID in Config.",
zap.String("API Resp Acct ID", apiAuth.AccountID),
zap.String("Config Acct ID", Config.AcctID),
)
}
return apiAuth
}
// Requests Upload URL from API and returns 'UploadURL'
func B2GetUploadURL(bucketId string) UploadURL {
// Authorize and Get API Token
authorizationResponse := AuthorizeAcct()
// Get Upload URL (POST https://api001.backblazeb2.com/b2api/v1/b2_get_upload_url)
jsonData := []byte(`{"bucketId": "` + bucketId + `"}`)
body := bytes.NewBuffer(jsonData)
// Create client
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", authorizationResponse.ApiURL+"/b2api/v1/b2_get_upload_url", body)
// Headers
req.Header.Add("Authorization", authorizationResponse.AuthorizationToken)
req.Header.Add("Content-Type", "application/json; charset=utf-8")
logger.Debug("Preparing to send Get Upload URL request.")
// Fetch Request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Failure : ", err)
}
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
var apiResponse Response
apiResponse = Response{Header: resp.Header, Status: resp.Status, Body: respBody}
var uploadURL UploadURL
err = json.Unmarshal(apiResponse.Body, &uploadURL)
if err != nil {
logger.Fatal("Bucket JSON Parse Failed",
zap.Error(err),
)
}
logger.Debug("Get Upload URL response received from API")
return uploadURL
}
func B2FinishLargeFile(largeFile LargeFile) error {
apiAuth := AuthorizeAcct()
// Create SHA1 array of completed files
var partSha1Array string
var buffer bytes.Buffer
for i := 0; i < len(largeFile.Temp); i++ {
buffer.WriteString("\u0022") // Add double quotation mark --> "
buffer.WriteString(largeFile.Temp[i].SHA1)
buffer.WriteString("\u0022")
if i != len(largeFile.Temp)-1 {
buffer.WriteString(",") // Only add trailing comma if item is not last
}
}
partSha1Array = buffer.String()
// Create client
client := &http.Client{}
// Request Body : JSON object with fileID & array of SHA1 hashes of files transmitted
jsonBody := []byte(`{"fileId": "` + largeFile.FileID + `", "partSha1Array":[` + partSha1Array + `]}`)
body := bytes.NewBuffer(jsonBody)
// Create request
req, err := http.NewRequest("POST", apiAuth.ApiURL+"/b2api/v1/b2_finish_large_file", body)
// Headers
req.Header.Add("Authorization", apiAuth.AuthorizationToken)
// Fetch Request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Failure : ", err)
}
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if resp.Status != "200 OK" {
logger.Warn("Finish B2 Large File Failed",
zap.String("HTTP Status Response", resp.Status),
zap.String("HTTP Resp Body", string(respBody)),
)
}
if resp.Status == "200 OK" {
logger.Info("Finish Large File Upload Completed",
zap.String("Filepath", largeFile.OrigPath),
zap.String("B2 File ID", largeFile.FileID),
)
}
return err
}
func B2GetUploadPartURL(fileId string) UploadPartResponse {
apiAuth := AuthorizeAcct()
// Create client
client := &http.Client{}
// Request Body : JSON object with fileId
jsonBody := []byte(`{"fileId": "` + fileId + `"}`)
body := bytes.NewBuffer(jsonBody)
// Create request
req, err := http.NewRequest("POST", apiAuth.ApiURL+"/b2api/v1/b2_get_upload_part_url", body)
// Headers
req.Header.Add("Authorization", apiAuth.AuthorizationToken)
// Fetch Request
resp, err := client.Do(req)
if err != nil {
logger.Fatal("Error requesting Part Upload URL",
zap.Error(err),
)
}
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
var uploadPartResponse UploadPartResponse
if resp.Status != "200 OK" {
logger.Fatal("Could not obtain Part Upload URL", zap.String("Response", string(respBody)))
} else if resp.Status == "200 OK" {
err = json.Unmarshal(respBody, &uploadPartResponse)
if err != nil {
logger.Fatal("Upload Part Response JSON Parse Failed", zap.Error(err))
}
logger.Info("Obtained Upload Part URL",
zap.String("B2 File ID", uploadPartResponse.FileID),
)
}
return uploadPartResponse
}
|
[
"\"B2AcctID\"",
"\"B2AppID\"",
"\"B2APIURL\""
] |
[] |
[
"B2AppID",
"B2AcctID",
"B2APIURL"
] |
[]
|
["B2AppID", "B2AcctID", "B2APIURL"]
|
go
| 3 | 0 | |
tests/system/test_crud.py
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
System tests for Create, Update, Delete. (CRUD)
"""
import datetime
import functools
import operator
import os
import threading
import zlib
try:
from unittest import mock
except ImportError:
import mock
import pytest
import test_utils.system
from google.cloud import ndb
from google.cloud.ndb import _cache
from google.cloud.ndb import global_cache as global_cache_module
from tests.system import KIND, eventually
USE_REDIS_CACHE = bool(os.environ.get("REDIS_CACHE_URL"))
def _equals(n):
return functools.partial(operator.eq, n)
@pytest.mark.usefixtures("client_context")
def test_retrieve_entity(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none", baz=b"night")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
key = ndb.Key(KIND, entity_id)
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
def test_retrieve_entity_with_caching(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none", baz=b"night")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
client_context.set_cache_policy(None) # Use default
key = ndb.Key(KIND, entity_id)
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
assert key.get() is entity
def test_retrieve_entity_with_global_cache(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none", baz=b"night")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
global_cache = global_cache_module._InProcessGlobalCache()
cache_dict = global_cache_module._InProcessGlobalCache.cache
with client_context.new(global_cache=global_cache).use() as context:
context.set_global_cache_policy(None) # Use default
key = ndb.Key(KIND, entity_id)
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
cache_key = _cache.global_cache_key(key._key)
assert cache_key in cache_dict
patch = mock.patch("google.cloud.ndb._datastore_api._LookupBatch.add")
patch.side_effect = Exception("Shouldn't call this")
with patch:
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
@pytest.mark.skipif(not USE_REDIS_CACHE, reason="Redis is not configured")
def test_retrieve_entity_with_redis_cache(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none", baz=b"night")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
global_cache = global_cache_module.RedisCache.from_environment()
with client_context.new(global_cache=global_cache).use() as context:
context.set_global_cache_policy(None) # Use default
key = ndb.Key(KIND, entity_id)
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
cache_key = _cache.global_cache_key(key._key)
assert global_cache.redis.get(cache_key) is not None
patch = mock.patch("google.cloud.ndb._datastore_api._LookupBatch.add")
patch.side_effect = Exception("Shouldn't call this")
with patch:
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
@pytest.mark.usefixtures("client_context")
def test_retrieve_entity_not_found(ds_entity):
entity_id = test_utils.system.unique_resource_id()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
key = ndb.Key(KIND, entity_id)
assert key.get() is None
@pytest.mark.usefixtures("client_context")
def test_nested_tasklet(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
@ndb.tasklet
def get_foo(key):
entity = yield key.get_async()
raise ndb.Return(entity.foo)
key = ndb.Key(KIND, entity_id)
assert get_foo(key).result() == 42
@pytest.mark.usefixtures("client_context")
def test_retrieve_two_entities_in_parallel(ds_entity):
entity1_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity1_id, foo=42, bar="none")
entity2_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity2_id, foo=65, bar="naan")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
key1 = ndb.Key(KIND, entity1_id)
key2 = ndb.Key(KIND, entity2_id)
@ndb.tasklet
def get_two_entities():
entity1, entity2 = yield key1.get_async(), key2.get_async()
raise ndb.Return(entity1, entity2)
entity1, entity2 = get_two_entities().result()
assert isinstance(entity1, SomeKind)
assert entity1.foo == 42
assert entity1.bar == "none"
assert isinstance(entity2, SomeKind)
assert entity2.foo == 65
assert entity2.bar == "naan"
@pytest.mark.usefixtures("client_context")
def test_insert_entity(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
entity = SomeKind(foo=42, bar="none")
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar == "none"
# Make sure strings are stored as strings in datastore
ds_entity = ds_client.get(key._key)
assert ds_entity["bar"] == "none"
@pytest.mark.usefixtures("client_context")
def test_insert_entity_with_stored_name_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.StringProperty()
bar = ndb.StringProperty(name="notbar")
entity = SomeKind(foo="something", bar="or other")
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == "something"
assert retrieved.bar == "or other"
ds_entity = ds_client.get(key._key)
assert ds_entity["notbar"] == "or other"
@pytest.mark.usefixtures("client_context")
def test_insert_roundtrip_naive_datetime(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.DateTimeProperty()
entity = SomeKind(foo=datetime.datetime(2010, 5, 12, 2, 42))
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == datetime.datetime(2010, 5, 12, 2, 42)
@pytest.mark.usefixtures("client_context")
def test_datetime_w_tzinfo(dispose_of, ds_client):
class timezone(datetime.tzinfo):
def __init__(self, offset):
self.offset = datetime.timedelta(hours=offset)
def utcoffset(self, dt):
return self.offset
def dst(self, dt):
return datetime.timedelta(0)
mytz = timezone(-4)
class SomeKind(ndb.Model):
foo = ndb.DateTimeProperty(tzinfo=mytz)
bar = ndb.DateTimeProperty(tzinfo=mytz)
entity = SomeKind(
foo=datetime.datetime(2010, 5, 12, 2, 42, tzinfo=timezone(-5)),
bar=datetime.datetime(2010, 5, 12, 2, 42),
)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == datetime.datetime(2010, 5, 12, 3, 42, tzinfo=mytz)
assert retrieved.bar == datetime.datetime(2010, 5, 11, 22, 42, tzinfo=mytz)
def test_parallel_threads(dispose_of, namespace):
client = ndb.Client(namespace=namespace)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
def insert(foo):
with client.context(cache_policy=False):
entity = SomeKind(foo=foo, bar="none")
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
assert retrieved.bar == "none"
thread1 = threading.Thread(target=insert, args=[42], name="one")
thread2 = threading.Thread(target=insert, args=[144], name="two")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
@pytest.mark.usefixtures("client_context")
def test_large_json_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.JsonProperty()
foo = {str(i): i for i in range(500)}
entity = SomeKind(foo=foo)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
@pytest.mark.usefixtures("client_context")
def test_compressed_json_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.JsonProperty(compressed=True)
foo = {str(i): i for i in range(500)}
entity = SomeKind(foo=foo)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
@pytest.mark.usefixtures("client_context")
def test_compressed_blob_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.BlobProperty(compressed=True)
foo = b"abc" * 100
entity = SomeKind(foo=foo)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
@pytest.mark.usefixtures("client_context")
def test_retrieve_entity_with_legacy_compressed_property(
ds_entity_with_meanings,
):
class SomeKind(ndb.Model):
blob = ndb.BlobProperty()
value = b"abc" * 1000
compressed_value = zlib.compress(value)
entity_id = test_utils.system.unique_resource_id()
ds_entity_with_meanings(
{"blob": (22, compressed_value)},
KIND,
entity_id,
**{"blob": compressed_value}
)
key = ndb.Key(KIND, entity_id)
retrieved = key.get()
assert retrieved.blob == value
@pytest.mark.usefixtures("client_context")
def test_large_pickle_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.PickleProperty()
foo = {str(i): i for i in range(500)}
entity = SomeKind(foo=foo)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
@pytest.mark.usefixtures("client_context")
def test_key_property(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.KeyProperty()
key_value = ndb.Key("Whatevs", 123)
entity = SomeKind(foo=key_value)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == key_value
@pytest.mark.usefixtures("client_context")
def test_multiple_key_properties(dispose_of, ds_client):
class SomeKind(ndb.Model):
foo = ndb.KeyProperty(kind="Whatevs")
bar = ndb.KeyProperty(kind="Whatevs")
foo = ndb.Key("Whatevs", 123)
bar = ndb.Key("Whatevs", 321)
entity = SomeKind(foo=foo, bar=bar)
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == foo
assert retrieved.bar == bar
assert retrieved.foo != retrieved.bar
def test_insert_entity_with_caching(client_context):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
client_context.set_cache_policy(None) # Use default
entity = SomeKind(foo=42, bar="none")
key = entity.put()
with client_context.new(cache_policy=False).use():
# Sneaky. Delete entity out from under cache so we know we're getting
# cached copy.
key.delete()
eventually(key.get, _equals(None))
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar == "none"
def test_insert_entity_with_global_cache(dispose_of, client_context):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
global_cache = global_cache_module._InProcessGlobalCache()
cache_dict = global_cache_module._InProcessGlobalCache.cache
with client_context.new(global_cache=global_cache).use() as context:
context.set_global_cache_policy(None) # Use default
entity = SomeKind(foo=42, bar="none")
key = entity.put()
dispose_of(key._key)
cache_key = _cache.global_cache_key(key._key)
assert not cache_dict
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar == "none"
assert cache_key in cache_dict
entity.foo = 43
entity.put()
# This is py27 behavior. I can see a case being made for caching the
# entity on write rather than waiting for a subsequent lookup.
assert cache_key not in cache_dict
@pytest.mark.skipif(not USE_REDIS_CACHE, reason="Redis is not configured")
def test_insert_entity_with_redis_cache(dispose_of, client_context):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
global_cache = global_cache_module.RedisCache.from_environment()
with client_context.new(global_cache=global_cache).use() as context:
context.set_global_cache_policy(None) # Use default
entity = SomeKind(foo=42, bar="none")
key = entity.put()
dispose_of(key._key)
cache_key = _cache.global_cache_key(key._key)
assert global_cache.redis.get(cache_key) is None
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar == "none"
assert global_cache.redis.get(cache_key) is not None
entity.foo = 43
entity.put()
# This is py27 behavior. I can see a case being made for caching the
# entity on write rather than waiting for a subsequent lookup.
assert global_cache.redis.get(cache_key) is None
@pytest.mark.usefixtures("client_context")
def test_update_entity(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
key = ndb.Key(KIND, entity_id)
entity = key.get()
entity.foo = 56
entity.bar = "high"
assert entity.put() == key
retrieved = key.get()
assert retrieved.foo == 56
assert retrieved.bar == "high"
@pytest.mark.usefixtures("client_context")
def test_insert_entity_in_transaction(dispose_of):
commit_callback = mock.Mock()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
def save_entity():
ndb.get_context().call_on_commit(commit_callback)
entity = SomeKind(foo=42, bar="none")
key = entity.put()
dispose_of(key._key)
return key
key = ndb.transaction(save_entity)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar == "none"
commit_callback.assert_called_once_with()
@pytest.mark.usefixtures("client_context")
def test_update_entity_in_transaction(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42, bar="none")
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
def update_entity():
key = ndb.Key(KIND, entity_id)
entity = key.get()
entity.foo = 56
entity.bar = "high"
assert entity.put() == key
return key
key = ndb.transaction(update_entity)
retrieved = key.get()
assert retrieved.foo == 56
assert retrieved.bar == "high"
@pytest.mark.usefixtures("client_context")
def test_parallel_transactions():
def task(delay):
@ndb.tasklet
def callback():
transaction = ndb.get_context().transaction
yield ndb.sleep(delay)
assert ndb.get_context().transaction == transaction
raise ndb.Return(transaction)
return callback
future1 = ndb.transaction_async(task(0.1))
future2 = ndb.transaction_async(task(0.06))
ndb.wait_all((future1, future2))
assert future1.get_result() != future2.get_result()
@pytest.mark.usefixtures("client_context")
def test_delete_entity(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
key = ndb.Key(KIND, entity_id)
assert key.get().foo == 42
assert key.delete() is None
assert key.get() is None
assert key.delete() is None
def test_delete_entity_with_caching(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
client_context.set_cache_policy(None) # Use default
key = ndb.Key(KIND, entity_id)
assert key.get().foo == 42
assert key.delete() is None
assert key.get() is None
assert key.delete() is None
def test_delete_entity_with_global_cache(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
key = ndb.Key(KIND, entity_id)
cache_key = _cache.global_cache_key(key._key)
global_cache = global_cache_module._InProcessGlobalCache()
cache_dict = global_cache_module._InProcessGlobalCache.cache
with client_context.new(global_cache=global_cache).use():
assert key.get().foo == 42
assert cache_key in cache_dict
assert key.delete() is None
assert cache_key not in cache_dict
# This is py27 behavior. Not entirely sold on leaving _LOCKED value for
# Datastore misses.
assert key.get() is None
assert cache_dict[cache_key][0] == b"0"
@pytest.mark.skipif(not USE_REDIS_CACHE, reason="Redis is not configured")
def test_delete_entity_with_redis_cache(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
key = ndb.Key(KIND, entity_id)
cache_key = _cache.global_cache_key(key._key)
global_cache = global_cache_module.RedisCache.from_environment()
with client_context.new(global_cache=global_cache).use():
assert key.get().foo == 42
assert global_cache.redis.get(cache_key) is not None
assert key.delete() is None
assert global_cache.redis.get(cache_key) is None
# This is py27 behavior. Not entirely sold on leaving _LOCKED value for
# Datastore misses.
assert key.get() is None
assert global_cache.redis.get(cache_key) == b"0"
@pytest.mark.usefixtures("client_context")
def test_delete_entity_in_transaction(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
key = ndb.Key(KIND, entity_id)
assert key.get().foo == 42
def delete_entity():
assert key.delete() is None
assert key.get().foo == 42 # not deleted until commit
ndb.transaction(delete_entity)
assert key.get() is None
@pytest.mark.usefixtures("client_context")
def test_delete_entity_in_transaction_then_rollback(ds_entity):
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
key = ndb.Key(KIND, entity_id)
assert key.get().foo == 42
def delete_entity():
assert key.delete() is None
raise Exception("Spurious error")
with pytest.raises(Exception):
ndb.transaction(delete_entity)
assert key.get().foo == 42
@pytest.mark.usefixtures("client_context")
def test_allocate_ids():
class SomeKind(ndb.Model):
pass
keys = SomeKind.allocate_ids(5)
assert len(keys) == 5
for key in keys:
assert key.id()
assert key.get() is None
@pytest.mark.usefixtures("client_context")
def test_get_by_id(ds_entity):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
entity_id = test_utils.system.unique_resource_id()
ds_entity(KIND, entity_id, foo=42)
key = ndb.Key(KIND, entity_id)
assert key.get().foo == 42
entity = SomeKind.get_by_id(entity_id)
assert entity.foo == 42
@pytest.mark.usefixtures("client_context")
def test_get_or_insert_get(ds_entity):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
name = "Inigo Montoya"
assert SomeKind.get_by_id(name) is None
ds_entity(KIND, name, foo=42)
entity = SomeKind.get_or_insert(name, foo=21)
assert entity.foo == 42
@pytest.mark.usefixtures("client_context")
def test_get_or_insert_insert(dispose_of):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
name = "Inigo Montoya"
assert SomeKind.get_by_id(name) is None
entity = SomeKind.get_or_insert(name, foo=21)
dispose_of(entity._key._key)
assert entity.foo == 21
@pytest.mark.usefixtures("client_context")
def test_get_or_insert_get_in_transaction(ds_entity):
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
name = "Inigo Montoya"
assert SomeKind.get_by_id(name) is None
def do_the_thing():
ds_entity(KIND, name, foo=42)
return SomeKind.get_or_insert(name, foo=21)
entity = ndb.transaction(do_the_thing)
assert entity.foo == 42
@pytest.mark.usefixtures("client_context")
def test_insert_entity_with_structured_property(dispose_of):
class OtherKind(ndb.Model):
one = ndb.StringProperty()
two = ndb.StringProperty()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StructuredProperty(OtherKind)
entity = SomeKind(foo=42, bar=OtherKind(one="hi", two="mom"))
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar.one == "hi"
assert retrieved.bar.two == "mom"
assert isinstance(retrieved.bar, OtherKind)
def test_insert_entity_with_structured_property_legacy_data(
client_context, dispose_of, ds_client
):
class OtherKind(ndb.Model):
one = ndb.StringProperty()
two = ndb.StringProperty()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StructuredProperty(OtherKind)
with client_context.new(legacy_data=True).use():
entity = SomeKind(foo=42, bar=OtherKind(one="hi", two="mom"))
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar.one == "hi"
assert retrieved.bar.two == "mom"
assert isinstance(retrieved.bar, OtherKind)
ds_entity = ds_client.get(key._key)
assert ds_entity["foo"] == 42
assert ds_entity["bar.one"] == "hi"
assert ds_entity["bar.two"] == "mom"
@pytest.mark.usefixtures("client_context")
def test_retrieve_entity_with_legacy_structured_property(ds_entity):
class OtherKind(ndb.Model):
one = ndb.StringProperty()
two = ndb.StringProperty()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StructuredProperty(OtherKind)
entity_id = test_utils.system.unique_resource_id()
ds_entity(
KIND, entity_id, **{"foo": 42, "bar.one": "hi", "bar.two": "mom"}
)
key = ndb.Key(KIND, entity_id)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar.one == "hi"
assert retrieved.bar.two == "mom"
assert isinstance(retrieved.bar, OtherKind)
@pytest.mark.usefixtures("client_context")
def test_retrieve_entity_with_legacy_repeated_structured_property(ds_entity):
class OtherKind(ndb.Model):
one = ndb.StringProperty()
two = ndb.StringProperty()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StructuredProperty(OtherKind, repeated=True)
entity_id = test_utils.system.unique_resource_id()
ds_entity(
KIND,
entity_id,
**{"foo": 42, "bar.one": ["hi", "hello"], "bar.two": ["mom", "dad"]}
)
key = ndb.Key(KIND, entity_id)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.bar[0].one == "hi"
assert retrieved.bar[0].two == "mom"
assert retrieved.bar[1].one == "hello"
assert retrieved.bar[1].two == "dad"
assert isinstance(retrieved.bar[0], OtherKind)
assert isinstance(retrieved.bar[1], OtherKind)
@pytest.mark.usefixtures("client_context")
def test_insert_expando(dispose_of):
class SomeKind(ndb.Expando):
foo = ndb.IntegerProperty()
entity = SomeKind(foo=42)
entity.expando_prop = "exp-value"
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert retrieved.foo == 42
assert retrieved.expando_prop == "exp-value"
@pytest.mark.usefixtures("client_context")
def test_insert_polymodel(dispose_of):
class Animal(ndb.PolyModel):
one = ndb.StringProperty()
class Feline(Animal):
two = ndb.StringProperty()
class Cat(Feline):
three = ndb.StringProperty()
entity = Cat(one="hello", two="dad", three="i'm in jail")
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert isinstance(retrieved, Animal)
assert isinstance(retrieved, Cat)
assert retrieved.one == "hello"
assert retrieved.two == "dad"
assert retrieved.three == "i'm in jail"
@pytest.mark.usefixtures("client_context")
def test_insert_autonow_property(dispose_of):
class SomeKind(ndb.Model):
foo = ndb.StringProperty()
created_at = ndb.DateTimeProperty(indexed=True, auto_now_add=True)
updated_at = ndb.DateTimeProperty(indexed=True, auto_now=True)
entity = SomeKind(foo="bar")
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert isinstance(retrieved.created_at, datetime.datetime)
assert isinstance(retrieved.updated_at, datetime.datetime)
@pytest.mark.usefixtures("client_context")
def test_insert_nested_autonow_property(dispose_of):
class OtherKind(ndb.Model):
created_at = ndb.DateTimeProperty(indexed=True, auto_now_add=True)
updated_at = ndb.DateTimeProperty(indexed=True, auto_now=True)
class SomeKind(ndb.Model):
other = ndb.StructuredProperty(OtherKind)
entity = SomeKind(other=OtherKind())
key = entity.put()
dispose_of(key._key)
retrieved = key.get()
assert isinstance(retrieved.other.created_at, datetime.datetime)
assert isinstance(retrieved.other.updated_at, datetime.datetime)
@pytest.mark.usefixtures("client_context")
def test_uninitialized_property(dispose_of):
class SomeKind(ndb.Model):
foo = ndb.StringProperty(required=True)
entity = SomeKind()
with pytest.raises(ndb.exceptions.BadValueError):
entity.put()
@mock.patch(
"google.cloud.ndb._datastore_api.make_call",
mock.Mock(side_effect=Exception("Datastore shouldn't get called.")),
)
def test_crud_without_datastore(ds_entity, client_context):
entity_id = test_utils.system.unique_resource_id()
class SomeKind(ndb.Model):
foo = ndb.IntegerProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
global_cache = global_cache_module._InProcessGlobalCache()
with client_context.new(global_cache=global_cache).use() as context:
context.set_global_cache_policy(None) # Use default
context.set_datastore_policy(False) # Don't use Datastore
key = ndb.Key(KIND, entity_id)
SomeKind(foo=42, bar="none", baz="night", _key=key).put()
entity = key.get()
assert isinstance(entity, SomeKind)
assert entity.foo == 42
assert entity.bar == "none"
assert entity.baz == "night"
key.delete()
assert key.get() is None
|
[] |
[] |
[
"REDIS_CACHE_URL"
] |
[]
|
["REDIS_CACHE_URL"]
|
python
| 1 | 0 | |
cappa/private/pip3.py
|
from __future__ import print_function, absolute_import
import os
from ..pip3 import Pip3
class PrivatePip3(Pip3):
def __init__(self, org, *flags):
super(PrivatePip3, self).__init__(*flags)
self.org = org
def install(self, packages):
packages = self._private_package_dict(packages)
super(PrivatePip3, self).install(packages)
def _private_package_dict(self, packages):
def repo_url(repo_string):
repo_split = repo_string.split('@')
if len(repo_split) > 1:
repo, version = repo_split
else:
repo = repo_split[0]
version = 'master'
if self.private_https_oauth:
# Use https with oauth. Pulls token from env
token = os.environ['GITHUB_TOKEN']
return 'git+https://{}@github.com/{}/{}.git@{}'.format(token, self.org, repo, version)
else:
return 'git+ssh://[email protected]/{}/{}.git@{}'.format(self.org, repo, version)
private_package_dict = {repo_url(repo): None for repo in packages}
return private_package_dict
|
[] |
[] |
[
"GITHUB_TOKEN"
] |
[]
|
["GITHUB_TOKEN"]
|
python
| 1 | 0 | |
codepix/cmd/kafka.go
|
/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"github.com/LucasMMF/imersao-fullstack-fullcycle/codepix/application/kafka"
"github.com/LucasMMF/imersao-fullstack-fullcycle/codepix/infrastructure/db"
ckafka "github.com/confluentinc/confluent-kafka-go/kafka"
"os"
"github.com/spf13/cobra"
)
// kafkaCmd represents the kafka command
var kafkaCmd = &cobra.Command{
Use: "kafka",
Short: "Start consuming transactions using Apache Kafka",
Run: func(cmd *cobra.Command, args []string) {
deliveryChan := make(chan ckafka.Event)
database := db.ConnectDB(os.Getenv("env"))
producer := kafka.NewKafkaProducer()
// kafka.Publish("Olá Consumer", "teste", producer, deliveryChan)
go kafka.DeliveryReport(deliveryChan)
kafkaProcessor := kafka.NewKafkaProcessor(database, producer, deliveryChan)
kafkaProcessor.Consume()
},
}
func init() {
rootCmd.AddCommand(kafkaCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// kafkaCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// kafkaCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
|
[
"\"env\""
] |
[] |
[
"env"
] |
[]
|
["env"]
|
go
| 1 | 0 | |
pkg/cluster/nodes/create.go
|
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nodes
import (
"fmt"
"net"
"os"
"github.com/pkg/errors"
"sigs.k8s.io/kind/pkg/cluster/config"
"sigs.k8s.io/kind/pkg/cluster/constants"
"sigs.k8s.io/kind/pkg/cluster/internal/haproxy"
"sigs.k8s.io/kind/pkg/cluster/internal/kubeadm"
"sigs.k8s.io/kind/pkg/container/cri"
"sigs.k8s.io/kind/pkg/container/docker"
)
// FromName creates a node handle from the node' Name
func FromName(name string) *Node {
return &Node{
name: name,
cache: &nodeCache{},
}
}
// helper used to get a free TCP port for the API server
func getPort() (int, error) {
dummyListener, err := net.Listen("tcp", ":0")
if err != nil {
return 0, err
}
defer dummyListener.Close()
port := dummyListener.Addr().(*net.TCPAddr).Port
return port, nil
}
// CreateControlPlaneNode creates a contol-plane node
// and gets ready for exposing the the API server
func CreateControlPlaneNode(name, image, clusterLabel string, mounts []cri.Mount) (node *Node, err error) {
// gets a random host port for the API server
port, err := getPort()
if err != nil {
return nil, errors.Wrap(err, "failed to get port for API server")
}
node, err = createNode(
name, image, clusterLabel, config.ControlPlaneRole, mounts,
// publish selected port for the API server
"--expose", fmt.Sprintf("%d", port),
"-p", fmt.Sprintf("%d:%d", port, kubeadm.APIServerPort),
)
if err != nil {
return node, err
}
// stores the port mapping into the node internal state
node.cache.set(func(cache *nodeCache) {
cache.ports = map[int]int{kubeadm.APIServerPort: port}
})
return node, nil
}
// CreateExternalLoadBalancerNode creates an external loab balancer node
// and gets ready for exposing the the API server and the load balancer admin console
func CreateExternalLoadBalancerNode(name, image, clusterLabel string) (node *Node, err error) {
// gets a random host port for control-plane load balancer
port, err := getPort()
if err != nil {
return nil, errors.Wrap(err, "failed to get port for control-plane load balancer")
}
node, err = createNode(name, image, clusterLabel, config.ExternalLoadBalancerRole,
nil,
// publish selected port for the control plane
"--expose", fmt.Sprintf("%d", port),
"-p", fmt.Sprintf("%d:%d", port, haproxy.ControlPlanePort),
)
if err != nil {
return node, err
}
// stores the port mapping into the node internal state
node.cache.set(func(cache *nodeCache) {
cache.ports = map[int]int{haproxy.ControlPlanePort: port}
})
return node, nil
}
// CreateWorkerNode creates a worker node
func CreateWorkerNode(name, image, clusterLabel string, mounts []cri.Mount) (node *Node, err error) {
node, err = createNode(name, image, clusterLabel, config.WorkerRole, mounts)
if err != nil {
return node, err
}
return node, nil
}
// TODO(bentheelder): refactor this to not have extraArgs
// createNode `docker run`s the node image, note that due to
// images/node/entrypoint being the entrypoint, this container will
// effectively be paused until we call actuallyStartNode(...)
func createNode(name, image, clusterLabel string, role config.NodeRole, mounts []cri.Mount, extraArgs ...string) (handle *Node, err error) {
runArgs := []string{
"-d", // run the container detached
// running containers in a container requires privileged
// NOTE: we could try to replicate this with --cap-add, and use less
// privileges, but this flag also changes some mounts that are necessary
// including some ones docker would otherwise do by default.
// for now this is what we want. in the future we may revisit this.
"--privileged",
"--security-opt", "seccomp=unconfined", // also ignore seccomp
"--tmpfs", "/tmp", // various things depend on working /tmp
"--tmpfs", "/run", // systemd wants a writable /run
// some k8s things want /lib/modules
"-v", "/lib/modules:/lib/modules:ro",
"--hostname", name, // make hostname match container name
"--name", name, // ... and set the container name
// label the node with the cluster ID
"--label", clusterLabel,
// label the node with the role ID
"--label", fmt.Sprintf("%s=%s", constants.NodeRoleKey, role),
// explicitly set the entrypoint
"--entrypoint=/usr/local/bin/entrypoint",
}
// pass proxy environment variables to be used by node's docker deamon
httpProxy := os.Getenv("HTTP_PROXY")
if httpProxy != "" {
runArgs = append(runArgs, "-e", "HTTP_PROXY="+httpProxy)
}
httpsProxy := os.Getenv("HTTPS_PROXY")
if httpsProxy != "" {
runArgs = append(runArgs, "-e", "HTTPS_PROXY="+httpsProxy)
}
noProxy := os.Getenv("NO_PROXY")
if noProxy != "" {
runArgs = append(runArgs, "-e", "NO_PROXY="+noProxy)
}
// adds node specific args
runArgs = append(runArgs, extraArgs...)
if docker.UsernsRemap() {
// We need this argument in order to make this command work
// in systems that have userns-remap enabled on the docker daemon
runArgs = append(runArgs, "--userns=host")
}
id, err := docker.Run(
image,
docker.WithRunArgs(runArgs...),
docker.WithContainerArgs(
// explicitly pass the entrypoint argument
"/sbin/init",
),
docker.WithMounts(mounts),
)
// if there is a returned ID then we did create a container
// we should return a handle so the caller can clean it up
// we'll return a handle with the nice name though
if id != "" {
handle = FromName(name)
}
if err != nil {
return handle, errors.Wrap(err, "docker run error")
}
// Deletes the machine-id embedded in the node image and regenerate a new one.
// This is necessary because both kubelet and other components like weave net
// use machine-id internally to distinguish nodes.
if err := handle.Command("rm", "-f", "/etc/machine-id").Run(); err != nil {
return handle, errors.Wrap(err, "machine-id-setup error")
}
if err := handle.Command("systemd-machine-id-setup").Run(); err != nil {
return handle, errors.Wrap(err, "machine-id-setup error")
}
return handle, nil
}
|
[
"\"HTTP_PROXY\"",
"\"HTTPS_PROXY\"",
"\"NO_PROXY\""
] |
[] |
[
"HTTP_PROXY",
"HTTPS_PROXY",
"NO_PROXY"
] |
[]
|
["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"]
|
go
| 3 | 0 | |
spyder/plugins/editor/plugin.py
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Editor Plugin"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
import logging
import os
import os.path as osp
import re
import time
# Third party imports
from qtpy.compat import from_qvariant, getopenfilenames, to_qvariant
from qtpy.QtCore import QByteArray, Qt, Signal, Slot
from qtpy.QtGui import QKeySequence
from qtpy.QtPrintSupport import QAbstractPrintDialog, QPrintDialog, QPrinter
from qtpy.QtWidgets import (QAction, QActionGroup, QApplication, QDialog,
QFileDialog, QInputDialog, QMenu, QSplitter,
QToolBar, QVBoxLayout, QWidget)
# Local imports
from spyder import dependencies
from spyder.config.base import _, get_conf_path, running_under_pytest
from spyder.config.main import (CONF, RUN_CELL_SHORTCUT,
RUN_CELL_AND_ADVANCE_SHORTCUT)
from spyder.config.utils import (get_edit_filetypes, get_edit_filters,
get_filter)
from spyder.py3compat import PY2, qbytearray_to_str, to_text_string
from spyder.utils import encoding, programs, sourcecode
from spyder.utils import icon_manager as ima
from spyder.utils.qthelpers import create_action, add_actions, MENU_SEPARATOR
from spyder.utils.misc import getcwd_or_home
from spyder.widgets.findreplace import FindReplace
from spyder.plugins.editor.confpage import EditorConfigPage
from spyder.plugins.editor.utils.autosave import AutosaveForPlugin
from spyder.plugins.editor.widgets.editor import (EditorMainWindow, Printer,
EditorSplitter, EditorStack,)
from spyder.plugins.editor.widgets.codeeditor import CodeEditor
from spyder.plugins.editor.utils.bookmarks import (load_bookmarks,
save_bookmarks)
from spyder.plugins.editor.utils.debugger import (clear_all_breakpoints,
clear_breakpoint)
from spyder.plugins.editor.widgets.status import (CursorPositionStatus,
EncodingStatus, EOLStatus,
ReadWriteStatus, VCSStatus)
from spyder.api.plugins import SpyderPluginWidget
from spyder.preferences.runconfig import (ALWAYS_OPEN_FIRST_RUN_OPTION,
get_run_configuration,
RunConfigDialog, RunConfigOneDialog)
from spyder.plugins.editor.lsp import LSPEventTypes
logger = logging.getLogger(__name__)
# Dependencies
PYLS_REQVER = '>=0.19.0'
dependencies.add('pyls',
_("Editor's code completion, go-to-definition, help and "
"real-time code analysis"),
required_version=PYLS_REQVER)
NBCONVERT_REQVER = ">=4.0"
dependencies.add("nbconvert", _("Manipulate Jupyter notebooks on the Editor"),
required_version=NBCONVERT_REQVER)
WINPDB_PATH = programs.find_program('winpdb')
class Editor(SpyderPluginWidget):
"""
Multi-file Editor widget
"""
CONF_SECTION = 'editor'
CONFIGWIDGET_CLASS = EditorConfigPage
TEMPFILE_PATH = get_conf_path('temp.py')
TEMPLATE_PATH = get_conf_path('template.py')
DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute
# Signals
run_in_current_ipyclient = Signal(str, str, str, bool, bool, bool, bool)
run_cell_in_ipyclient = Signal(str, str, str, bool)
exec_in_extconsole = Signal(str, bool)
redirect_stdio = Signal(bool)
open_dir = Signal(str)
breakpoints_saved = Signal()
run_in_current_extconsole = Signal(str, str, str, bool, bool)
open_file_update = Signal(str)
sig_lsp_notification = Signal(dict, str)
def __init__(self, parent, ignore_last_opened_files=False):
SpyderPluginWidget.__init__(self, parent)
self.__set_eol_chars = True
# Creating template if it doesn't already exist
if not osp.isfile(self.TEMPLATE_PATH):
if os.name == "nt":
shebang = []
else:
shebang = ['#!/usr/bin/env python' + ('2' if PY2 else '3')]
header = shebang + [
'# -*- coding: utf-8 -*-',
'"""', 'Created on %(date)s', '',
'@author: %(username)s', '"""', '', '']
try:
encoding.write(os.linesep.join(header), self.TEMPLATE_PATH,
'utf-8')
except EnvironmentError:
pass
self.projects = None
self.outlineexplorer = None
self.help = None
self.file_dependent_actions = []
self.pythonfile_dependent_actions = []
self.dock_toolbar_actions = None
self.edit_menu_actions = None #XXX: find another way to notify Spyder
self.stack_menu_actions = None
self.checkable_actions = {}
self.__first_open_files_setup = True
self.editorstacks = []
self.last_focus_editorstack = {}
self.editorwindows = []
self.editorwindows_to_be_created = []
self.toolbar_list = None
self.menu_list = None
# Initialize plugin
self.initialize_plugin()
self.options_button.hide()
# Configuration dialog size
self.dialog_size = None
statusbar = parent.statusBar() # Create a status bar
self.vcs_status = VCSStatus(self, statusbar)
self.cursorpos_status = CursorPositionStatus(self, statusbar)
self.encoding_status = EncodingStatus(self, statusbar)
self.eol_status = EOLStatus(self, statusbar)
self.readwrite_status = ReadWriteStatus(self, statusbar)
layout = QVBoxLayout()
self.dock_toolbar = QToolBar(self)
add_actions(self.dock_toolbar, self.dock_toolbar_actions)
layout.addWidget(self.dock_toolbar)
self.last_edit_cursor_pos = None
self.cursor_pos_history = []
self.cursor_pos_index = None
self.__ignore_cursor_position = True
# LSP setup
self.sig_lsp_notification.connect(self.document_server_settings)
self.lsp_editor_settings = {}
# Setup new windows:
self.main.all_actions_defined.connect(self.setup_other_windows)
# Change module completions when PYTHONPATH changes
self.main.sig_pythonpath_changed.connect(self.set_path)
# Find widget
self.find_widget = FindReplace(self, enable_replace=True)
self.find_widget.hide()
self.find_widget.visibility_changed.connect(
lambda vs: self.rehighlight_cells())
self.register_widget_shortcuts(self.find_widget)
# Tabbed editor widget + Find/Replace widget
editor_widgets = QWidget(self)
editor_layout = QVBoxLayout()
editor_layout.setContentsMargins(0, 0, 0, 0)
editor_widgets.setLayout(editor_layout)
self.editorsplitter = EditorSplitter(self, self,
self.stack_menu_actions, first=True)
editor_layout.addWidget(self.editorsplitter)
editor_layout.addWidget(self.find_widget)
# Start autosave component
self.autosave = AutosaveForPlugin(self)
self.autosave.try_recover_from_autosave()
# Multiply by 1000 to convert seconds to milliseconds
self.autosave.interval = self.get_option('autosave_interval') * 1000
self.autosave.enabled = self.get_option('autosave_enabled')
# Splitter: editor widgets (see above) + outline explorer
self.splitter = QSplitter(self)
self.splitter.setContentsMargins(0, 0, 0, 0)
self.splitter.addWidget(editor_widgets)
self.splitter.setStretchFactor(0, 5)
self.splitter.setStretchFactor(1, 1)
layout.addWidget(self.splitter)
self.setLayout(layout)
self.setFocusPolicy(Qt.ClickFocus)
# Editor's splitter state
state = self.get_option('splitter_state', None)
if state is not None:
self.splitter.restoreState( QByteArray().fromHex(
str(state).encode('utf-8')) )
self.recent_files = self.get_option('recent_files', [])
self.untitled_num = 0
# Parameters of last file execution:
self.__last_ic_exec = None # internal console
self.__last_ec_exec = None # external console
# File types and filters used by the Open dialog
self.edit_filetypes = None
self.edit_filters = None
self.__ignore_cursor_position = False
current_editor = self.get_current_editor()
if current_editor is not None:
filename = self.get_current_filename()
position = current_editor.get_position('cursor')
self.add_cursor_position_to_history(filename, position)
self.update_cursorpos_actions()
self.set_path()
def set_projects(self, projects):
self.projects = projects
@Slot()
def show_hide_projects(self):
if self.projects is not None:
dw = self.projects.dockwidget
if dw.isVisible():
dw.hide()
else:
dw.show()
dw.raise_()
self.switch_to_plugin()
def set_outlineexplorer(self, outlineexplorer):
self.outlineexplorer = outlineexplorer
for editorstack in self.editorstacks:
# Pass the OutlineExplorer widget to the stacks because they
# don't need the plugin
editorstack.set_outlineexplorer(self.outlineexplorer.explorer)
self.editorstacks[0].initialize_outlineexplorer()
self.outlineexplorer.explorer.edit_goto.connect(
lambda filenames, goto, word:
self.load(filenames=filenames, goto=goto, word=word,
editorwindow=self))
self.outlineexplorer.explorer.edit.connect(
lambda filenames:
self.load(filenames=filenames, editorwindow=self))
def set_help(self, help_plugin):
self.help = help_plugin
for editorstack in self.editorstacks:
editorstack.set_help(self.help)
#------ Private API --------------------------------------------------------
def restore_scrollbar_position(self):
"""Restoring scrollbar position after main window is visible"""
# Widget is now visible, we may center cursor on top level editor:
try:
self.get_current_editor().centerCursor()
except AttributeError:
pass
@Slot(dict)
def report_open_file(self, options):
"""Request to start a LSP server to attend a language."""
filename = options['filename']
logger.debug('Call LSP for %s' % filename)
language = options['language']
callback = options['codeeditor']
stat = self.main.lspmanager.start_client(language.lower())
self.main.lspmanager.register_file(
language.lower(), filename, callback)
if stat:
if language.lower() in self.lsp_editor_settings:
self.lsp_server_ready(
language.lower(), self.lsp_editor_settings[
language.lower()])
else:
editor = self.get_current_editor()
editor.lsp_ready = False
@Slot(dict, str)
def document_server_settings(self, settings, language):
"""Update LSP server settings for textDocument requests."""
self.lsp_editor_settings[language] = settings
logger.debug('LSP Language Settings: %r' % self.lsp_editor_settings)
self.lsp_server_ready(language, self.lsp_editor_settings[language])
def lsp_server_ready(self, language, configuration):
"""Notify all stackeditors about LSP server availability."""
for editorstack in self.editorstacks:
editorstack.notify_server_ready(language, configuration)
def send_lsp_request(self, language, request, params):
logger.debug("LSP request: %r" %request)
self.main.lspmanager.send_request(language, request, params)
#------ SpyderPluginWidget API ---------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
title = _('Editor')
return title
def get_plugin_icon(self):
"""Return widget icon."""
return ima.icon('edit')
def get_focus_widget(self):
"""
Return the widget to give focus to.
This happens when plugin's dockwidget is raised on top-level.
"""
return self.get_current_editor()
def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
SpyderPluginWidget.visibility_changed(self, enable)
if self.dockwidget is None:
return
if self.dockwidget.isWindow():
self.dock_toolbar.show()
else:
self.dock_toolbar.hide()
if enable:
self.refresh_plugin()
self.sig_update_plugin_title.emit()
def refresh_plugin(self):
"""Refresh editor plugin"""
editorstack = self.get_current_editorstack()
editorstack.refresh()
self.refresh_save_all_action()
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
state = self.splitter.saveState()
self.set_option('splitter_state', qbytearray_to_str(state))
filenames = []
editorstack = self.editorstacks[0]
active_project_path = None
if self.projects is not None:
active_project_path = self.projects.get_active_project_path()
if not active_project_path:
self.set_open_filenames()
else:
self.projects.set_project_filenames(
[finfo.filename for finfo in editorstack.data])
self.set_option('layout_settings',
self.editorsplitter.get_layout_settings())
self.set_option('windows_layout_settings',
[win.get_layout_settings() for win in self.editorwindows])
# self.set_option('filenames', filenames)
self.set_option('recent_files', self.recent_files)
# Stop autosave timer before closing windows
self.autosave.stop_autosave_timer()
try:
if not editorstack.save_if_changed(cancelable) and cancelable:
return False
else:
for win in self.editorwindows[:]:
win.close()
return True
except IndexError:
return True
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
# ---- File menu and toolbar ----
self.new_action = create_action(
self,
_("&New file..."),
icon=ima.icon('filenew'), tip=_("New file"),
triggered=self.new,
context=Qt.WidgetShortcut
)
self.register_shortcut(self.new_action, context="Editor",
name="New file", add_sc_to_tip=True)
self.open_last_closed_action = create_action(
self,
_("O&pen last closed"),
tip=_("Open last closed"),
triggered=self.open_last_closed
)
self.register_shortcut(self.open_last_closed_action, context="Editor",
name="Open last closed")
self.open_action = create_action(self, _("&Open..."),
icon=ima.icon('fileopen'), tip=_("Open file"),
triggered=self.load,
context=Qt.WidgetShortcut)
self.register_shortcut(self.open_action, context="Editor",
name="Open file", add_sc_to_tip=True)
self.revert_action = create_action(self, _("&Revert"),
icon=ima.icon('revert'), tip=_("Revert file from disk"),
triggered=self.revert)
self.save_action = create_action(self, _("&Save"),
icon=ima.icon('filesave'), tip=_("Save file"),
triggered=self.save,
context=Qt.WidgetShortcut)
self.register_shortcut(self.save_action, context="Editor",
name="Save file", add_sc_to_tip=True)
self.save_all_action = create_action(self, _("Sav&e all"),
icon=ima.icon('save_all'), tip=_("Save all files"),
triggered=self.save_all,
context=Qt.WidgetShortcut)
self.register_shortcut(self.save_all_action, context="Editor",
name="Save all", add_sc_to_tip=True)
save_as_action = create_action(self, _("Save &as..."), None,
ima.icon('filesaveas'), tip=_("Save current file as..."),
triggered=self.save_as,
context=Qt.WidgetShortcut)
self.register_shortcut(save_as_action, "Editor", "Save As")
save_copy_as_action = create_action(self, _("Save copy as..."), None,
ima.icon('filesaveas'), _("Save copy of current file as..."),
triggered=self.save_copy_as)
print_preview_action = create_action(self, _("Print preview..."),
tip=_("Print preview..."), triggered=self.print_preview)
self.print_action = create_action(self, _("&Print..."),
icon=ima.icon('print'), tip=_("Print current file..."),
triggered=self.print_file)
# Shortcut for close_action is defined in widgets/editor.py
self.close_action = create_action(self, _("&Close"),
icon=ima.icon('fileclose'), tip=_("Close current file"),
triggered=self.close_file)
self.close_all_action = create_action(self, _("C&lose all"),
icon=ima.icon('filecloseall'), tip=_("Close all opened files"),
triggered=self.close_all_files,
context=Qt.WidgetShortcut)
self.register_shortcut(self.close_all_action, context="Editor",
name="Close all")
# ---- Find menu and toolbar ----
_text = _("&Find text")
find_action = create_action(self, _text, icon=ima.icon('find'),
tip=_text, triggered=self.find,
context=Qt.WidgetShortcut)
self.register_shortcut(find_action, context="_",
name="Find text", add_sc_to_tip=True)
find_next_action = create_action(self, _("Find &next"),
icon=ima.icon('findnext'),
triggered=self.find_next,
context=Qt.WidgetShortcut)
self.register_shortcut(find_next_action, context="_",
name="Find next")
find_previous_action = create_action(self, _("Find &previous"),
icon=ima.icon('findprevious'),
triggered=self.find_previous,
context=Qt.WidgetShortcut)
self.register_shortcut(find_previous_action, context="_",
name="Find previous")
_text = _("&Replace text")
replace_action = create_action(self, _text, icon=ima.icon('replace'),
tip=_text, triggered=self.replace,
context=Qt.WidgetShortcut)
self.register_shortcut(replace_action, context="_",
name="Replace text")
# ---- Debug menu and toolbar ----
set_clear_breakpoint_action = create_action(self,
_("Set/Clear breakpoint"),
icon=ima.icon('breakpoint_big'),
triggered=self.set_or_clear_breakpoint,
context=Qt.WidgetShortcut)
self.register_shortcut(set_clear_breakpoint_action, context="Editor",
name="Breakpoint")
set_cond_breakpoint_action = create_action(self,
_("Set/Edit conditional breakpoint"),
icon=ima.icon('breakpoint_cond_big'),
triggered=self.set_or_edit_conditional_breakpoint,
context=Qt.WidgetShortcut)
self.register_shortcut(set_cond_breakpoint_action, context="Editor",
name="Conditional breakpoint")
clear_all_breakpoints_action = create_action(self,
_('Clear breakpoints in all files'),
triggered=self.clear_all_breakpoints)
self.winpdb_action = create_action(self, _("Debug with winpdb"),
triggered=self.run_winpdb)
self.winpdb_action.setEnabled(WINPDB_PATH is not None and PY2)
# --- Debug toolbar ---
debug_action = create_action(self, _("&Debug"),
icon=ima.icon('debug'),
tip=_("Debug file"),
triggered=self.debug_file)
self.register_shortcut(debug_action, context="_", name="Debug",
add_sc_to_tip=True)
debug_next_action = create_action(self, _("Step"),
icon=ima.icon('arrow-step-over'), tip=_("Run current line"),
triggered=lambda: self.debug_command("next"))
self.register_shortcut(debug_next_action, "_", "Debug Step Over",
add_sc_to_tip=True)
debug_continue_action = create_action(self, _("Continue"),
icon=ima.icon('arrow-continue'),
tip=_("Continue execution until next breakpoint"),
triggered=lambda: self.debug_command("continue"))
self.register_shortcut(debug_continue_action, "_", "Debug Continue",
add_sc_to_tip=True)
debug_step_action = create_action(self, _("Step Into"),
icon=ima.icon('arrow-step-in'),
tip=_("Step into function or method of current line"),
triggered=lambda: self.debug_command("step"))
self.register_shortcut(debug_step_action, "_", "Debug Step Into",
add_sc_to_tip=True)
debug_return_action = create_action(self, _("Step Return"),
icon=ima.icon('arrow-step-out'),
tip=_("Run until current function or method returns"),
triggered=lambda: self.debug_command("return"))
self.register_shortcut(debug_return_action, "_", "Debug Step Return",
add_sc_to_tip=True)
debug_exit_action = create_action(self, _("Stop"),
icon=ima.icon('stop_debug'), tip=_("Stop debugging"),
triggered=lambda: self.debug_command("exit"))
self.register_shortcut(debug_exit_action, "_", "Debug Exit",
add_sc_to_tip=True)
# --- Run toolbar ---
run_action = create_action(self, _("&Run"), icon=ima.icon('run'),
tip=_("Run file"),
triggered=self.run_file)
self.register_shortcut(run_action, context="_", name="Run",
add_sc_to_tip=True)
configure_action = create_action(self, _("&Configuration per file..."),
icon=ima.icon('run_settings'),
tip=_("Run settings"),
menurole=QAction.NoRole,
triggered=self.edit_run_configurations)
self.register_shortcut(configure_action, context="_",
name="Configure", add_sc_to_tip=True)
re_run_action = create_action(self, _("Re-run &last script"),
icon=ima.icon('run_again'),
tip=_("Run again last file"),
triggered=self.re_run_file)
self.register_shortcut(re_run_action, context="_",
name="Re-run last script",
add_sc_to_tip=True)
run_selected_action = create_action(self, _("Run &selection or "
"current line"),
icon=ima.icon('run_selection'),
tip=_("Run selection or "
"current line"),
triggered=self.run_selection,
context=Qt.WidgetShortcut)
self.register_shortcut(run_selected_action, context="Editor",
name="Run selection", add_sc_to_tip=True)
run_cell_action = create_action(self,
_("Run cell"),
icon=ima.icon('run_cell'),
shortcut=QKeySequence(RUN_CELL_SHORTCUT),
tip=_("Run current cell (Ctrl+Enter)\n"
"[Use #%% to create cells]"),
triggered=self.run_cell,
context=Qt.WidgetShortcut)
run_cell_advance_action = create_action(self,
_("Run cell and advance"),
icon=ima.icon('run_cell_advance'),
shortcut=QKeySequence(RUN_CELL_AND_ADVANCE_SHORTCUT),
tip=_("Run current cell and go to the next one "
"(Shift+Enter)"),
triggered=self.run_cell_and_advance,
context=Qt.WidgetShortcut)
re_run_last_cell_action = create_action(self,
_("Re-run last cell"),
tip=_("Re run last cell "),
triggered=self.re_run_last_cell,
context=Qt.WidgetShortcut)
self.register_shortcut(re_run_last_cell_action,
context="Editor",
name='re-run last cell',
add_sc_to_tip=True)
# --- Source code Toolbar ---
self.todo_list_action = create_action(self,
_("Show todo list"), icon=ima.icon('todo_list'),
tip=_("Show comments list (TODO/FIXME/XXX/HINT/TIP/@todo/"
"HACK/BUG/OPTIMIZE/!!!/???)"),
triggered=self.go_to_next_todo)
self.todo_menu = QMenu(self)
self.todo_menu.setStyleSheet("QMenu {menu-scrollable: 1;}")
self.todo_list_action.setMenu(self.todo_menu)
self.todo_menu.aboutToShow.connect(self.update_todo_menu)
self.warning_list_action = create_action(self,
_("Show warning/error list"), icon=ima.icon('wng_list'),
tip=_("Show code analysis warnings/errors"),
triggered=self.go_to_next_warning)
self.warning_menu = QMenu(self)
self.warning_menu.setStyleSheet("QMenu {menu-scrollable: 1;}")
self.warning_list_action.setMenu(self.warning_menu)
self.warning_menu.aboutToShow.connect(self.update_warning_menu)
self.previous_warning_action = create_action(self,
_("Previous warning/error"), icon=ima.icon('prev_wng'),
tip=_("Go to previous code analysis warning/error"),
triggered=self.go_to_previous_warning,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_warning_action,
context="Editor",
name="Previous warning",
add_sc_to_tip=True)
self.next_warning_action = create_action(self,
_("Next warning/error"), icon=ima.icon('next_wng'),
tip=_("Go to next code analysis warning/error"),
triggered=self.go_to_next_warning,
context=Qt.WidgetShortcut)
self.register_shortcut(self.next_warning_action,
context="Editor",
name="Next warning",
add_sc_to_tip=True)
self.previous_edit_cursor_action = create_action(self,
_("Last edit location"), icon=ima.icon('last_edit_location'),
tip=_("Go to last edit location"),
triggered=self.go_to_last_edit_location,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_edit_cursor_action,
context="Editor",
name="Last edit location",
add_sc_to_tip=True)
self.previous_cursor_action = create_action(self,
_("Previous cursor position"), icon=ima.icon('prev_cursor'),
tip=_("Go to previous cursor position"),
triggered=self.go_to_previous_cursor_position,
context=Qt.WidgetShortcut)
self.register_shortcut(self.previous_cursor_action,
context="Editor",
name="Previous cursor position",
add_sc_to_tip=True)
self.next_cursor_action = create_action(self,
_("Next cursor position"), icon=ima.icon('next_cursor'),
tip=_("Go to next cursor position"),
triggered=self.go_to_next_cursor_position,
context=Qt.WidgetShortcut)
self.register_shortcut(self.next_cursor_action,
context="Editor",
name="Next cursor position",
add_sc_to_tip=True)
# --- Edit Toolbar ---
self.toggle_comment_action = create_action(self,
_("Comment")+"/"+_("Uncomment"), icon=ima.icon('comment'),
tip=_("Comment current line or selection"),
triggered=self.toggle_comment, context=Qt.WidgetShortcut)
self.register_shortcut(self.toggle_comment_action, context="Editor",
name="Toggle comment")
blockcomment_action = create_action(self, _("Add &block comment"),
tip=_("Add block comment around "
"current line or selection"),
triggered=self.blockcomment, context=Qt.WidgetShortcut)
self.register_shortcut(blockcomment_action, context="Editor",
name="Blockcomment")
unblockcomment_action = create_action(self,
_("R&emove block comment"),
tip = _("Remove comment block around "
"current line or selection"),
triggered=self.unblockcomment, context=Qt.WidgetShortcut)
self.register_shortcut(unblockcomment_action, context="Editor",
name="Unblockcomment")
# ----------------------------------------------------------------------
# The following action shortcuts are hard-coded in CodeEditor
# keyPressEvent handler (the shortcut is here only to inform user):
# (context=Qt.WidgetShortcut -> disable shortcut for other widgets)
self.indent_action = create_action(self,
_("Indent"), "Tab", icon=ima.icon('indent'),
tip=_("Indent current line or selection"),
triggered=self.indent, context=Qt.WidgetShortcut)
self.unindent_action = create_action(self,
_("Unindent"), "Shift+Tab", icon=ima.icon('unindent'),
tip=_("Unindent current line or selection"),
triggered=self.unindent, context=Qt.WidgetShortcut)
self.text_uppercase_action = create_action(self,
_("Toggle Uppercase"),
tip=_("Change to uppercase current line or selection"),
triggered=self.text_uppercase, context=Qt.WidgetShortcut)
self.register_shortcut(self.text_uppercase_action, context="Editor",
name="transform to uppercase")
self.text_lowercase_action = create_action(self,
_("Toggle Lowercase"),
tip=_("Change to lowercase current line or selection"),
triggered=self.text_lowercase, context=Qt.WidgetShortcut)
self.register_shortcut(self.text_lowercase_action, context="Editor",
name="transform to lowercase")
# ----------------------------------------------------------------------
self.win_eol_action = create_action(self,
_("Carriage return and line feed (Windows)"),
toggled=lambda checked: self.toggle_eol_chars('nt', checked))
self.linux_eol_action = create_action(self,
_("Line feed (UNIX)"),
toggled=lambda checked: self.toggle_eol_chars('posix', checked))
self.mac_eol_action = create_action(self,
_("Carriage return (Mac)"),
toggled=lambda checked: self.toggle_eol_chars('mac', checked))
eol_action_group = QActionGroup(self)
eol_actions = (self.win_eol_action, self.linux_eol_action,
self.mac_eol_action)
add_actions(eol_action_group, eol_actions)
eol_menu = QMenu(_("Convert end-of-line characters"), self)
add_actions(eol_menu, eol_actions)
trailingspaces_action = create_action(self,
_("Remove trailing spaces"),
triggered=self.remove_trailing_spaces)
# Checkable actions
showblanks_action = self._create_checkable_action(
_("Show blank spaces"), 'blank_spaces', 'set_blanks_enabled')
scrollpastend_action = self._create_checkable_action(
_("Scroll past the end"), 'scroll_past_end',
'set_scrollpastend_enabled')
showindentguides_action = self._create_checkable_action(
_("Show indent guides."), 'indent_guides', 'set_indent_guides')
show_classfunc_dropdown_action = self._create_checkable_action(
_("Show selector for classes and functions."),
'show_class_func_dropdown', 'set_classfunc_dropdown_visible')
showcode_analysis_pep8_action = self._create_checkable_action(
_("Show code style warnings (pep8)"),
'code_analysis/pep8', 'set_pep8_enabled')
self.checkable_actions = {
'blank_spaces': showblanks_action,
'scroll_past_end': scrollpastend_action,
'indent_guides': showindentguides_action,
'show_class_func_dropdown': show_classfunc_dropdown_action,
'code_analysis/pep8': showcode_analysis_pep8_action}
fixindentation_action = create_action(self, _("Fix indentation"),
tip=_("Replace tab characters by space characters"),
triggered=self.fix_indentation)
gotoline_action = create_action(self, _("Go to line..."),
icon=ima.icon('gotoline'),
triggered=self.go_to_line,
context=Qt.WidgetShortcut)
self.register_shortcut(gotoline_action, context="Editor",
name="Go to line")
workdir_action = create_action(self,
_("Set console working directory"),
icon=ima.icon('DirOpenIcon'),
tip=_("Set current console (and file explorer) working "
"directory to current script directory"),
triggered=self.__set_workdir)
self.max_recent_action = create_action(self,
_("Maximum number of recent files..."),
triggered=self.change_max_recent_files)
self.clear_recent_action = create_action(self,
_("Clear this list"), tip=_("Clear recent files list"),
triggered=self.clear_recent_files)
# ---- File menu/toolbar construction ----
self.recent_file_menu = QMenu(_("Open &recent"), self)
self.recent_file_menu.aboutToShow.connect(self.update_recent_file_menu)
file_menu_actions = [self.new_action,
MENU_SEPARATOR,
self.open_action,
self.open_last_closed_action,
self.recent_file_menu,
MENU_SEPARATOR,
MENU_SEPARATOR,
self.save_action,
self.save_all_action,
save_as_action,
save_copy_as_action,
self.revert_action,
MENU_SEPARATOR,
print_preview_action,
self.print_action,
MENU_SEPARATOR,
self.close_action,
self.close_all_action,
MENU_SEPARATOR]
self.main.file_menu_actions += file_menu_actions
file_toolbar_actions = ([self.new_action, self.open_action,
self.save_action, self.save_all_action] +
self.main.file_toolbar_actions)
self.main.file_toolbar_actions = file_toolbar_actions
# ---- Find menu/toolbar construction ----
self.main.search_menu_actions = [find_action,
find_next_action,
find_previous_action,
replace_action]
self.main.search_toolbar_actions = [find_action,
find_next_action,
replace_action]
# ---- Edit menu/toolbar construction ----
self.edit_menu_actions = [self.toggle_comment_action,
blockcomment_action, unblockcomment_action,
self.indent_action, self.unindent_action,
self.text_uppercase_action,
self.text_lowercase_action]
self.main.edit_menu_actions += [MENU_SEPARATOR] + self.edit_menu_actions
edit_toolbar_actions = [self.toggle_comment_action,
self.unindent_action, self.indent_action]
self.main.edit_toolbar_actions += edit_toolbar_actions
# ---- Search menu/toolbar construction ----
self.main.search_menu_actions += [gotoline_action]
self.main.search_toolbar_actions += [gotoline_action]
# ---- Run menu/toolbar construction ----
run_menu_actions = [run_action, run_cell_action,
run_cell_advance_action,
re_run_last_cell_action, MENU_SEPARATOR,
run_selected_action, re_run_action,
configure_action, MENU_SEPARATOR]
self.main.run_menu_actions += run_menu_actions
run_toolbar_actions = [run_action, run_cell_action,
run_cell_advance_action, run_selected_action,
re_run_action]
self.main.run_toolbar_actions += run_toolbar_actions
# ---- Debug menu/toolbar construction ----
# NOTE: 'list_breakpoints' is used by the breakpoints
# plugin to add its "List breakpoints" action to this
# menu
debug_menu_actions = [debug_action,
debug_next_action,
debug_step_action,
debug_return_action,
debug_continue_action,
debug_exit_action,
MENU_SEPARATOR,
set_clear_breakpoint_action,
set_cond_breakpoint_action,
clear_all_breakpoints_action,
'list_breakpoints',
MENU_SEPARATOR,
self.winpdb_action]
self.main.debug_menu_actions += debug_menu_actions
debug_toolbar_actions = [debug_action, debug_next_action,
debug_step_action, debug_return_action,
debug_continue_action, debug_exit_action]
self.main.debug_toolbar_actions += debug_toolbar_actions
# ---- Source menu/toolbar construction ----
source_menu_actions = [eol_menu,
showblanks_action,
scrollpastend_action,
showindentguides_action,
show_classfunc_dropdown_action,
showcode_analysis_pep8_action,
trailingspaces_action,
fixindentation_action,
MENU_SEPARATOR,
self.todo_list_action,
self.warning_list_action,
self.previous_warning_action,
self.next_warning_action,
MENU_SEPARATOR,
self.previous_edit_cursor_action,
self.previous_cursor_action,
self.next_cursor_action]
self.main.source_menu_actions += source_menu_actions
source_toolbar_actions = [self.todo_list_action,
self.warning_list_action,
self.previous_warning_action,
self.next_warning_action,
MENU_SEPARATOR,
self.previous_edit_cursor_action,
self.previous_cursor_action,
self.next_cursor_action]
self.main.source_toolbar_actions += source_toolbar_actions
# ---- Dock widget and file dependent actions ----
self.dock_toolbar_actions = (file_toolbar_actions +
[MENU_SEPARATOR] +
source_toolbar_actions +
[MENU_SEPARATOR] +
run_toolbar_actions +
[MENU_SEPARATOR] +
debug_toolbar_actions +
[MENU_SEPARATOR] +
edit_toolbar_actions)
self.pythonfile_dependent_actions = [run_action, configure_action,
set_clear_breakpoint_action,
set_cond_breakpoint_action,
debug_action, run_selected_action,
run_cell_action,
run_cell_advance_action,
re_run_last_cell_action,
blockcomment_action,
unblockcomment_action,
self.winpdb_action]
self.cythonfile_compatible_actions = [run_action, configure_action]
self.file_dependent_actions = self.pythonfile_dependent_actions + \
[self.save_action, save_as_action, save_copy_as_action,
print_preview_action, self.print_action,
self.save_all_action, gotoline_action, workdir_action,
self.close_action, self.close_all_action,
self.toggle_comment_action, self.revert_action,
self.indent_action, self.unindent_action]
self.stack_menu_actions = [gotoline_action, workdir_action]
return self.file_dependent_actions
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.main.lspmanager.register_plugin_type(LSPEventTypes.DOCUMENT,
self.sig_lsp_notification)
self.main.restore_scrollbar_position.connect(
self.restore_scrollbar_position)
self.main.console.edit_goto.connect(self.load)
self.exec_in_extconsole.connect(self.main.execute_in_external_console)
self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.open_dir.connect(self.main.workingdirectory.chdir)
self.set_help(self.main.help)
if self.main.outlineexplorer is not None:
self.set_outlineexplorer(self.main.outlineexplorer)
editorstack = self.get_current_editorstack()
if not editorstack.data:
self.__load_temp_file()
self.main.add_dockwidget(self)
self.main.add_to_fileswitcher(self, editorstack.tabs, editorstack.data,
ima.icon('TextFileIcon'))
def update_font(self):
"""Update font from Preferences"""
font = self.get_plugin_font()
color_scheme = self.get_color_scheme()
for editorstack in self.editorstacks:
editorstack.set_default_font(font, color_scheme)
completion_size = CONF.get('main', 'completion/size')
for finfo in editorstack.data:
comp_widget = finfo.editor.completion_widget
comp_widget.setup_appearance(completion_size, font)
def _create_checkable_action(self, text, conf_name, editorstack_method):
"""Helper function to create a checkable action.
Args:
text (str): Text to be displayed in the action.
conf_name (str): configuration setting associated with the action
editorstack_method (str): name of EditorStack class that will be
used to update the changes in each editorstack.
"""
def toogle(checked):
self.switch_to_plugin()
self._toggle_checkable_action(checked, editorstack_method,
conf_name)
action = create_action(self, text, toggled=toogle)
action.setChecked(CONF.get('editor', conf_name))
return action
@Slot(bool, str, str)
def _toggle_checkable_action(self, checked, editorstack_method, conf_name):
"""Handle the toogle of a checkable action.
Update editorstacks and the configuration.
Args:
checked (bool): State of the action.
editorstack_method (str): name of EditorStack class that will be
used to update the changes in each editorstack.
conf_name (str): configuration setting associated with the action.
"""
if self.editorstacks:
for editorstack in self.editorstacks:
try:
editorstack.__getattribute__(editorstack_method)(checked)
except AttributeError as e:
logger.error(e, exc_info=True)
# Run code analysis when `set_pep8_enabled` is toggled
if editorstack_method == 'set_pep8_enabled':
# TODO: Connect this to the LSP
#for finfo in editorstack.data:
# finfo.run_code_analysis(
# self.get_option('code_analysis/pyflakes'),
# checked)
pass
CONF.set('editor', conf_name, checked)
def received_sig_option_changed(self, option, value):
"""
Called when sig_option_changed is received.
If option being changed is autosave_mapping, then synchronize new
mapping with all editor stacks except the sender.
"""
if option == 'autosave_mapping':
for editorstack in self.editorstacks:
if editorstack != self.sender():
editorstack.autosave_mapping = value
self.sig_option_changed.emit(option, value)
#------ Focus tabwidget
def __get_focus_editorstack(self):
fwidget = QApplication.focusWidget()
if isinstance(fwidget, EditorStack):
return fwidget
else:
for editorstack in self.editorstacks:
if editorstack.isAncestorOf(fwidget):
return editorstack
def set_last_focus_editorstack(self, editorwindow, editorstack):
self.last_focus_editorstack[editorwindow] = editorstack
self.last_focus_editorstack[None] = editorstack # very last editorstack
def get_last_focus_editorstack(self, editorwindow=None):
return self.last_focus_editorstack[editorwindow]
def remove_last_focus_editorstack(self, editorstack):
for editorwindow, widget in list(self.last_focus_editorstack.items()):
if widget is editorstack:
self.last_focus_editorstack[editorwindow] = None
def save_focus_editorstack(self):
editorstack = self.__get_focus_editorstack()
if editorstack is not None:
for win in [self]+self.editorwindows:
if win.isAncestorOf(editorstack):
self.set_last_focus_editorstack(win, editorstack)
# ------ Handling editorstacks
def register_editorstack(self, editorstack):
self.editorstacks.append(editorstack)
self.register_widget_shortcuts(editorstack)
if len(self.editorstacks) > 1 and self.main is not None:
# The first editostack is registered automatically with Spyder's
# main window through the `register_plugin` method. Only additional
# editors added by splitting need to be registered.
# See Issue #5057.
self.main.fileswitcher.sig_goto_file.connect(
editorstack.set_stack_index)
if self.isAncestorOf(editorstack):
# editorstack is a child of the Editor plugin
self.set_last_focus_editorstack(self, editorstack)
editorstack.set_closable( len(self.editorstacks) > 1 )
if self.outlineexplorer is not None:
editorstack.set_outlineexplorer(self.outlineexplorer.explorer)
editorstack.set_find_widget(self.find_widget)
editorstack.reset_statusbar.connect(self.readwrite_status.hide)
editorstack.reset_statusbar.connect(self.encoding_status.hide)
editorstack.reset_statusbar.connect(self.cursorpos_status.hide)
editorstack.readonly_changed.connect(
self.readwrite_status.update_readonly)
editorstack.encoding_changed.connect(
self.encoding_status.update_encoding)
editorstack.sig_editor_cursor_position_changed.connect(
self.cursorpos_status.update_cursor_position)
editorstack.sig_refresh_eol_chars.connect(
self.eol_status.update_eol)
editorstack.current_file_changed.connect(
self.vcs_status.update_vcs)
editorstack.file_saved.connect(
self.vcs_status.update_vcs_state)
editorstack.autosave_mapping \
= CONF.get('editor', 'autosave_mapping', {})
editorstack.set_help(self.help)
editorstack.set_io_actions(self.new_action, self.open_action,
self.save_action, self.revert_action)
editorstack.set_tempfile_path(self.TEMPFILE_PATH)
settings = (
('set_pyflakes_enabled', 'code_analysis/pyflakes'),
('set_pep8_enabled', 'code_analysis/pep8'),
('set_todolist_enabled', 'todo_list'),
('set_realtime_analysis_enabled', 'realtime_analysis'),
('set_realtime_analysis_timeout', 'realtime_analysis/timeout'),
('set_blanks_enabled', 'blank_spaces'),
('set_scrollpastend_enabled', 'scroll_past_end'),
('set_linenumbers_enabled', 'line_numbers'),
('set_edgeline_enabled', 'edge_line'),
('set_edgeline_columns', 'edge_line_columns'),
('set_indent_guides', 'indent_guides'),
('set_codecompletion_auto_enabled', 'codecompletion/auto'),
('set_codecompletion_case_enabled', 'codecompletion/case_sensitive'),
('set_codecompletion_enter_enabled', 'codecompletion/enter_key'),
('set_calltips_enabled', 'calltips'),
('set_go_to_definition_enabled', 'go_to_definition'),
('set_focus_to_editor', 'focus_to_editor'),
('set_run_cell_copy', 'run_cell_copy'),
('set_close_parentheses_enabled', 'close_parentheses'),
('set_close_quotes_enabled', 'close_quotes'),
('set_add_colons_enabled', 'add_colons'),
('set_auto_unindent_enabled', 'auto_unindent'),
('set_indent_chars', 'indent_chars'),
('set_tab_stop_width_spaces', 'tab_stop_width_spaces'),
('set_wrap_enabled', 'wrap'),
('set_tabmode_enabled', 'tab_always_indent'),
('set_intelligent_backspace_enabled', 'intelligent_backspace'),
('set_highlight_current_line_enabled', 'highlight_current_line'),
('set_highlight_current_cell_enabled', 'highlight_current_cell'),
('set_occurrence_highlighting_enabled', 'occurrence_highlighting'),
('set_occurrence_highlighting_timeout', 'occurrence_highlighting/timeout'),
('set_checkeolchars_enabled', 'check_eol_chars'),
('set_tabbar_visible', 'show_tab_bar'),
('set_classfunc_dropdown_visible', 'show_class_func_dropdown'),
('set_always_remove_trailing_spaces', 'always_remove_trailing_spaces'),
('set_convert_eol_on_save', 'convert_eol_on_save'),
('set_convert_eol_on_save_to', 'convert_eol_on_save_to'),
)
for method, setting in settings:
getattr(editorstack, method)(self.get_option(setting))
editorstack.set_help_enabled(CONF.get('help', 'connect/editor'))
color_scheme = self.get_color_scheme()
editorstack.set_default_font(self.get_plugin_font(), color_scheme)
editorstack.starting_long_process.connect(self.starting_long_process)
editorstack.ending_long_process.connect(self.ending_long_process)
# Redirect signals
editorstack.sig_option_changed.connect(
self.received_sig_option_changed)
editorstack.redirect_stdio.connect(
lambda state: self.redirect_stdio.emit(state))
editorstack.exec_in_extconsole.connect(
lambda text, option:
self.exec_in_extconsole.emit(text, option))
editorstack.run_cell_in_ipyclient.connect(
lambda code, cell_name, filename, run_cell_copy:
self.run_cell_in_ipyclient.emit(code, cell_name, filename,
run_cell_copy))
editorstack.update_plugin_title.connect(
lambda: self.sig_update_plugin_title.emit())
editorstack.editor_focus_changed.connect(self.save_focus_editorstack)
editorstack.editor_focus_changed.connect(self.main.plugin_focus_changed)
editorstack.zoom_in.connect(lambda: self.zoom(1))
editorstack.zoom_out.connect(lambda: self.zoom(-1))
editorstack.zoom_reset.connect(lambda: self.zoom(0))
editorstack.sig_open_file.connect(self.report_open_file)
editorstack.sig_new_file.connect(lambda s: self.new(text=s))
editorstack.sig_new_file[()].connect(self.new)
editorstack.sig_close_file.connect(self.close_file_in_all_editorstacks)
editorstack.file_saved.connect(self.file_saved_in_editorstack)
editorstack.file_renamed_in_data.connect(
self.file_renamed_in_data_in_editorstack)
editorstack.opened_files_list_changed.connect(
self.opened_files_list_changed)
editorstack.active_languages_stats.connect(
self.update_active_languages)
editorstack.sig_go_to_definition.connect(
lambda fname, line, col: self.load(
fname, line, start_column=col))
editorstack.perform_lsp_request.connect(self.send_lsp_request)
editorstack.todo_results_changed.connect(self.todo_results_changed)
editorstack.update_code_analysis_actions.connect(
self.update_code_analysis_actions)
editorstack.update_code_analysis_actions.connect(
self.update_todo_actions)
editorstack.refresh_file_dependent_actions.connect(
self.refresh_file_dependent_actions)
editorstack.refresh_save_all_action.connect(self.refresh_save_all_action)
editorstack.sig_refresh_eol_chars.connect(self.refresh_eol_chars)
editorstack.sig_breakpoints_saved.connect(self.breakpoints_saved)
editorstack.text_changed_at.connect(self.text_changed_at)
editorstack.current_file_changed.connect(self.current_file_changed)
editorstack.plugin_load.connect(self.load)
editorstack.plugin_load[()].connect(self.load)
editorstack.edit_goto.connect(self.load)
editorstack.sig_save_as.connect(self.save_as)
editorstack.sig_prev_edit_pos.connect(self.go_to_last_edit_location)
editorstack.sig_prev_cursor.connect(self.go_to_previous_cursor_position)
editorstack.sig_next_cursor.connect(self.go_to_next_cursor_position)
editorstack.sig_prev_warning.connect(self.go_to_previous_warning)
editorstack.sig_next_warning.connect(self.go_to_next_warning)
editorstack.sig_save_bookmark.connect(self.save_bookmark)
editorstack.sig_load_bookmark.connect(self.load_bookmark)
editorstack.sig_save_bookmarks.connect(self.save_bookmarks)
def unregister_editorstack(self, editorstack):
"""Removing editorstack only if it's not the last remaining"""
self.remove_last_focus_editorstack(editorstack)
if len(self.editorstacks) > 1:
index = self.editorstacks.index(editorstack)
self.editorstacks.pop(index)
return True
else:
# editorstack was not removed!
return False
def clone_editorstack(self, editorstack):
editorstack.clone_from(self.editorstacks[0])
for finfo in editorstack.data:
self.register_widget_shortcuts(finfo.editor)
@Slot(str, str)
def close_file_in_all_editorstacks(self, editorstack_id_str, filename):
for editorstack in self.editorstacks:
if str(id(editorstack)) != editorstack_id_str:
editorstack.blockSignals(True)
index = editorstack.get_index_from_filename(filename)
editorstack.close_file(index, force=True)
editorstack.blockSignals(False)
@Slot(str, str, str)
def file_saved_in_editorstack(self, editorstack_id_str,
original_filename, filename):
"""A file was saved in editorstack, this notifies others"""
for editorstack in self.editorstacks:
if str(id(editorstack)) != editorstack_id_str:
editorstack.file_saved_in_other_editorstack(original_filename,
filename)
@Slot(str, str, str)
def file_renamed_in_data_in_editorstack(self, editorstack_id_str,
original_filename, filename):
"""A file was renamed in data in editorstack, this notifies others"""
for editorstack in self.editorstacks:
if str(id(editorstack)) != editorstack_id_str:
editorstack.rename_in_data(original_filename, filename)
#------ Handling editor windows
def setup_other_windows(self):
"""Setup toolbars and menus for 'New window' instances"""
self.toolbar_list = ((_("File toolbar"), "file_toolbar",
self.main.file_toolbar_actions),
(_("Search toolbar"), "search_toolbar",
self.main.search_menu_actions),
(_("Source toolbar"), "source_toolbar",
self.main.source_toolbar_actions),
(_("Run toolbar"), "run_toolbar",
self.main.run_toolbar_actions),
(_("Debug toolbar"), "debug_toolbar",
self.main.debug_toolbar_actions),
(_("Edit toolbar"), "edit_toolbar",
self.main.edit_toolbar_actions))
self.menu_list = ((_("&File"), self.main.file_menu_actions),
(_("&Edit"), self.main.edit_menu_actions),
(_("&Search"), self.main.search_menu_actions),
(_("Sour&ce"), self.main.source_menu_actions),
(_("&Run"), self.main.run_menu_actions),
(_("&Tools"), self.main.tools_menu_actions),
(_("&View"), []),
(_("&Help"), self.main.help_menu_actions))
# Create pending new windows:
for layout_settings in self.editorwindows_to_be_created:
win = self.create_new_window()
win.set_layout_settings(layout_settings)
def switch_to_plugin(self):
"""
Reimplemented method to deactivate shortcut when
opening a new window.
"""
if not self.editorwindows:
super(Editor, self).switch_to_plugin()
def create_new_window(self):
oe_options = self.outlineexplorer.explorer.get_options()
window = EditorMainWindow(
self, self.stack_menu_actions, self.toolbar_list, self.menu_list,
show_fullpath=oe_options['show_fullpath'],
show_all_files=oe_options['show_all_files'],
group_cells=oe_options['group_cells'],
show_comments=oe_options['show_comments'],
sort_files_alphabetically=oe_options['sort_files_alphabetically'])
window.add_toolbars_to_menu("&View", window.get_toolbars())
window.load_toolbars()
window.resize(self.size())
window.show()
window.editorwidget.editorsplitter.editorstack.new_window = True
self.register_editorwindow(window)
window.destroyed.connect(lambda: self.unregister_editorwindow(window))
return window
def register_editorwindow(self, window):
self.editorwindows.append(window)
def unregister_editorwindow(self, window):
self.editorwindows.pop(self.editorwindows.index(window))
#------ Accessors
def get_filenames(self):
return [finfo.filename for finfo in self.editorstacks[0].data]
def get_filename_index(self, filename):
return self.editorstacks[0].has_filename(filename)
def get_current_editorstack(self, editorwindow=None):
if self.editorstacks is not None:
if len(self.editorstacks) == 1:
editorstack = self.editorstacks[0]
else:
editorstack = self.__get_focus_editorstack()
if editorstack is None or editorwindow is not None:
editorstack = self.get_last_focus_editorstack(editorwindow)
if editorstack is None:
editorstack = self.editorstacks[0]
return editorstack
def get_current_editor(self):
editorstack = self.get_current_editorstack()
if editorstack is not None:
return editorstack.get_current_editor()
def get_current_finfo(self):
editorstack = self.get_current_editorstack()
if editorstack is not None:
return editorstack.get_current_finfo()
def get_current_filename(self):
editorstack = self.get_current_editorstack()
if editorstack is not None:
return editorstack.get_current_filename()
def is_file_opened(self, filename=None):
return self.editorstacks[0].is_file_opened(filename)
def set_current_filename(self, filename, editorwindow=None, focus=True):
"""Set focus to *filename* if this file has been opened.
Return the editor instance associated to *filename*.
"""
editorstack = self.get_current_editorstack(editorwindow)
return editorstack.set_current_filename(filename, focus)
def set_path(self):
# TODO: Fix this
for finfo in self.editorstacks[0].data:
finfo.path = self.main.get_spyder_pythonpath()
#if self.introspector:
# self.introspector.change_extra_path(
# self.main.get_spyder_pythonpath())
#------ FileSwitcher API
def get_current_tab_manager(self):
"""Get the widget with the TabWidget attribute."""
return self.get_current_editorstack()
#------ Refresh methods
def refresh_file_dependent_actions(self):
"""Enable/disable file dependent actions
(only if dockwidget is visible)"""
if self.dockwidget and self.dockwidget.isVisible():
enable = self.get_current_editor() is not None
for action in self.file_dependent_actions:
action.setEnabled(enable)
def refresh_save_all_action(self):
"""Enable 'Save All' if there are files to be saved"""
editorstack = self.get_current_editorstack()
if editorstack:
state = any(finfo.editor.document().isModified() or finfo.newly_created
for finfo in editorstack.data)
self.save_all_action.setEnabled(state)
def update_warning_menu(self):
"""Update warning list menu"""
editor = self.get_current_editor()
check_results = editor.get_current_warnings()
self.warning_menu.clear()
filename = self.get_current_filename()
for message, line_number in check_results:
error = 'syntax' in message
text = message[:1].upper() + message[1:]
icon = ima.icon('error') if error else ima.icon('warning')
slot = lambda _checked, _l=line_number: self.load(filename, goto=_l)
action = create_action(self, text=text, icon=icon, triggered=slot)
self.warning_menu.addAction(action)
def update_todo_menu(self):
"""Update todo list menu"""
editorstack = self.get_current_editorstack()
results = editorstack.get_todo_results()
self.todo_menu.clear()
filename = self.get_current_filename()
for text, line0 in results:
icon = ima.icon('todo')
slot = lambda _checked, _l=line0: self.load(filename, goto=_l)
action = create_action(self, text=text, icon=icon, triggered=slot)
self.todo_menu.addAction(action)
self.update_todo_actions()
def todo_results_changed(self):
"""
Synchronize todo results between editorstacks
Refresh todo list navigation buttons
"""
editorstack = self.get_current_editorstack()
results = editorstack.get_todo_results()
index = editorstack.get_stack_index()
if index != -1:
filename = editorstack.data[index].filename
for other_editorstack in self.editorstacks:
if other_editorstack is not editorstack:
other_editorstack.set_todo_results(filename, results)
self.update_todo_actions()
def refresh_eol_chars(self, os_name):
os_name = to_text_string(os_name)
self.__set_eol_chars = False
if os_name == 'nt':
self.win_eol_action.setChecked(True)
elif os_name == 'posix':
self.linux_eol_action.setChecked(True)
else:
self.mac_eol_action.setChecked(True)
self.__set_eol_chars = True
#------ Slots
def opened_files_list_changed(self):
"""
Opened files list has changed:
--> open/close file action
--> modification ('*' added to title)
--> current edited file has changed
"""
# Refresh Python file dependent actions:
editor = self.get_current_editor()
if editor:
python_enable = editor.is_python()
cython_enable = python_enable or (
programs.is_module_installed('Cython') and editor.is_cython())
for action in self.pythonfile_dependent_actions:
if action in self.cythonfile_compatible_actions:
enable = cython_enable
else:
enable = python_enable
if action is self.winpdb_action:
action.setEnabled(enable and WINPDB_PATH is not None)
else:
action.setEnabled(enable)
self.open_file_update.emit(self.get_current_filename())
def update_code_analysis_actions(self):
"""Update actions in the warnings menu."""
editor = self.get_current_editor()
# To fix an error at startup
if editor is None:
return
results = editor.get_current_warnings()
# Update code analysis buttons
state = (self.get_option('code_analysis/pyflakes') \
or self.get_option('code_analysis/pep8')) \
and results is not None and len(results)
for action in (self.warning_list_action, self.previous_warning_action,
self.next_warning_action):
if state is not None:
action.setEnabled(state)
def update_todo_actions(self):
editorstack = self.get_current_editorstack()
results = editorstack.get_todo_results()
state = (self.get_option('todo_list') and
results is not None and len(results))
if state is not None:
self.todo_list_action.setEnabled(state)
def rehighlight_cells(self):
"""Rehighlight cells of current editor"""
editor = self.get_current_editor()
editor.rehighlight_cells()
QApplication.processEvents()
@Slot(set)
def update_active_languages(self, languages):
self.main.lspmanager.update_client_status(languages)
#------ Breakpoints
def save_breakpoints(self, filename, breakpoints):
filename = to_text_string(filename)
breakpoints = to_text_string(breakpoints)
filename = osp.normpath(osp.abspath(filename))
if breakpoints:
breakpoints = eval(breakpoints)
else:
breakpoints = []
save_breakpoints(filename, breakpoints)
self.breakpoints_saved.emit()
# ------ Bookmarks
def save_bookmarks(self, filename, bookmarks):
"""Receive bookmark changes and save them."""
filename = to_text_string(filename)
bookmarks = to_text_string(bookmarks)
filename = osp.normpath(osp.abspath(filename))
bookmarks = eval(bookmarks)
save_bookmarks(filename, bookmarks)
#------ File I/O
def __load_temp_file(self):
"""Load temporary file from a text file in user home directory"""
if not osp.isfile(self.TEMPFILE_PATH):
# Creating temporary file
default = ['# -*- coding: utf-8 -*-',
'"""', _("Spyder Editor"), '',
_("This is a temporary script file."),
'"""', '', '']
text = os.linesep.join([encoding.to_unicode(qstr)
for qstr in default])
try:
encoding.write(to_text_string(text), self.TEMPFILE_PATH,
'utf-8')
except EnvironmentError:
self.new()
return
self.load(self.TEMPFILE_PATH)
@Slot()
def __set_workdir(self):
"""Set current script directory as working directory"""
fname = self.get_current_filename()
if fname is not None:
directory = osp.dirname(osp.abspath(fname))
self.open_dir.emit(directory)
def __add_recent_file(self, fname):
"""Add to recent file list"""
if fname is None:
return
if fname in self.recent_files:
self.recent_files.remove(fname)
self.recent_files.insert(0, fname)
if len(self.recent_files) > self.get_option('max_recent_files'):
self.recent_files.pop(-1)
def _clone_file_everywhere(self, finfo):
"""Clone file (*src_editor* widget) in all editorstacks
Cloning from the first editorstack in which every single new editor
is created (when loading or creating a new file)"""
for editorstack in self.editorstacks[1:]:
editor = editorstack.clone_editor_from(finfo, set_current=False)
self.register_widget_shortcuts(editor)
@Slot()
@Slot(str)
def new(self, fname=None, editorstack=None, text=None):
"""
Create a new file - Untitled
fname=None --> fname will be 'untitledXX.py' but do not create file
fname=<basestring> --> create file
"""
# If no text is provided, create default content
empty = False
try:
if text is None:
default_content = True
text, enc = encoding.read(self.TEMPLATE_PATH)
enc_match = re.search(r'-*- coding: ?([a-z0-9A-Z\-]*) -*-',
text)
if enc_match:
enc = enc_match.group(1)
# Initialize template variables
# Windows
username = encoding.to_unicode_from_fs(
os.environ.get('USERNAME', ''))
# Linux, Mac OS X
if not username:
username = encoding.to_unicode_from_fs(
os.environ.get('USER', '-'))
VARS = {
'date': time.ctime(),
'username': username,
}
try:
text = text % VARS
except Exception:
pass
else:
default_content = False
enc = encoding.read(self.TEMPLATE_PATH)[1]
except (IOError, OSError):
text = ''
enc = 'utf-8'
default_content = True
empty = True
create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
# Creating editor widget
if editorstack is None:
current_es = self.get_current_editorstack()
else:
current_es = editorstack
created_from_here = fname is None
if created_from_here:
while True:
fname = create_fname(self.untitled_num)
self.untitled_num += 1
if not osp.isfile(fname):
break
basedir = getcwd_or_home()
if self.main.projects.get_active_project() is not None:
basedir = self.main.projects.get_active_project_path()
else:
c_fname = self.get_current_filename()
if c_fname is not None and c_fname != self.TEMPFILE_PATH:
basedir = osp.dirname(c_fname)
fname = osp.abspath(osp.join(basedir, fname))
else:
# QString when triggered by a Qt signal
fname = osp.abspath(to_text_string(fname))
index = current_es.has_filename(fname)
if index is not None and not current_es.close_file(index):
return
# Creating the editor widget in the first editorstack (the one that
# can't be destroyed), then cloning this editor widget in all other
# editorstacks:
finfo = self.editorstacks[0].new(fname, enc, text, default_content,
empty)
finfo.path = self.main.get_spyder_pythonpath()
self._clone_file_everywhere(finfo)
current_editor = current_es.set_current_filename(finfo.filename)
self.register_widget_shortcuts(current_editor)
if not created_from_here:
self.save(force=True)
def edit_template(self):
"""Edit new file template"""
self.load(self.TEMPLATE_PATH)
def update_recent_file_menu(self):
"""Update recent file menu"""
recent_files = []
for fname in self.recent_files:
if self.is_file_opened(fname) is None and osp.isfile(fname):
recent_files.append(fname)
self.recent_file_menu.clear()
if recent_files:
for fname in recent_files:
action = create_action(self, fname,
icon=ima.icon('FileIcon'),
triggered=self.load)
action.setData(to_qvariant(fname))
self.recent_file_menu.addAction(action)
self.clear_recent_action.setEnabled(len(recent_files) > 0)
add_actions(self.recent_file_menu, (None, self.max_recent_action,
self.clear_recent_action))
@Slot()
def clear_recent_files(self):
"""Clear recent files list"""
self.recent_files = []
@Slot()
def change_max_recent_files(self):
"Change max recent files entries"""
editorstack = self.get_current_editorstack()
mrf, valid = QInputDialog.getInt(editorstack, _('Editor'),
_('Maximum number of recent files'),
self.get_option('max_recent_files'), 1, 35)
if valid:
self.set_option('max_recent_files', mrf)
@Slot()
@Slot(str)
@Slot(str, int, str)
@Slot(str, int, str, object)
def load(self, filenames=None, goto=None, word='',
editorwindow=None, processevents=True, start_column=None,
set_focus=True, add_where='end'):
"""
Load a text file
editorwindow: load in this editorwindow (useful when clicking on
outline explorer with multiple editor windows)
processevents: determines if processEvents() should be called at the
end of this method (set to False to prevent keyboard events from
creeping through to the editor during debugging)
"""
# Switch to editor before trying to load a file
try:
self.switch_to_plugin()
except AttributeError:
pass
editor0 = self.get_current_editor()
if editor0 is not None:
position0 = editor0.get_position('cursor')
filename0 = self.get_current_filename()
else:
position0, filename0 = None, None
if not filenames:
# Recent files action
action = self.sender()
if isinstance(action, QAction):
filenames = from_qvariant(action.data(), to_text_string)
if not filenames:
basedir = getcwd_or_home()
if self.edit_filetypes is None:
self.edit_filetypes = get_edit_filetypes()
if self.edit_filters is None:
self.edit_filters = get_edit_filters()
c_fname = self.get_current_filename()
if c_fname is not None and c_fname != self.TEMPFILE_PATH:
basedir = osp.dirname(c_fname)
self.redirect_stdio.emit(False)
parent_widget = self.get_current_editorstack()
if filename0 is not None:
selectedfilter = get_filter(self.edit_filetypes,
osp.splitext(filename0)[1])
else:
selectedfilter = ''
if not running_under_pytest():
filenames, _sf = getopenfilenames(
parent_widget,
_("Open file"), basedir,
self.edit_filters,
selectedfilter=selectedfilter,
options=QFileDialog.HideNameFilterDetails)
else:
# Use a Qt (i.e. scriptable) dialog for pytest
dialog = QFileDialog(parent_widget, _("Open file"),
options=QFileDialog.DontUseNativeDialog)
if dialog.exec_():
filenames = dialog.selectedFiles()
self.redirect_stdio.emit(True)
if filenames:
filenames = [osp.normpath(fname) for fname in filenames]
else:
return
focus_widget = QApplication.focusWidget()
if self.editorwindows and not self.dockwidget.isVisible():
# We override the editorwindow variable to force a focus on
# the editor window instead of the hidden editor dockwidget.
# See PR #5742.
if editorwindow not in self.editorwindows:
editorwindow = self.editorwindows[0]
editorwindow.setFocus()
editorwindow.raise_()
elif (self.dockwidget and not self.ismaximized
and not self.dockwidget.isAncestorOf(focus_widget)
and not isinstance(focus_widget, CodeEditor)):
self.dockwidget.setVisible(True)
self.dockwidget.setFocus()
self.dockwidget.raise_()
def _convert(fname):
fname = osp.abspath(encoding.to_unicode_from_fs(fname))
if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':':
fname = fname[0].upper()+fname[1:]
return fname
if hasattr(filenames, 'replaceInStrings'):
# This is a QStringList instance (PyQt API #1), converting to list:
filenames = list(filenames)
if not isinstance(filenames, list):
filenames = [_convert(filenames)]
else:
filenames = [_convert(fname) for fname in list(filenames)]
if isinstance(goto, int):
goto = [goto]
elif goto is not None and len(goto) != len(filenames):
goto = None
for index, filename in enumerate(filenames):
# -- Do not open an already opened file
focus = set_focus and index == 0
current_editor = self.set_current_filename(filename,
editorwindow,
focus=focus)
if current_editor is None:
# -- Not a valid filename:
if not osp.isfile(filename):
continue
# --
current_es = self.get_current_editorstack(editorwindow)
# Creating the editor widget in the first editorstack
# (the one that can't be destroyed), then cloning this
# editor widget in all other editorstacks:
finfo = self.editorstacks[0].load(
filename, set_current=False, add_where=add_where)
finfo.path = self.main.get_spyder_pythonpath()
self._clone_file_everywhere(finfo)
current_editor = current_es.set_current_filename(filename,
focus=focus)
current_editor.debugger.load_breakpoints()
current_editor.set_bookmarks(load_bookmarks(filename))
self.register_widget_shortcuts(current_editor)
current_es.analyze_script()
self.__add_recent_file(filename)
if goto is not None: # 'word' is assumed to be None as well
current_editor.go_to_line(goto[index], word=word,
start_column=start_column)
position = current_editor.get_position('cursor')
self.cursor_moved(filename0, position0, filename, position)
current_editor.clearFocus()
current_editor.setFocus()
current_editor.window().raise_()
if processevents:
QApplication.processEvents()
else:
# processevents is false only when calling from debugging
current_editor.sig_debug_stop.emit(goto[index])
current_sw = self.main.ipyconsole.get_current_shellwidget()
current_sw.sig_prompt_ready.connect(
current_editor.sig_debug_stop[()].emit)
@Slot()
def print_file(self):
"""Print current file"""
editor = self.get_current_editor()
filename = self.get_current_filename()
printer = Printer(mode=QPrinter.HighResolution,
header_font=self.get_plugin_font('printer_header'))
printDialog = QPrintDialog(printer, editor)
if editor.has_selected_text():
printDialog.setOption(QAbstractPrintDialog.PrintSelection, True)
self.redirect_stdio.emit(False)
answer = printDialog.exec_()
self.redirect_stdio.emit(True)
if answer == QDialog.Accepted:
self.starting_long_process(_("Printing..."))
printer.setDocName(filename)
editor.print_(printer)
self.ending_long_process()
@Slot()
def print_preview(self):
"""Print preview for current file"""
from qtpy.QtPrintSupport import QPrintPreviewDialog
editor = self.get_current_editor()
printer = Printer(mode=QPrinter.HighResolution,
header_font=self.get_plugin_font('printer_header'))
preview = QPrintPreviewDialog(printer, self)
preview.setWindowFlags(Qt.Window)
preview.paintRequested.connect(lambda printer: editor.print_(printer))
self.redirect_stdio.emit(False)
preview.exec_()
self.redirect_stdio.emit(True)
@Slot()
def close_file(self):
"""Close current file"""
editorstack = self.get_current_editorstack()
editorstack.close_file()
@Slot()
def close_all_files(self):
"""Close all opened scripts"""
self.editorstacks[0].close_all_files()
@Slot()
def save(self, index=None, force=False):
"""Save file"""
editorstack = self.get_current_editorstack()
return editorstack.save(index=index, force=force)
@Slot()
def save_as(self):
"""Save *as* the currently edited file"""
editorstack = self.get_current_editorstack()
if editorstack.save_as():
fname = editorstack.get_current_filename()
self.__add_recent_file(fname)
@Slot()
def save_copy_as(self):
"""Save *copy as* the currently edited file"""
editorstack = self.get_current_editorstack()
editorstack.save_copy_as()
@Slot()
def save_all(self):
"""Save all opened files"""
self.get_current_editorstack().save_all()
@Slot()
def revert(self):
"""Revert the currently edited file from disk"""
editorstack = self.get_current_editorstack()
editorstack.revert()
@Slot()
def find(self):
"""Find slot"""
editorstack = self.get_current_editorstack()
editorstack.find_widget.show()
editorstack.find_widget.search_text.setFocus()
@Slot()
def find_next(self):
"""Fnd next slot"""
editorstack = self.get_current_editorstack()
editorstack.find_widget.find_next()
@Slot()
def find_previous(self):
"""Find previous slot"""
editorstack = self.get_current_editorstack()
editorstack.find_widget.find_previous()
@Slot()
def replace(self):
"""Replace slot"""
editorstack = self.get_current_editorstack()
editorstack.find_widget.show_replace()
def open_last_closed(self):
""" Reopens the last closed tab."""
editorstack = self.get_current_editorstack()
last_closed_files = editorstack.get_last_closed_files()
if (len(last_closed_files) > 0):
file_to_open = last_closed_files[0]
last_closed_files.remove(file_to_open)
editorstack.set_last_closed_files(last_closed_files)
self.load(file_to_open)
#------ Explorer widget
def close_file_from_name(self, filename):
"""Close file from its name"""
filename = osp.abspath(to_text_string(filename))
index = self.editorstacks[0].has_filename(filename)
if index is not None:
self.editorstacks[0].close_file(index)
def removed(self, filename):
"""File was removed in file explorer widget or in project explorer"""
self.close_file_from_name(filename)
def removed_tree(self, dirname):
"""Directory was removed in project explorer widget"""
dirname = osp.abspath(to_text_string(dirname))
for fname in self.get_filenames():
if osp.abspath(fname).startswith(dirname):
self.close_file_from_name(fname)
def renamed(self, source, dest):
"""File was renamed in file explorer widget or in project explorer"""
filename = osp.abspath(to_text_string(source))
index = self.editorstacks[0].has_filename(filename)
if index is not None:
for editorstack in self.editorstacks:
editorstack.rename_in_data(filename,
new_filename=to_text_string(dest))
def renamed_tree(self, source, dest):
"""Directory was renamed in file explorer or in project explorer."""
dirname = osp.abspath(to_text_string(source))
tofile = to_text_string(dest)
for fname in self.get_filenames():
if osp.abspath(fname).startswith(dirname):
new_filename = fname.replace(dirname, tofile)
self.renamed(source=fname, dest=new_filename)
#------ Source code
@Slot()
def indent(self):
"""Indent current line or selection"""
editor = self.get_current_editor()
if editor is not None:
editor.indent()
@Slot()
def unindent(self):
"""Unindent current line or selection"""
editor = self.get_current_editor()
if editor is not None:
editor.unindent()
@Slot()
def text_uppercase (self):
"""Change current line or selection to uppercase."""
editor = self.get_current_editor()
if editor is not None:
editor.transform_to_uppercase()
@Slot()
def text_lowercase(self):
"""Change current line or selection to lowercase."""
editor = self.get_current_editor()
if editor is not None:
editor.transform_to_lowercase()
@Slot()
def toggle_comment(self):
"""Comment current line or selection"""
editor = self.get_current_editor()
if editor is not None:
editor.toggle_comment()
@Slot()
def blockcomment(self):
"""Block comment current line or selection"""
editor = self.get_current_editor()
if editor is not None:
editor.blockcomment()
@Slot()
def unblockcomment(self):
"""Un-block comment current line or selection"""
editor = self.get_current_editor()
if editor is not None:
editor.unblockcomment()
@Slot()
def go_to_next_todo(self):
self.switch_to_plugin()
editor = self.get_current_editor()
position = editor.go_to_next_todo()
filename = self.get_current_filename()
self.add_cursor_position_to_history(filename, position)
@Slot()
def go_to_next_warning(self):
self.switch_to_plugin()
editor = self.get_current_editor()
position = editor.go_to_next_warning()
filename = self.get_current_filename()
self.add_cursor_position_to_history(filename, position)
@Slot()
def go_to_previous_warning(self):
self.switch_to_plugin()
editor = self.get_current_editor()
position = editor.go_to_previous_warning()
filename = self.get_current_filename()
self.add_cursor_position_to_history(filename, position)
@Slot()
def run_winpdb(self):
"""Run winpdb to debug current file"""
if self.save():
fname = self.get_current_filename()
runconf = get_run_configuration(fname)
if runconf is None:
args = []
wdir = None
else:
args = runconf.get_arguments().split()
wdir = runconf.get_working_directory()
# Handle the case where wdir comes back as an empty string
# when the working directory dialog checkbox is unchecked.
# (subprocess "cwd" default is None, so empty str
# must be changed to None in this case.)
programs.run_program(WINPDB_PATH, [fname] + args, cwd=wdir or None)
def toggle_eol_chars(self, os_name, checked):
if checked:
editor = self.get_current_editor()
if self.__set_eol_chars:
self.switch_to_plugin()
editor.set_eol_chars(sourcecode.get_eol_chars_from_os_name(os_name))
@Slot()
def remove_trailing_spaces(self):
self.switch_to_plugin()
editorstack = self.get_current_editorstack()
editorstack.remove_trailing_spaces()
@Slot()
def fix_indentation(self):
self.switch_to_plugin()
editorstack = self.get_current_editorstack()
editorstack.fix_indentation()
#------ Cursor position history management
def update_cursorpos_actions(self):
self.previous_edit_cursor_action.setEnabled(
self.last_edit_cursor_pos is not None)
self.previous_cursor_action.setEnabled(
self.cursor_pos_index is not None and self.cursor_pos_index > 0)
self.next_cursor_action.setEnabled(self.cursor_pos_index is not None \
and self.cursor_pos_index < len(self.cursor_pos_history)-1)
def add_cursor_position_to_history(self, filename, position, fc=False):
if self.__ignore_cursor_position:
return
for index, (fname, pos) in enumerate(self.cursor_pos_history[:]):
if fname == filename:
if pos == position or pos == 0:
if fc:
self.cursor_pos_history[index] = (filename, position)
self.cursor_pos_index = index
self.update_cursorpos_actions()
return
else:
if self.cursor_pos_index >= index:
self.cursor_pos_index -= 1
self.cursor_pos_history.pop(index)
break
if self.cursor_pos_index is not None:
self.cursor_pos_history = \
self.cursor_pos_history[:self.cursor_pos_index+1]
self.cursor_pos_history.append((filename, position))
self.cursor_pos_index = len(self.cursor_pos_history)-1
self.update_cursorpos_actions()
def cursor_moved(self, filename0, position0, filename1, position1):
"""Cursor was just moved: 'go to'"""
if position0 is not None:
self.add_cursor_position_to_history(filename0, position0)
self.add_cursor_position_to_history(filename1, position1)
def text_changed_at(self, filename, position):
self.last_edit_cursor_pos = (to_text_string(filename), position)
def current_file_changed(self, filename, position):
self.add_cursor_position_to_history(to_text_string(filename), position,
fc=True)
@Slot()
def go_to_last_edit_location(self):
if self.last_edit_cursor_pos is not None:
filename, position = self.last_edit_cursor_pos
if not osp.isfile(filename):
self.last_edit_cursor_pos = None
return
else:
self.load(filename)
editor = self.get_current_editor()
if position < editor.document().characterCount():
editor.set_cursor_position(position)
def __move_cursor_position(self, index_move):
if self.cursor_pos_index is None:
return
filename, _position = self.cursor_pos_history[self.cursor_pos_index]
self.cursor_pos_history[self.cursor_pos_index] = ( filename,
self.get_current_editor().get_position('cursor') )
self.__ignore_cursor_position = True
old_index = self.cursor_pos_index
self.cursor_pos_index = min([
len(self.cursor_pos_history)-1,
max([0, self.cursor_pos_index+index_move])
])
filename, position = self.cursor_pos_history[self.cursor_pos_index]
if not osp.isfile(filename):
self.cursor_pos_history.pop(self.cursor_pos_index)
if self.cursor_pos_index < old_index:
old_index -= 1
self.cursor_pos_index = old_index
else:
self.load(filename)
editor = self.get_current_editor()
if position < editor.document().characterCount():
editor.set_cursor_position(position)
self.__ignore_cursor_position = False
self.update_cursorpos_actions()
@Slot()
def go_to_previous_cursor_position(self):
self.switch_to_plugin()
self.__move_cursor_position(-1)
@Slot()
def go_to_next_cursor_position(self):
self.switch_to_plugin()
self.__move_cursor_position(1)
@Slot()
def go_to_line(self, line=None):
"""Open 'go to line' dialog"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
editorstack.go_to_line(line)
@Slot()
def set_or_clear_breakpoint(self):
"""Set/Clear breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_or_clear_breakpoint()
@Slot()
def set_or_edit_conditional_breakpoint(self):
"""Set/Edit conditional breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_or_edit_conditional_breakpoint()
@Slot()
def clear_all_breakpoints(self):
"""Clear breakpoints in all files"""
self.switch_to_plugin()
clear_all_breakpoints()
self.breakpoints_saved.emit()
editorstack = self.get_current_editorstack()
if editorstack is not None:
for data in editorstack.data:
data.editor.debugger.clear_breakpoints()
self.refresh_plugin()
def clear_breakpoint(self, filename, lineno):
"""Remove a single breakpoint"""
clear_breakpoint(filename, lineno)
self.breakpoints_saved.emit()
editorstack = self.get_current_editorstack()
if editorstack is not None:
index = self.is_file_opened(filename)
if index is not None:
editorstack.data[index].editor.debugger.toogle_breakpoint(
lineno)
def debug_command(self, command):
"""Debug actions"""
self.switch_to_plugin()
self.main.ipyconsole.write_to_stdin(command)
focus_widget = self.main.ipyconsole.get_focus_widget()
if focus_widget:
focus_widget.setFocus()
#------ Run Python script
@Slot()
def edit_run_configurations(self):
dialog = RunConfigDialog(self)
dialog.size_change.connect(lambda s: self.set_dialog_size(s))
if self.dialog_size is not None:
dialog.resize(self.dialog_size)
fname = osp.abspath(self.get_current_filename())
dialog.setup(fname)
if dialog.exec_():
fname = dialog.file_to_run
if fname is not None:
self.load(fname)
self.run_file()
@Slot()
def run_file(self, debug=False):
"""Run script inside current interpreter or in a new one"""
editorstack = self.get_current_editorstack()
if editorstack.save():
editor = self.get_current_editor()
fname = osp.abspath(self.get_current_filename())
# Get fname's dirname before we escape the single and double
# quotes (Fixes Issue #6771)
dirname = osp.dirname(fname)
# Escape single and double quotes in fname and dirname
# (Fixes Issue #2158)
fname = fname.replace("'", r"\'").replace('"', r'\"')
dirname = dirname.replace("'", r"\'").replace('"', r'\"')
runconf = get_run_configuration(fname)
if runconf is None:
dialog = RunConfigOneDialog(self)
dialog.size_change.connect(lambda s: self.set_dialog_size(s))
if self.dialog_size is not None:
dialog.resize(self.dialog_size)
dialog.setup(fname)
if CONF.get('run', 'open_at_least_once',
not running_under_pytest()):
# Open Run Config dialog at least once: the first time
# a script is ever run in Spyder, so that the user may
# see it at least once and be conscious that it exists
show_dlg = True
CONF.set('run', 'open_at_least_once', False)
else:
# Open Run Config dialog only
# if ALWAYS_OPEN_FIRST_RUN_OPTION option is enabled
show_dlg = CONF.get('run', ALWAYS_OPEN_FIRST_RUN_OPTION)
if show_dlg and not dialog.exec_():
return
runconf = dialog.get_configuration()
args = runconf.get_arguments()
python_args = runconf.get_python_arguments()
interact = runconf.interact
post_mortem = runconf.post_mortem
current = runconf.current
systerm = runconf.systerm
clear_namespace = runconf.clear_namespace
if runconf.file_dir:
wdir = dirname
elif runconf.cw_dir:
wdir = ''
elif osp.isdir(runconf.dir):
wdir = runconf.dir
else:
wdir = ''
python = True # Note: in the future, it may be useful to run
# something in a terminal instead of a Python interp.
self.__last_ec_exec = (fname, wdir, args, interact, debug,
python, python_args, current, systerm,
post_mortem, clear_namespace)
self.re_run_file()
if not interact and not debug:
# If external console dockwidget is hidden, it will be
# raised in top-level and so focus will be given to the
# current external shell automatically
# (see SpyderPluginWidget.visibility_changed method)
editor.setFocus()
def set_dialog_size(self, size):
self.dialog_size = size
@Slot()
def debug_file(self):
"""Debug current script"""
self.switch_to_plugin()
current_editor = self.get_current_editor()
if current_editor is not None:
current_editor.sig_debug_start.emit()
self.run_file(debug=True)
@Slot()
def re_run_file(self):
"""Re-run last script"""
if self.get_option('save_all_before_run'):
self.save_all()
if self.__last_ec_exec is None:
return
(fname, wdir, args, interact, debug,
python, python_args, current, systerm,
post_mortem, clear_namespace) = self.__last_ec_exec
if not systerm:
self.run_in_current_ipyclient.emit(fname, wdir, args,
debug, post_mortem,
current, clear_namespace)
else:
self.main.open_external_console(fname, wdir, args, interact,
debug, python, python_args,
systerm, post_mortem)
@Slot()
def run_selection(self):
"""Run selection or current line in external console"""
editorstack = self.get_current_editorstack()
editorstack.run_selection()
@Slot()
def run_cell(self):
"""Run current cell"""
editorstack = self.get_current_editorstack()
editorstack.run_cell()
@Slot()
def run_cell_and_advance(self):
"""Run current cell and advance to the next one"""
editorstack = self.get_current_editorstack()
editorstack.run_cell_and_advance()
@Slot()
def re_run_last_cell(self):
"""Run last executed cell."""
editorstack = self.get_current_editorstack()
editorstack.re_run_last_cell()
# ------ Code bookmarks
@Slot(int)
def save_bookmark(self, slot_num):
"""Save current line and position as bookmark."""
bookmarks = CONF.get('editor', 'bookmarks')
editorstack = self.get_current_editorstack()
if slot_num in bookmarks:
filename, line_num, column = bookmarks[slot_num]
if osp.isfile(filename):
index = editorstack.has_filename(filename)
if index is not None:
block = (editorstack.tabs.widget(index).document()
.findBlockByNumber(line_num))
block.userData().bookmarks.remove((slot_num, column))
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_bookmark(slot_num)
@Slot(int)
def load_bookmark(self, slot_num):
"""Set cursor to bookmarked file and position."""
bookmarks = CONF.get('editor', 'bookmarks')
if slot_num in bookmarks:
filename, line_num, column = bookmarks[slot_num]
else:
return
if not osp.isfile(filename):
self.last_edit_cursor_pos = None
return
self.load(filename)
editor = self.get_current_editor()
if line_num < editor.document().lineCount():
linelength = len(editor.document()
.findBlockByNumber(line_num).text())
if column <= linelength:
editor.go_to_line(line_num + 1, column)
else:
# Last column
editor.go_to_line(line_num + 1, linelength)
#------ Zoom in/out/reset
def zoom(self, factor):
"""Zoom in/out/reset"""
editor = self.get_current_editorstack().get_current_editor()
if factor == 0:
font = self.get_plugin_font()
editor.set_font(font)
else:
font = editor.font()
size = font.pointSize() + factor
if size > 0:
font.setPointSize(size)
editor.set_font(font)
editor.update_tab_stop_width_spaces()
#------ Options
def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
if self.editorstacks is not None:
# --- syntax highlight and text rendering settings
color_scheme_n = 'color_scheme_name'
color_scheme_o = self.get_color_scheme()
currentline_n = 'highlight_current_line'
currentline_o = self.get_option(currentline_n)
currentcell_n = 'highlight_current_cell'
currentcell_o = self.get_option(currentcell_n)
occurrence_n = 'occurrence_highlighting'
occurrence_o = self.get_option(occurrence_n)
occurrence_timeout_n = 'occurrence_highlighting/timeout'
occurrence_timeout_o = self.get_option(occurrence_timeout_n)
focus_to_editor_n = 'focus_to_editor'
focus_to_editor_o = self.get_option(focus_to_editor_n)
for editorstack in self.editorstacks:
if color_scheme_n in options:
editorstack.set_color_scheme(color_scheme_o)
if currentline_n in options:
editorstack.set_highlight_current_line_enabled(
currentline_o)
if currentcell_n in options:
editorstack.set_highlight_current_cell_enabled(
currentcell_o)
if occurrence_n in options:
editorstack.set_occurrence_highlighting_enabled(occurrence_o)
if occurrence_timeout_n in options:
editorstack.set_occurrence_highlighting_timeout(
occurrence_timeout_o)
if focus_to_editor_n in options:
editorstack.set_focus_to_editor(focus_to_editor_o)
# --- everything else
tabbar_n = 'show_tab_bar'
tabbar_o = self.get_option(tabbar_n)
classfuncdropdown_n = 'show_class_func_dropdown'
classfuncdropdown_o = self.get_option(classfuncdropdown_n)
linenb_n = 'line_numbers'
linenb_o = self.get_option(linenb_n)
blanks_n = 'blank_spaces'
blanks_o = self.get_option(blanks_n)
scrollpastend_n = 'scroll_past_end'
scrollpastend_o = self.get_option(scrollpastend_n)
edgeline_n = 'edge_line'
edgeline_o = self.get_option(edgeline_n)
edgelinecols_n = 'edge_line_columns'
edgelinecols_o = self.get_option(edgelinecols_n)
wrap_n = 'wrap'
wrap_o = self.get_option(wrap_n)
indentguides_n = 'indent_guides'
indentguides_o = self.get_option(indentguides_n)
tabindent_n = 'tab_always_indent'
tabindent_o = self.get_option(tabindent_n)
ibackspace_n = 'intelligent_backspace'
ibackspace_o = self.get_option(ibackspace_n)
removetrail_n = 'always_remove_trailing_spaces'
removetrail_o = self.get_option(removetrail_n)
converteol_n = 'convert_eol_on_save'
converteol_o = self.get_option(converteol_n)
converteolto_n = 'convert_eol_on_save_to'
converteolto_o = self.get_option(converteolto_n)
runcellcopy_n = 'run_cell_copy'
runcellcopy_o = self.get_option(runcellcopy_n)
autocomp_n = 'codecompletion/auto'
autocomp_o = self.get_option(autocomp_n)
case_comp_n = 'codecompletion/case_sensitive'
case_comp_o = self.get_option(case_comp_n)
enter_key_n = 'codecompletion/enter_key'
enter_key_o = self.get_option(enter_key_n)
calltips_n = 'calltips'
calltips_o = self.get_option(calltips_n)
gotodef_n = 'go_to_definition'
gotodef_o = self.get_option(gotodef_n)
closepar_n = 'close_parentheses'
closepar_o = self.get_option(closepar_n)
close_quotes_n = 'close_quotes'
close_quotes_o = self.get_option(close_quotes_n)
add_colons_n = 'add_colons'
add_colons_o = self.get_option(add_colons_n)
autounindent_n = 'auto_unindent'
autounindent_o = self.get_option(autounindent_n)
indent_chars_n = 'indent_chars'
indent_chars_o = self.get_option(indent_chars_n)
tab_stop_width_spaces_n = 'tab_stop_width_spaces'
tab_stop_width_spaces_o = self.get_option(tab_stop_width_spaces_n)
help_n = 'connect_to_oi'
help_o = CONF.get('help', 'connect/editor')
todo_n = 'todo_list'
todo_o = self.get_option(todo_n)
pyflakes_n = 'code_analysis/pyflakes'
pyflakes_o = self.get_option(pyflakes_n)
pep8_n = 'code_analysis/pep8'
pep8_o = self.get_option(pep8_n)
rt_analysis_n = 'realtime_analysis'
rt_analysis_o = self.get_option(rt_analysis_n)
rta_timeout_n = 'realtime_analysis/timeout'
rta_timeout_o = self.get_option(rta_timeout_n)
finfo = self.get_current_finfo()
for editorstack in self.editorstacks:
if tabbar_n in options:
editorstack.set_tabbar_visible(tabbar_o)
if linenb_n in options:
editorstack.set_linenumbers_enabled(linenb_o,
current_finfo=finfo)
if edgeline_n in options:
editorstack.set_edgeline_enabled(edgeline_o)
if edgelinecols_n in options:
editorstack.set_edgeline_columns(edgelinecols_o)
if wrap_n in options:
editorstack.set_wrap_enabled(wrap_o)
if tabindent_n in options:
editorstack.set_tabmode_enabled(tabindent_o)
if ibackspace_n in options:
editorstack.set_intelligent_backspace_enabled(ibackspace_o)
if removetrail_n in options:
editorstack.set_always_remove_trailing_spaces(removetrail_o)
if converteol_n in options:
editorstack.set_convert_eol_on_save(converteol_o)
if converteolto_n in options:
editorstack.set_convert_eol_on_save_to(converteolto_o)
if runcellcopy_n in options:
editorstack.set_run_cell_copy(runcellcopy_o)
if autocomp_n in options:
editorstack.set_codecompletion_auto_enabled(autocomp_o)
if case_comp_n in options:
editorstack.set_codecompletion_case_enabled(case_comp_o)
if enter_key_n in options:
editorstack.set_codecompletion_enter_enabled(enter_key_o)
if calltips_n in options:
editorstack.set_calltips_enabled(calltips_o)
if gotodef_n in options:
editorstack.set_go_to_definition_enabled(gotodef_o)
if closepar_n in options:
editorstack.set_close_parentheses_enabled(closepar_o)
if close_quotes_n in options:
editorstack.set_close_quotes_enabled(close_quotes_o)
if add_colons_n in options:
editorstack.set_add_colons_enabled(add_colons_o)
if autounindent_n in options:
editorstack.set_auto_unindent_enabled(autounindent_o)
if indent_chars_n in options:
editorstack.set_indent_chars(indent_chars_o)
if tab_stop_width_spaces_n in options:
editorstack.set_tab_stop_width_spaces(tab_stop_width_spaces_o)
if help_n in options:
editorstack.set_help_enabled(help_o)
if todo_n in options:
editorstack.set_todolist_enabled(todo_o,
current_finfo=finfo)
if pyflakes_n in options:
editorstack.set_pyflakes_enabled(pyflakes_o,
current_finfo=finfo)
if pep8_n in options:
editorstack.set_pep8_enabled(pep8_o, current_finfo=finfo)
if rt_analysis_n in options:
editorstack.set_realtime_analysis_enabled(rt_analysis_o)
if rta_timeout_n in options:
editorstack.set_realtime_analysis_timeout(rta_timeout_o)
for name, action in self.checkable_actions.items():
if name in options:
state = self.get_option(name)
action.setChecked(state)
action.trigger()
# Multiply by 1000 to convert seconds to milliseconds
self.autosave.interval = (
self.get_option('autosave_interval') * 1000)
self.autosave.enabled = self.get_option('autosave_enabled')
# We must update the current editor after the others:
# (otherwise, code analysis buttons state would correspond to the
# last editor instead of showing the one of the current editor)
if finfo is not None:
if todo_n in options and todo_o:
finfo.run_todo_finder()
if pyflakes_n in options or pep8_n in options:
# TODO: Connect this to the LSP
#finfo.run_code_analysis(pyflakes_o, pep8_o)
pass
# --- Open files
def get_open_filenames(self):
"""Get the list of open files in the current stack"""
editorstack = self.editorstacks[0]
filenames = []
filenames += [finfo.filename for finfo in editorstack.data]
return filenames
def set_open_filenames(self):
"""
Set the recent opened files on editor based on active project.
If no project is active, then editor filenames are saved, otherwise
the opened filenames are stored in the project config info.
"""
if self.projects is not None:
if not self.projects.get_active_project():
filenames = self.get_open_filenames()
self.set_option('filenames', filenames)
def setup_open_files(self):
"""
Open the list of saved files per project.
Also open any files that the user selected in the recovery dialog.
"""
self.set_create_new_file_if_empty(False)
active_project_path = None
if self.projects is not None:
active_project_path = self.projects.get_active_project_path()
if active_project_path:
filenames = self.projects.get_project_filenames()
else:
filenames = self.get_option('filenames', default=[])
self.close_all_files()
all_filenames = self.autosave.recover_files_to_open + filenames
if all_filenames and any([osp.isfile(f) for f in all_filenames]):
layout = self.get_option('layout_settings', None)
# Check if no saved layout settings exist, e.g. clean prefs file
# If not, load with default focus/layout, to fix issue #8458 .
if layout:
is_vertical, cfname, clines = layout.get('splitsettings')[0]
if cfname in filenames:
index = filenames.index(cfname)
# First we load the last focused file.
self.load(filenames[index], goto=clines[index], set_focus=True)
# Then we load the files located to the left of the last
# focused file in the tabbar, while keeping the focus on
# the last focused file.
if index > 0:
self.load(filenames[index::-1], goto=clines[index::-1],
set_focus=False, add_where='start')
# Then we load the files located to the right of the last
# focused file in the tabbar, while keeping the focus on
# the last focused file.
if index < (len(filenames) - 1):
self.load(filenames[index+1:], goto=clines[index:],
set_focus=False, add_where='end')
# Finally we load any recovered files at the end of the tabbar,
# while keeping focus on the last focused file.
if self.autosave.recover_files_to_open:
self.load(self.autosave.recover_files_to_open,
set_focus=False, add_where='end')
else:
if filenames:
self.load(filenames, goto=clines)
if self.autosave.recover_files_to_open:
self.load(self.autosave.recover_files_to_open)
else:
if filenames:
self.load(filenames)
if self.autosave.recover_files_to_open:
self.load(self.autosave.recover_files_to_open)
if self.__first_open_files_setup:
self.__first_open_files_setup = False
if layout is not None:
self.editorsplitter.set_layout_settings(
layout,
dont_goto=filenames[0])
win_layout = self.get_option('windows_layout_settings', [])
if win_layout:
for layout_settings in win_layout:
self.editorwindows_to_be_created.append(
layout_settings)
self.set_last_focus_editorstack(self, self.editorstacks[0])
else:
self.__load_temp_file()
self.set_create_new_file_if_empty(True)
def save_open_files(self):
"""Save the list of open files"""
self.set_option('filenames', self.get_open_filenames())
def set_create_new_file_if_empty(self, value):
"""Change the value of create_new_file_if_empty"""
for editorstack in self.editorstacks:
editorstack.create_new_file_if_empty = value
|
[] |
[] |
[
"USER",
"USERNAME"
] |
[]
|
["USER", "USERNAME"]
|
python
| 2 | 0 | |
app/rpc/tests/rpc_test.go
|
// This is a test utility for Ethermint's Web3 JSON-RPC services.
//
// To run these tests please first ensure you have the ethermintd running
// and have started the RPC service with `ethermintcli rest-server`.
//
// You can configure the desired HOST and MODE as well
package tests
import (
"bytes"
"encoding/json"
"fmt"
"log"
"math/big"
"math/rand"
"os"
"strings"
"sync"
"testing"
"time"
ethcmn "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/okex/exchain/app/rpc/types"
"github.com/okex/exchain/app/rpc/websockets"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"golang.org/x/net/websocket"
)
const (
addrAStoreKey = 0
defaultProtocolVersion = 65
defaultChainID = 65
defaultMinGasPrice = "0.000000001okt"
latestBlockNumber = "latest"
pendingBlockNumber = "pending"
)
var (
receiverAddr = ethcmn.BytesToAddress([]byte("receiver"))
inexistentAddr = ethcmn.BytesToAddress([]byte{0})
inexistentHash = ethcmn.BytesToHash([]byte("inexistent hash"))
MODE = os.Getenv("MODE")
from = []byte{1}
zeroString = "0x0"
)
func TestMain(m *testing.M) {
var err error
from, err = GetAddress()
if err != nil {
fmt.Printf("failed to get account: %s\n", err)
os.Exit(1)
}
// Start all tests
code := m.Run()
os.Exit(code)
}
func TestEth_Accounts(t *testing.T) {
// all unlocked addresses
rpcRes, err := CallWithError("eth_accounts", nil)
require.NoError(t, err)
require.Equal(t, 1, rpcRes.ID)
var addrsUnlocked []ethcmn.Address
require.NoError(t, json.Unmarshal(rpcRes.Result, &addrsUnlocked))
require.Equal(t, addrCounter, len(addrsUnlocked))
require.True(t, addrsUnlocked[0] == hexAddr1)
require.True(t, addrsUnlocked[1] == hexAddr2)
}
func TestEth_ProtocolVersion(t *testing.T) {
rpcRes, err := CallWithError("eth_protocolVersion", nil)
require.NoError(t, err)
var version hexutil.Uint
require.NoError(t, json.Unmarshal(rpcRes.Result, &version))
require.Equal(t, version, hexutil.Uint(defaultProtocolVersion))
}
func TestEth_ChainId(t *testing.T) {
rpcRes, err := CallWithError("eth_chainId", nil)
require.NoError(t, err)
var chainID hexutil.Uint
require.NoError(t, json.Unmarshal(rpcRes.Result, &chainID))
require.Equal(t, chainID, hexutil.Uint(defaultChainID))
}
func TestEth_Syncing(t *testing.T) {
rpcRes, err := CallWithError("eth_syncing", nil)
require.NoError(t, err)
// single node for test.sh -> always leading without syncing
var catchingUp bool
require.NoError(t, json.Unmarshal(rpcRes.Result, &catchingUp))
require.False(t, catchingUp)
// TODO: set an evn in multi-nodes testnet to test the sycing status of a lagging node
}
func TestEth_Coinbase(t *testing.T) {
// single node -> always the same addr for coinbase
rpcRes, err := CallWithError("eth_coinbase", nil)
require.NoError(t, err)
var coinbaseAddr1 ethcmn.Address
require.NoError(t, json.Unmarshal(rpcRes.Result, &coinbaseAddr1))
// wait for 5s as an block interval
time.Sleep(5 * time.Second)
// query again
rpcRes, err = CallWithError("eth_coinbase", nil)
require.NoError(t, err)
var coinbaseAddr2 ethcmn.Address
require.NoError(t, json.Unmarshal(rpcRes.Result, &coinbaseAddr2))
require.Equal(t, coinbaseAddr1, coinbaseAddr2)
}
func TestEth_PowAttribute(t *testing.T) {
// eth_mining -> always false
rpcRes, err := CallWithError("eth_mining", nil)
require.NoError(t, err)
var mining bool
require.NoError(t, json.Unmarshal(rpcRes.Result, &mining))
require.False(t, mining)
// eth_hashrate -> always 0
rpcRes, err = CallWithError("eth_hashrate", nil)
require.NoError(t, err)
var hashrate hexutil.Uint64
require.NoError(t, json.Unmarshal(rpcRes.Result, &hashrate))
require.True(t, hashrate == 0)
// eth_getUncleCountByBlockHash -> 0 for any hash
rpcRes, err = CallWithError("eth_getUncleCountByBlockHash", []interface{}{inexistentHash})
require.NoError(t, err)
var uncleCount hexutil.Uint
require.NoError(t, json.Unmarshal(rpcRes.Result, &uncleCount))
require.True(t, uncleCount == 0)
// eth_getUncleCountByBlockNumber -> 0 for any block number
rpcRes, err = CallWithError("eth_getUncleCountByBlockNumber", []interface{}{latestBlockNumber})
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &uncleCount))
require.True(t, uncleCount == 0)
// eth_getUncleByBlockHashAndIndex -> always "null"
rand.Seed(time.Now().UnixNano())
luckyNum := int64(rand.Int())
randomBlockHash := ethcmn.BigToHash(big.NewInt(luckyNum))
randomIndex := hexutil.Uint(luckyNum)
rpcRes, err = CallWithError("eth_getUncleByBlockHashAndIndex", []interface{}{randomBlockHash, randomIndex})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
// error check
// miss argument
_, err = CallWithError("eth_getUncleByBlockHashAndIndex", []interface{}{randomBlockHash})
require.Error(t, err)
_, err = CallWithError("eth_getUncleByBlockHashAndIndex", nil)
require.Error(t, err)
// eth_getUncleByBlockNumberAndIndex -> always "null"
luckyNum = int64(rand.Int())
randomBlockHeight := hexutil.Uint(luckyNum)
randomIndex = hexutil.Uint(luckyNum)
rpcRes, err = CallWithError("eth_getUncleByBlockNumberAndIndex", []interface{}{randomBlockHeight, randomIndex})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
// error check
// miss argument
_, err = CallWithError("eth_getUncleByBlockNumberAndIndex", []interface{}{randomBlockHeight})
require.Error(t, err)
_, err = CallWithError("eth_getUncleByBlockNumberAndIndex", nil)
require.Error(t, err)
}
func TestEth_GasPrice(t *testing.T) {
rpcRes, err := CallWithError("eth_gasPrice", nil)
require.NoError(t, err)
var gasPrice hexutil.Big
require.NoError(t, json.Unmarshal(rpcRes.Result, &gasPrice))
// min gas price in test.sh is "0.000000001okt"
mgp, err := sdk.ParseDecCoin(defaultMinGasPrice)
require.NoError(t, err)
require.True(t, mgp.Amount.BigInt().Cmp(gasPrice.ToInt()) == 0)
}
func TestEth_BlockNumber(t *testing.T) {
rpcRes := Call(t, "eth_blockNumber", nil)
var blockNumber1 hexutil.Uint64
require.NoError(t, json.Unmarshal(rpcRes.Result, &blockNumber1))
// wait for 5s as an block interval
time.Sleep(5 * time.Second)
rpcRes = Call(t, "eth_blockNumber", nil)
var blockNumber2 hexutil.Uint64
require.NoError(t, json.Unmarshal(rpcRes.Result, &blockNumber2))
require.True(t, blockNumber2 > blockNumber1)
}
func TestEth_GetBalance(t *testing.T) {
// initial balance of hexAddr2 is 1000000000okt in test.sh
initialBalance, err := sdk.ParseDecCoin("1000000000okt")
require.NoError(t, err)
rpcRes, err := CallWithError("eth_getBalance", []interface{}{hexAddr2, latestBlockNumber})
require.NoError(t, err)
var balance hexutil.Big
require.NoError(t, json.Unmarshal(rpcRes.Result, &balance))
require.True(t, initialBalance.Amount.Int.Cmp(balance.ToInt()) == 0)
// query on certain block height (2)
rpcRes, err = CallWithError("eth_getBalance", []interface{}{hexAddr2, hexutil.EncodeUint64(2)})
require.NoError(t, json.Unmarshal(rpcRes.Result, &balance))
require.NoError(t, err)
require.True(t, initialBalance.Amount.Int.Cmp(balance.ToInt()) == 0)
// query with pending -> no tx in mempool
rpcRes, err = CallWithError("eth_getBalance", []interface{}{hexAddr2, pendingBlockNumber})
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &balance))
require.True(t, initialBalance.Amount.Int.Cmp(balance.ToInt()) == 0)
// inexistent addr -> zero balance
rpcRes, err = CallWithError("eth_getBalance", []interface{}{inexistentAddr, latestBlockNumber})
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &balance))
require.True(t, sdk.ZeroDec().Int.Cmp(balance.ToInt()) == 0)
// error check
// empty hex string
_, err = CallWithError("eth_getBalance", []interface{}{hexAddr2, ""})
require.Error(t, err)
// missing argument
_, err = CallWithError("eth_getBalance", []interface{}{hexAddr2})
require.Error(t, err)
}
func TestEth_SendTransaction_Transfer(t *testing.T) {
value := sdk.NewDec(1024)
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = hexAddr1.Hex()
param[0]["to"] = receiverAddr.Hex()
param[0]["value"] = (*hexutil.Big)(value.BigInt()).String()
param[0]["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
rpcRes := Call(t, "eth_sendTransaction", param)
var hash ethcmn.Hash
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
receipt := WaitForReceipt(t, hash)
require.NotNil(t, receipt)
require.Equal(t, "0x1", receipt["status"].(string))
t.Logf("%s transfers %sokt to %s successfully\n", hexAddr1.Hex(), value.String(), receiverAddr.Hex())
// TODO: logic bug, fix it later
// ignore gas price -> default 'ethermint.DefaultGasPrice' on node -> successfully
//delete(param[0], "gasPrice")
//rpcRes = Call(t, "eth_sendTransaction", param)
//
//require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
//receipt = WaitForReceipt(t, hash)
//require.NotNil(t, receipt)
//require.Equal(t, "0x1", receipt["status"].(string))
//t.Logf("%s transfers %sokt to %s successfully with nil gas price \n", hexAddr1.Hex(), value.String(), receiverAddr.Hex())
// error check
// sender is not unlocked on the node
param[0]["from"] = receiverAddr.Hex()
param[0]["to"] = hexAddr1.Hex()
rpcRes, err := CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// data.Data and data.Input are not same
param[0]["from"], param[0]["to"] = param[0]["to"], param[0]["from"]
param[0]["data"] = "0x1234567890abcdef"
param[0]["input"] = param[0]["data"][:len(param[0]["data"])-2]
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// input and toAddr are all empty
delete(param[0], "to")
delete(param[0], "input")
delete(param[0], "data")
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// 0 gas price
param[0]["to"] = receiverAddr.Hex()
param[0]["gasPrice"] = (*hexutil.Big)(sdk.ZeroDec().BigInt()).String()
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
}
func TestEth_SendTransaction_ContractDeploy(t *testing.T) {
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = hexAddr1.Hex()
param[0]["data"] = "0x6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029"
param[0]["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
rpcRes := Call(t, "eth_sendTransaction", param)
var hash ethcmn.Hash
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
receipt := WaitForReceipt(t, hash)
require.NotNil(t, receipt)
require.Equal(t, "0x1", receipt["status"].(string))
t.Logf("%s deploys contract (filled \"data\") successfully with tx hash %s\n", hexAddr1.Hex(), hash.String())
// TODO: logic bug, fix it later
// ignore gas price -> default 'ethermint.DefaultGasPrice' on node -> successfully
//delete(param[0], "gasPrice")
//rpcRes = Call(t, "eth_sendTransaction", param)
//
//require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
//receipt = WaitForReceipt(t, hash)
//require.NotNil(t, receipt)
//require.Equal(t, "0x1", receipt["status"].(string))
//t.Logf("%s deploys contract successfully with tx hash %s and nil gas price\n", hexAddr1.Hex(), hash.String())
// same payload filled in both 'input' and 'data' -> ok
param[0]["input"] = param[0]["data"]
rpcRes = Call(t, "eth_sendTransaction", param)
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
receipt = WaitForReceipt(t, hash)
require.NotNil(t, receipt)
require.Equal(t, "0x1", receipt["status"].(string))
t.Logf("%s deploys contract (filled \"input\" and \"data\") successfully with tx hash %s\n", hexAddr1.Hex(), hash.String())
// TODO: logic bug, fix it later
// filled in 'input' -> ok
//delete(param[0], "data")
//rpcRes = Call(t, "eth_sendTransaction", param)
//
//require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
//receipt = WaitForReceipt(t, hash)
//require.NotNil(t, receipt)
//require.Equal(t, "0x1", receipt["status"].(string))
//t.Logf("%s deploys contract (filled \"input\") successfully with tx hash %s\n", hexAddr1.Hex(), hash.String())
// error check
// sender is not unlocked on the node
param[0]["from"] = receiverAddr.Hex()
rpcRes, err := CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// data.Data and data.Input are not same
param[0]["from"] = hexAddr1.Hex()
param[0]["input"] = param[0]["data"][:len(param[0]["data"])-2]
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// 0 gas price
delete(param[0], "input")
param[0]["gasPrice"] = (*hexutil.Big)(sdk.ZeroDec().BigInt()).String()
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
// no payload of contract deployment
delete(param[0], "data")
rpcRes, err = CallWithError("eth_sendTransaction", param)
require.Error(t, err)
}
func TestEth_GetStorageAt(t *testing.T) {
expectedRes := hexutil.Bytes{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
rpcRes := Call(t, "eth_getStorageAt", []string{hexAddr1.Hex(), fmt.Sprint(addrAStoreKey), latestBlockNumber})
var storage hexutil.Bytes
require.NoError(t, storage.UnmarshalJSON(rpcRes.Result))
t.Logf("Got value [%X] for %s with key %X\n", storage, hexAddr1.Hex(), addrAStoreKey)
require.True(t, bytes.Equal(storage, expectedRes), "expected: %d (%d bytes) got: %d (%d bytes)", expectedRes, len(expectedRes), storage, len(storage))
// error check
// miss argument
_, err := CallWithError("eth_getStorageAt", []string{hexAddr1.Hex(), fmt.Sprint(addrAStoreKey)})
require.Error(t, err)
_, err = CallWithError("eth_getStorageAt", []string{hexAddr1.Hex()})
require.Error(t, err)
}
func TestEth_GetTransactionByHash(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
rpcRes := Call(t, "eth_getTransactionByHash", []interface{}{hash})
var transaction types.Transaction
require.NoError(t, json.Unmarshal(rpcRes.Result, &transaction))
require.True(t, hexAddr1 == transaction.From)
require.True(t, receiverAddr == *transaction.To)
require.True(t, hash == transaction.Hash)
require.True(t, transaction.Value.ToInt().Cmp(big.NewInt(1024)) == 0)
require.True(t, transaction.GasPrice.ToInt().Cmp(defaultGasPrice.Amount.BigInt()) == 0)
// no input for a transfer tx
require.Equal(t, 0, len(transaction.Input))
// hash not found -> rpcRes.Result -> "null"
rpcRes, err := CallWithError("eth_getTransactionByHash", []interface{}{inexistentHash})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
require.Nil(t, rpcRes.Error)
}
func TestEth_GetTransactionCount(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
height := getBlockHeightFromTxHash(t, hash)
rpcRes := Call(t, "eth_getTransactionCount", []interface{}{hexAddr1, height.String()})
var nonce, preNonce hexutil.Uint64
require.NoError(t, json.Unmarshal(rpcRes.Result, &nonce))
// query height - 1
rpcRes = Call(t, "eth_getTransactionCount", []interface{}{hexAddr1, (height - 1).String()})
require.NoError(t, json.Unmarshal(rpcRes.Result, &preNonce))
require.True(t, nonce-preNonce == 1)
// latestBlock query
rpcRes = Call(t, "eth_getTransactionCount", []interface{}{hexAddr1, latestBlockNumber})
require.NoError(t, json.Unmarshal(rpcRes.Result, &preNonce))
require.Equal(t, nonce, preNonce)
// pendingBlock query
rpcRes = Call(t, "eth_getTransactionCount", []interface{}{hexAddr1, pendingBlockNumber})
require.NoError(t, json.Unmarshal(rpcRes.Result, &nonce))
require.Equal(t, preNonce, nonce)
// error check
// miss argument
_, err := CallWithError("eth_getTransactionCount", []interface{}{hexAddr1})
require.Error(t, err)
_, err = CallWithError("eth_getTransactionCount", nil)
require.Error(t, err)
}
func TestEth_GetBlockTransactionCountByHash(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
blockHash := getBlockHashFromTxHash(t, hash)
require.NotNil(t, blockHash)
rpcRes := Call(t, "eth_getBlockTransactionCountByHash", []interface{}{*blockHash})
var txCount hexutil.Uint
require.NoError(t, json.Unmarshal(rpcRes.Result, &txCount))
// only 1 tx on that height in this single node testnet
require.True(t, txCount == 1)
// inexistent hash -> return nil
rpcRes = Call(t, "eth_getBlockTransactionCountByHash", []interface{}{inexistentHash})
assertNullFromJSONResponse(t, rpcRes.Result)
// error check
// miss argument
_, err := CallWithError("eth_getBlockTransactionCountByHash", nil)
require.Error(t, err)
}
func TestEth_GetBlockTransactionCountByNumber(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
height := getBlockHeightFromTxHash(t, hash)
require.True(t, height != 0)
rpcRes := Call(t, "eth_getBlockTransactionCountByNumber", []interface{}{height.String()})
var txCount hexutil.Uint
require.NoError(t, json.Unmarshal(rpcRes.Result, &txCount))
// only 1 tx on that height in this single node testnet
require.True(t, txCount == 1)
// latestBlock query
rpcRes = Call(t, "eth_getBlockTransactionCountByNumber", []interface{}{latestBlockNumber})
require.NoError(t, json.Unmarshal(rpcRes.Result, &txCount))
// there is no tx on latest block
require.True(t, txCount == 0)
// pendingBlock query
rpcRes = Call(t, "eth_getBlockTransactionCountByNumber", []interface{}{pendingBlockNumber})
require.NoError(t, json.Unmarshal(rpcRes.Result, &txCount))
// there is no tx on latest block and mempool
require.True(t, txCount == 0)
// error check
// miss argument
_, err := CallWithError("eth_getBlockTransactionCountByNumber", nil)
require.Error(t, err)
fmt.Println(err)
}
func TestEth_GetCode(t *testing.T) {
// TODO: logic bug, fix it later
// erc20 contract
//hash, receipet := deployTestContract(t, hexAddr1, erc20ContractKind)
//height := getBlockHeightFromTxHash(t, hash)
//require.True(t, height != 0)
//
//rpcRes := Call(t, "eth_getCode", []interface{}{receipet["contractAddress"], height.String()})
//var code hexutil.Bytes
//require.NoError(t, json.Unmarshal(rpcRes.Result, &code))
//require.True(t, strings.EqualFold(erc20ContractByteCode, code.String()))
// test contract
// TODO: logic bug, fix it later
//hash, receipet := deployTestContract(t, hexAddr1, testContractKind)
//height := getBlockHeightFromTxHash(t, hash)
//require.True(t, height != 0)
//
//rpcRes := Call(t, "eth_getCode", []interface{}{receipet["contractAddress"], height.String()})
//var code hexutil.Bytes
//require.NoError(t, json.Unmarshal(rpcRes.Result, &code))
//fmt.Println(testContractByteCode)
//fmt.Println(code.String())
//require.True(t, strings.EqualFold(testContractByteCode, code.String()))
// error check
// miss argument
// TODO: use a valid contract address as the first argument in params
_, err := CallWithError("eth_getCode", []interface{}{hexAddr1})
require.Error(t, err)
_, err = CallWithError("eth_getCode", nil)
require.Error(t, err)
}
func TestEth_GetTransactionLogs(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
rpcRes := Call(t, "eth_getTransactionLogs", []interface{}{hash})
var transactionLogs []ethtypes.Log
require.NoError(t, json.Unmarshal(rpcRes.Result, &transactionLogs))
// no transaction log for an evm transfer
assertNullFromJSONResponse(t, rpcRes.Result)
// test contract that emits an event in its constructor
hash, receipt := deployTestContract(t, hexAddr1, testContractKind)
rpcRes = Call(t, "eth_getTransactionLogs", []interface{}{hash})
require.NoError(t, json.Unmarshal(rpcRes.Result, &transactionLogs))
require.Equal(t, 1, len(transactionLogs))
require.True(t, ethcmn.HexToAddress(receipt["contractAddress"].(string)) == transactionLogs[0].Address)
require.True(t, hash == transactionLogs[0].TxHash)
// event in test contract constructor keeps the value: 1024
require.True(t, transactionLogs[0].Topics[1].Big().Cmp(big.NewInt(1024)) == 0)
// inexistent tx hash
_, err := CallWithError("eth_getTransactionLogs", []interface{}{inexistentHash})
require.Error(t, err)
// error check
// miss argument
_, err = CallWithError("eth_getTransactionLogs", nil)
require.Error(t, err)
}
func TestEth_Sign(t *testing.T) {
data := []byte("context to sign")
expectedSignature, err := signWithAccNameAndPasswd("alice", defaultPassWd, data)
require.NoError(t, err)
rpcRes := Call(t, "eth_sign", []interface{}{hexAddr1, hexutil.Bytes(data)})
var sig hexutil.Bytes
require.NoError(t, json.Unmarshal(rpcRes.Result, &sig))
require.True(t, bytes.Equal(expectedSignature, sig))
// error check
// inexistent signer
_, err = CallWithError("eth_sign", []interface{}{receiverAddr, hexutil.Bytes(data)})
require.Error(t, err)
// miss argument
_, err = CallWithError("eth_sign", []interface{}{receiverAddr})
require.Error(t, err)
_, err = CallWithError("eth_sign", nil)
require.Error(t, err)
}
func TestEth_Call(t *testing.T) {
// simulate evm transfer
callArgs := make(map[string]string)
callArgs["from"] = hexAddr1.Hex()
callArgs["to"] = receiverAddr.Hex()
callArgs["value"] = hexutil.Uint(1024).String()
callArgs["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
_, err := CallWithError("eth_call", []interface{}{callArgs, latestBlockNumber})
require.NoError(t, err)
// simulate contract deployment
delete(callArgs, "to")
delete(callArgs, "value")
callArgs["data"] = erc20ContractDeployedByteCode
_, err = CallWithError("eth_call", []interface{}{callArgs, latestBlockNumber})
require.NoError(t, err)
// error check
// miss argument
_, err = CallWithError("eth_call", []interface{}{callArgs})
require.Error(t, err)
_, err = CallWithError("eth_call", nil)
require.Error(t, err)
}
func TestEth_EstimateGas_WithoutArgs(t *testing.T) {
// error check
// miss argument
res, err := CallWithError("eth_estimateGas", nil)
require.Error(t, err)
require.Nil(t, res)
}
func TestEth_EstimateGas_Transfer(t *testing.T) {
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = "0x" + fmt.Sprintf("%x", from)
param[0]["to"] = "0x1122334455667788990011223344556677889900"
param[0]["value"] = "0x1"
param[0]["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
rpcRes := Call(t, "eth_estimateGas", param)
require.NotNil(t, rpcRes)
require.NotEmpty(t, rpcRes.Result)
var gas string
err := json.Unmarshal(rpcRes.Result, &gas)
require.NoError(t, err, string(rpcRes.Result))
require.Equal(t, "0x100bb", gas)
}
func TestEth_EstimateGas_ContractDeployment(t *testing.T) {
bytecode := "0x608060405234801561001057600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a260d08061004d6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063eb8ac92114602d575b600080fd5b606060048036036040811015604157600080fd5b8101908080359060200190929190803590602001909291905050506062565b005b8160008190555080827ff3ca124a697ba07e8c5e80bebcfcc48991fc16a63170e8a9206e30508960d00360405160405180910390a3505056fea265627a7a723158201d94d2187aaf3a6790527b615fcc40970febf0385fa6d72a2344848ebd0df3e964736f6c63430005110032"
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = "0x" + fmt.Sprintf("%x", from)
param[0]["data"] = bytecode
rpcRes := Call(t, "eth_estimateGas", param)
require.NotNil(t, rpcRes)
require.NotEmpty(t, rpcRes.Result)
var gas hexutil.Uint64
err := json.Unmarshal(rpcRes.Result, &gas)
require.NoError(t, err, string(rpcRes.Result))
require.Equal(t, "0x1b243", gas.String())
}
func TestEth_GetBlockByHash(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
time.Sleep(3 * time.Second)
expectedBlockHash := getBlockHashFromTxHash(t, hash)
// TODO: OKExChain only supports the block query with txs' hash inside no matter what the second bool argument is.
// eth rpc: false -> txs' hash inside
// true -> txs full content
// TODO: block hash bug , wait for pr merge
//rpcRes := Call(t, "eth_getBlockByHash", []interface{}{expectedBlockHash, false})
//var res map[string]interface{}
//require.NoError(t, json.Unmarshal(rpcRes.Result, &res))
//require.True(t, strings.EqualFold(expectedBlockHash, res["hash"].(string)))
//
//rpcRes = Call(t, "eth_getBlockByHash", []interface{}{expectedBlockHash, true})
//require.NoError(t, json.Unmarshal(rpcRes.Result, &res))
//require.True(t, strings.EqualFold(expectedBlockHash, res["hash"].(string)))
// inexistent hash
//rpcRes, err := CallWithError("eth_getBlockByHash", []interface{}{inexistentHash, false})
// error check
// miss argument
_, err := CallWithError("eth_getBlockByHash", []interface{}{expectedBlockHash})
require.Error(t, err)
_, err = CallWithError("eth_getBlockByHash", nil)
require.Error(t, err)
}
func TestEth_GetBlockByNumber(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
expectedHeight := getBlockHeightFromTxHash(t, hash)
// TODO: OKExChain only supports the block query with txs' hash inside no matter what the second bool argument is.
// eth rpc: false -> txs' hash inside
rpcRes := Call(t, "eth_getBlockByNumber", []interface{}{expectedHeight, false})
var res map[string]interface{}
require.NoError(t, json.Unmarshal(rpcRes.Result, &res))
require.True(t, strings.EqualFold(expectedHeight.String(), res["number"].(string)))
rpcRes = Call(t, "eth_getBlockByNumber", []interface{}{expectedHeight, true})
require.NoError(t, json.Unmarshal(rpcRes.Result, &res))
require.True(t, strings.EqualFold(expectedHeight.String(), res["number"].(string)))
// error check
// future block height -> return nil without error
rpcRes = Call(t, "eth_blockNumber", nil)
var currentBlockHeight hexutil.Uint64
require.NoError(t, json.Unmarshal(rpcRes.Result, ¤tBlockHeight))
rpcRes, err := CallWithError("eth_getBlockByNumber", []interface{}{currentBlockHeight + 100, false})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
// miss argument
_, err = CallWithError("eth_getBlockByNumber", []interface{}{currentBlockHeight})
require.Error(t, err)
_, err = CallWithError("eth_getBlockByNumber", nil)
require.Error(t, err)
}
func TestEth_GetTransactionByBlockHashAndIndex(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(5 * time.Second)
blockHash, index := getBlockHashFromTxHash(t, hash), hexutil.Uint(0)
rpcRes := Call(t, "eth_getTransactionByBlockHashAndIndex", []interface{}{blockHash, index})
var transaction types.Transaction
require.NoError(t, json.Unmarshal(rpcRes.Result, &transaction))
require.True(t, hash == transaction.Hash)
require.True(t, *blockHash == *transaction.BlockHash)
require.True(t, hexutil.Uint64(index) == *transaction.TransactionIndex)
// inexistent block hash
// TODO: error:{"code":1,"log":"internal","height":1497,"codespace":"undefined"}, fix it later
//rpcRes, err := CallWithError("eth_getTransactionByBlockHashAndIndex", []interface{}{inexistentHash, index})
//fmt.Println(err)
// inexistent transaction index -> nil
rpcRes, err := CallWithError("eth_getTransactionByBlockHashAndIndex", []interface{}{blockHash, index + 100})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
// error check
// miss argument
rpcRes, err = CallWithError("eth_getTransactionByBlockHashAndIndex", []interface{}{blockHash})
require.Error(t, err)
rpcRes, err = CallWithError("eth_getTransactionByBlockHashAndIndex", nil)
require.Error(t, err)
}
func TestEth_GetTransactionReceipt(t *testing.T) {
hash := sendTestTransaction(t, hexAddr1, receiverAddr, 1024)
// sleep for a while
time.Sleep(3 * time.Second)
rpcRes := Call(t, "eth_getTransactionReceipt", []interface{}{hash})
var receipt map[string]interface{}
require.NoError(t, json.Unmarshal(rpcRes.Result, &receipt))
require.True(t, strings.EqualFold(hexAddr1.Hex(), receipt["from"].(string)))
require.True(t, strings.EqualFold(receiverAddr.Hex(), receipt["to"].(string)))
require.True(t, strings.EqualFold(hexutil.Uint(1).String(), receipt["status"].(string)))
require.True(t, strings.EqualFold(hash.Hex(), receipt["transactionHash"].(string)))
// contract deployment
hash, receipt = deployTestContract(t, hexAddr1, erc20ContractKind)
require.True(t, strings.EqualFold(hexAddr1.Hex(), receipt["from"].(string)))
require.True(t, strings.EqualFold(hexutil.Uint(1).String(), receipt["status"].(string)))
require.True(t, strings.EqualFold(hash.Hex(), receipt["transactionHash"].(string)))
// inexistent hash -> nil without error
rpcRes, err := CallWithError("eth_getTransactionReceipt", []interface{}{inexistentHash})
require.NoError(t, err)
assertNullFromJSONResponse(t, rpcRes.Result)
// error check
// miss argument
_, err = CallWithError("eth_getTransactionReceipt", nil)
require.Error(t, err)
}
func TestEth_PendingTransactions(t *testing.T) {
// there will be no pending tx in mempool because of the quick grab of block building
rpcRes := Call(t, "eth_pendingTransactions", nil)
var transactions []types.Transaction
require.NoError(t, json.Unmarshal(rpcRes.Result, &transactions))
require.Zero(t, len(transactions))
}
func TestBlockBloom(t *testing.T) {
hash, receipt := deployTestContract(t, hexAddr1, testContractKind)
rpcRes := Call(t, "eth_getBlockByNumber", []interface{}{receipt["blockNumber"].(string), false})
var blockInfo map[string]interface{}
require.NoError(t, json.Unmarshal(rpcRes.Result, &blockInfo))
logsBloom := hexToBloom(t, blockInfo["logsBloom"].(string))
// get the transaction log with tx hash
rpcRes = Call(t, "eth_getTransactionLogs", []interface{}{hash})
var transactionLogs []ethtypes.Log
require.NoError(t, json.Unmarshal(rpcRes.Result, &transactionLogs))
require.Equal(t, 1, len(transactionLogs))
// all the topics in the transactionLogs should be included in the logs bloom of the block
require.True(t, logsBloom.Test(transactionLogs[0].Topics[0].Bytes()))
require.True(t, logsBloom.Test(transactionLogs[0].Topics[1].Bytes()))
// check the consistency of tx hash
require.True(t, strings.EqualFold(hash.Hex(), blockInfo["transactions"].([]interface{})[0].(string)))
}
func TestEth_GetLogs_NoLogs(t *testing.T) {
param := make([]map[string][]string, 1)
param[0] = make(map[string][]string)
// inexistent topics
inexistentTopicsHash := ethcmn.BytesToHash([]byte("inexistent topics")).Hex()
param[0]["topics"] = []string{inexistentTopicsHash}
rpcRes, err := CallWithError("eth_getLogs", param)
require.NoError(t, err)
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(rpcRes.Result, &logs))
require.Zero(t, len(logs))
// error check
_, err = CallWithError("eth_getLogs", nil)
require.Error(t, err)
}
func TestEth_GetLogs_GetTopicsFromHistory(t *testing.T) {
_, receipt := deployTestContract(t, hexAddr1, testContractKind)
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
param[0]["topics"] = []string{helloTopic, worldTopic}
param[0]["fromBlock"] = receipt["blockNumber"].(string)
time.Sleep(time.Second * 5)
rpcRes := Call(t, "eth_getLogs", param)
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(rpcRes.Result, &logs))
require.Equal(t, 1, len(logs))
require.Equal(t, 2, len(logs[0].Topics))
require.True(t, logs[0].Topics[0].Hex() == helloTopic)
require.True(t, logs[0].Topics[1].Hex() == worldTopic)
// get block number from receipt
blockNumber, err := hexutil.DecodeUint64(receipt["blockNumber"].(string))
require.NoError(t, err)
// get current block height -> there is no logs from that height
param[0]["fromBlock"] = hexutil.Uint64(blockNumber + 1).String()
rpcRes, err = CallWithError("eth_getLogs", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &logs))
require.Zero(t, len(logs))
}
func TestEth_GetProof(t *testing.T) {
// initial balance of hexAddr2 is 1000000000okt in test.sh
initialBalance, err := sdk.ParseDecCoin("1000000000okt")
require.NoError(t, err)
rpcRes := Call(t, "eth_getProof", []interface{}{hexAddr2, []string{fmt.Sprint(addrAStoreKey)}, "latest"})
require.NotNil(t, rpcRes)
var accRes types.AccountResult
require.NoError(t, json.Unmarshal(rpcRes.Result, &accRes))
require.True(t, accRes.Address == hexAddr2)
require.True(t, initialBalance.Amount.Int.Cmp(accRes.Balance.ToInt()) == 0)
require.NotEmpty(t, accRes.AccountProof)
require.NotEmpty(t, accRes.StorageProof)
// inexistentAddr -> zero value account result
rpcRes, err = CallWithError("eth_getProof", []interface{}{inexistentAddr, []string{fmt.Sprint(addrAStoreKey)}, "latest"})
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &accRes))
require.True(t, accRes.Address == inexistentAddr)
require.True(t, sdk.ZeroDec().Int.Cmp(accRes.Balance.ToInt()) == 0)
// error check
// miss argument
_, err = CallWithError("eth_getProof", []interface{}{hexAddr2, []string{fmt.Sprint(addrAStoreKey)}})
require.Error(t, err)
_, err = CallWithError("eth_getProof", []interface{}{hexAddr2})
require.Error(t, err)
_, err = CallWithError("eth_getProof", nil)
require.Error(t, err)
}
func TestEth_NewFilter(t *testing.T) {
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
// random topics
param[0]["topics"] = []ethcmn.Hash{ethcmn.BytesToHash([]byte("random topics"))}
rpcRes := Call(t, "eth_newFilter", param)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// fromBlock: latest, toBlock: latest -> no error
delete(param[0], "topics")
param[0]["fromBlock"] = latestBlockNumber
param[0]["toBlock"] = latestBlockNumber
rpcRes, err := CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// fromBlock: nil, toBlock: latest -> no error
delete(param[0], "fromBlock")
rpcRes, err = CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// fromBlock: latest, toBlock: nil -> no error
delete(param[0], "toBlock")
param[0]["fromBlock"] = latestBlockNumber
rpcRes, err = CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// fromBlock: pending, toBlock: pending -> no error
param[0]["fromBlock"] = pendingBlockNumber
param[0]["toBlock"] = pendingBlockNumber
rpcRes, err = CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// fromBlock: latest, toBlock: pending -> no error
param[0]["fromBlock"] = latestBlockNumber
rpcRes, err = CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// toBlock > fromBlock -> no error
param[0]["fromBlock"] = (*hexutil.Big)(big.NewInt(2)).String()
param[0]["toBlock"] = (*hexutil.Big)(big.NewInt(3)).String()
rpcRes, err = CallWithError("eth_newFilter", param)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// error check
// miss argument
_, err = CallWithError("eth_newFilter", nil)
require.Error(t, err)
// fromBlock > toBlock -> error: invalid from and to block combination: from > to
param[0]["fromBlock"] = (*hexutil.Big)(big.NewInt(3)).String()
param[0]["toBlock"] = (*hexutil.Big)(big.NewInt(2)).String()
rpcRes, err = CallWithError("eth_newFilter", param)
require.Error(t, err)
// fromBlock: pending, toBlock: latest
param[0]["fromBlock"] = pendingBlockNumber
param[0]["toBlock"] = latestBlockNumber
rpcRes, err = CallWithError("eth_newFilter", param)
require.Error(t, err)
}
func TestEth_NewBlockFilter(t *testing.T) {
rpcRes := Call(t, "eth_newBlockFilter", nil)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
}
func TestEth_GetFilterChanges_BlockFilter(t *testing.T) {
rpcRes := Call(t, "eth_newBlockFilter", nil)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
// wait for block generation
time.Sleep(5 * time.Second)
changesRes := Call(t, "eth_getFilterChanges", []interface{}{ID})
var hashes []ethcmn.Hash
require.NoError(t, json.Unmarshal(changesRes.Result, &hashes))
require.GreaterOrEqual(t, len(hashes), 1)
// error check
// miss argument
_, err := CallWithError("eth_getFilterChanges", nil)
require.Error(t, err)
}
func TestEth_GetFilterChanges_NoLogs(t *testing.T) {
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
param[0]["topics"] = []ethcmn.Hash{ethcmn.BytesToHash([]byte("random topics"))}
rpcRes := Call(t, "eth_newFilter", param)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
changesRes := Call(t, "eth_getFilterChanges", []interface{}{ID})
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
// no logs
require.Empty(t, logs)
}
func TestEth_GetFilterChanges_WrongID(t *testing.T) {
// ID's length is 16
inexistentID := "0x1234567890abcdef"
_, err := CallWithError("eth_getFilterChanges", []interface{}{inexistentID})
require.Error(t, err)
}
func TestEth_GetFilterChanges_NoTopics(t *testing.T) {
// create a new filter with no topics and latest block height for "fromBlock"
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
param[0]["fromBlock"] = latestBlockNumber
rpcRes := Call(t, "eth_newFilter", param)
require.Nil(t, rpcRes.Error)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
t.Logf("create filter successfully with ID %s\n", ID)
// deploy contract with emitting events
_, _ = deployTestContract(t, hexAddr1, testContractKind)
// get filter changes
changesRes := Call(t, "eth_getFilterChanges", []string{ID})
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
require.Equal(t, 1, len(logs))
}
func TestEth_GetFilterChanges_Addresses(t *testing.T) {
// TODO: logic bug, fix it later
//// deploy contract with emitting events
//_, receipt := deployTestContract(t, hexAddr1, testContractKind)
//contractAddrHex := receipt["contractAddress"].(string)
//blockHeight := receipt["blockNumber"].(string)
//// create a filter
//param := make([]map[string]interface{}, 1)
//param[0] = make(map[string]interface{})
//// focus on the contract by its address
//param[0]["addresses"] = []string{contractAddrHex}
//param[0]["topics"] = []string{helloTopic, worldTopic}
//param[0]["fromBlock"] = blockHeight
//rpcRes := Call(t, "eth_newFilter", param)
//
//var ID string
//require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
//t.Logf("create filter focusing on contract %s successfully with ID %s\n", contractAddrHex, ID)
//
//// get filter changes
//changesRes := Call(t, "eth_getFilterChanges", []string{ID})
//
//var logs []ethtypes.Log
//require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
//require.Equal(t, 1, len(logs))
}
func TestEth_GetFilterChanges_BlockHash(t *testing.T) {
// TODO: logic bug, fix it later
//// deploy contract with emitting events
//_, receipt := deployTestContract(t, hexAddr1, testContractKind)
//blockHash := receipt["blockHash"].(string)
//contractAddrHex := receipt["contractAddress"].(string)
//// create a filter
//param := make([]map[string]interface{}, 1)
//param[0] = make(map[string]interface{})
//// focus on the contract by its address
//param[0]["blockHash"] = blockHash
//param[0]["addresses"] = []string{contractAddrHex}
//param[0]["topics"] = []string{helloTopic, worldTopic}
//rpcRes := Call(t, "eth_newFilter", param)
//
//var ID string
//require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
//t.Logf("create filter focusing on contract %s in the block with block hash %s successfully with ID %s\n", contractAddrHex, blockHash, ID)
//
//// get filter changes
//changesRes := Call(t, "eth_getFilterChanges", []string{ID})
//
//var logs []ethtypes.Log
//require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
//require.Equal(t, 1, len(logs))
}
// Tests topics case where there are topics in first two positions
func TestEth_GetFilterChanges_Topics_AB(t *testing.T) {
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
// set topics in filter with A && B
param[0]["topics"] = []string{helloTopic, worldTopic}
param[0]["fromBlock"] = latestBlockNumber
// create new filter
rpcRes := Call(t, "eth_newFilter", param)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
t.Logf("create filter successfully with ID %s\n", ID)
// deploy contract with emitting events
_, _ = deployTestContract(t, hexAddr1, testContractKind)
// get filter changes
changesRes := Call(t, "eth_getFilterChanges", []string{ID})
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
require.Equal(t, 1, len(logs))
}
func TestEth_GetFilterChanges_Topics_XB(t *testing.T) {
param := make([]map[string]interface{}, 1)
param[0] = make(map[string]interface{})
// set topics in filter with X && B
param[0]["topics"] = []interface{}{nil, worldTopic}
param[0]["fromBlock"] = latestBlockNumber
// create new filter
rpcRes := Call(t, "eth_newFilter", param)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
t.Logf("create filter successfully with ID %s\n", ID)
// deploy contract with emitting events
_, _ = deployTestContract(t, hexAddr1, testContractKind)
// get filter changes
changesRes := Call(t, "eth_getFilterChanges", []string{ID})
var logs []ethtypes.Log
require.NoError(t, json.Unmarshal(changesRes.Result, &logs))
require.Equal(t, 1, len(logs))
}
//func TestEth_GetFilterChanges_Topics_XXC(t *testing.T) {
// t.Skip()
// // TODO: call test function, need tx receipts to determine contract address
//}
func TestEth_PendingTransactionFilter(t *testing.T) {
rpcRes := Call(t, "eth_newPendingTransactionFilter", nil)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
for i := 0; i < 5; i++ {
_, _ = deployTestContract(t, hexAddr1, erc20ContractKind)
}
time.Sleep(10 * time.Second)
// get filter changes
changesRes := Call(t, "eth_getFilterChanges", []string{ID})
require.NotNil(t, changesRes)
var txs []hexutil.Bytes
require.NoError(t, json.Unmarshal(changesRes.Result, &txs))
require.True(t, len(txs) >= 2, "could not get any txs", "changesRes.Result", string(changesRes.Result))
}
func TestEth_UninstallFilter(t *testing.T) {
// create a new filter, get id
rpcRes := Call(t, "eth_newBlockFilter", nil)
var ID string
require.NoError(t, json.Unmarshal(rpcRes.Result, &ID))
require.NotZero(t, ID)
// based on id, uninstall filter
rpcRes = Call(t, "eth_uninstallFilter", []string{ID})
require.NotNil(t, rpcRes)
var status bool
require.NoError(t, json.Unmarshal(rpcRes.Result, &status))
require.Equal(t, true, status)
// uninstall a non-existent filter
rpcRes = Call(t, "eth_uninstallFilter", []string{ID})
require.NotNil(t, rpcRes)
require.NoError(t, json.Unmarshal(rpcRes.Result, &status))
require.Equal(t, false, status)
}
func TestEth_Subscribe_And_UnSubscribe(t *testing.T) {
// create websocket
origin, url := "http://127.0.0.1:8546/", "ws://127.0.0.1:8546"
ws, err := websocket.Dial(url, "", origin)
require.NoError(t, err)
defer func() {
// close websocket
err = ws.Close()
require.NoError(t, err)
}()
// send valid message
validMessage := []byte(`{"id": 2, "method": "eth_subscribe", "params": ["newHeads"]}`)
excuteValidMessage(t, ws, validMessage)
// send invalid message
invalidMessage := []byte(`{"id": 2, "method": "eth_subscribe", "params": ["non-existent method"]}`)
excuteInvalidMessage(t, ws, invalidMessage)
invalidMessage = []byte(`{"id": 2, "method": "eth_subscribe", "params": [""]}`)
excuteInvalidMessage(t, ws, invalidMessage)
}
func excuteValidMessage(t *testing.T, ws *websocket.Conn, message []byte) {
fmt.Println("Send:", string(message))
_, err := ws.Write(message)
require.NoError(t, err)
msg := make([]byte, 10240)
// receive subscription id
n, err := ws.Read(msg)
require.NoError(t, err)
var res Response
require.NoError(t, json.Unmarshal(msg[:n], &res))
subscriptionId := string(res.Result)
// receive message three times
for i := 0; i < 3; i++ {
n, err = ws.Read(msg)
require.NoError(t, err)
fmt.Println("Receive:", string(msg[:n]))
}
// cancel the subscription
cancelMsg := fmt.Sprintf(`{"id": 2, "method": "eth_unsubscribe", "params": [%s]}`, subscriptionId)
fmt.Println("Send:", cancelMsg)
_, err = ws.Write([]byte(cancelMsg))
require.NoError(t, err)
// receive the result of eth_unsubscribe
n, err = ws.Read(msg)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(msg[:n], &res))
require.Equal(t, "true", string(res.Result))
}
func excuteInvalidMessage(t *testing.T, ws *websocket.Conn, message []byte) {
fmt.Println("Send:", string(message))
_, err := ws.Write(message)
require.NoError(t, err)
msg := make([]byte, 10240)
// receive error msg
n, err := ws.Read(msg)
require.NoError(t, err)
var res Response
require.NoError(t, json.Unmarshal(msg[:n], &res))
require.Equal(t, -32600, res.Error.Code)
require.Equal(t, 1, res.ID)
}
func TestWebsocket_PendingTransaction(t *testing.T) {
// create websocket
origin, url := "http://127.0.0.1:8546/", "ws://127.0.0.1:8546"
ws, err := websocket.Dial(url, "", origin)
require.NoError(t, err)
defer func() {
// close websocket
err = ws.Close()
require.NoError(t, err)
}()
// send message to call newPendingTransactions ws api
_, err = ws.Write([]byte(`{"id": 2, "method": "eth_subscribe", "params": ["newPendingTransactions"]}`))
require.NoError(t, err)
msg := make([]byte, 10240)
// receive subscription id
n, err := ws.Read(msg)
require.NoError(t, err)
var res Response
require.NoError(t, json.Unmarshal(msg[:n], &res))
subscriptionId := string(res.Result)
// send transactions
var expectedHashList [3]ethcmn.Hash
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = hexAddr1.Hex()
param[0]["data"] = "0x6080604052348015600f57600080fd5b5060117f775a94827b8fd9b519d36cd827093c664f93347070a554f65e4a6f56cd73889860405160405180910390a2603580604b6000396000f3fe6080604052600080fdfea165627a7a723058206cab665f0f557620554bb45adf266708d2bd349b8a4314bdff205ee8440e3c240029"
param[0]["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
rpcRes := Call(t, "eth_sendTransaction", param)
var hash ethcmn.Hash
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
expectedHashList[i] = hash
}
}()
var actualHashList [3]ethcmn.Hash
// receive message three times
for i := 0; i < 3; i++ {
n, err = ws.Read(msg)
require.NoError(t, err)
var notification websockets.SubscriptionNotification
require.NoError(t, json.Unmarshal(msg[:n], ¬ification))
actualHashList[i] = ethcmn.HexToHash(notification.Params.Result.(string))
}
wg.Wait()
require.EqualValues(t, expectedHashList, actualHashList)
// cancel the subscription
cancelMsg := fmt.Sprintf(`{"id": 2, "method": "eth_unsubscribe", "params": [%s]}`, subscriptionId)
_, err = ws.Write([]byte(cancelMsg))
require.NoError(t, err)
}
//{} or nil matches any topic list
//{A} matches topic A in first position
//{{}, {B}} matches any topic in first position AND B in second position
//{{A}, {B}} matches topic A in first position AND B in second position
//{{A, B}, {C, D}} matches topic (A OR B) in first position AND (C OR D) in second position
func TestWebsocket_Logs(t *testing.T) {
contractAddr1, contractAddr2, contractAddr3 := deployTestTokenContract(t), deployTestTokenContract(t), deployTestTokenContract(t)
// init test cases
tests := []struct {
addressList string // input
topicsList string // input
expected int // expected result
}{
// case 0: matches any contract address & any topics
{"", "", 21},
// case 1: matches one contract address & any topics
{fmt.Sprintf(`"address":"%s"`, contractAddr1), "", 7},
// case 2: matches two contract addressses & any topics
{fmt.Sprintf(`"address":["%s","%s"]`, contractAddr1, contractAddr2), "", 14},
// case 3: matches two contract addressses & one topic in first position
{fmt.Sprintf(`"address":["%s","%s"]`, contractAddr1, contractAddr2), fmt.Sprintf(`"topics":["%s"]`, approveFuncHash), 6},
// case 4: matches two contract addressses & one topic in third position
{fmt.Sprintf(`"address":["%s","%s"]`, contractAddr1, contractAddr2), fmt.Sprintf(`"topics":[null, null, ["%s"]]`, recvAddr1Hash), 4},
// case 5: matches two contract addressses & two topics in first、third position
{fmt.Sprintf(`"address":["%s","%s"]`, contractAddr1, contractAddr2), fmt.Sprintf(`"topics":[["%s"], null, ["%s"]]`, approveFuncHash, recvAddr1Hash), 2},
// case 6: matches two contract addressses & two topic lists in first、third position
{fmt.Sprintf(`"address":["%s","%s"]`, contractAddr1, contractAddr2), fmt.Sprintf(`"topics":[["%s","%s"], null, ["%s","%s"]]`, approveFuncHash, transferFuncHash, recvAddr1Hash, recvAddr2Hash), 8},
}
go func() {
time.Sleep(time.Minute * 2)
panic("the tasks have been running for too long time, over 2 minutes")
}()
// the approximate running time is one minute
var wg sync.WaitGroup
wg.Add(len(tests) + 1)
for i, test := range tests {
go verifyWebSocketRecvNum(t, &wg, i, test.addressList, test.topicsList, test.expected)
}
go sendTxs(t, &wg, contractAddr1, contractAddr2, contractAddr3)
wg.Wait()
}
func deployTestTokenContract(t *testing.T) string {
param := make([]map[string]string, 1)
param[0] = map[string]string{
"from": hexAddr1.Hex(),
"data": ttokenContractByteCode,
"gasPrice": (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String(),
}
rpcRes := Call(t, "eth_sendTransaction", param)
var hash ethcmn.Hash
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
receipt := WaitForReceipt(t, hash)
require.NotNil(t, receipt)
contractAddr, ok := receipt["contractAddress"].(string)
require.True(t, ok)
return contractAddr
}
func verifyWebSocketRecvNum(t *testing.T, wg *sync.WaitGroup, index int, addressList, topicsList string, expected int) {
defer wg.Done()
// create websocket
origin, url := "http://127.0.0.1:8546/", "ws://127.0.0.1:8546"
ws, err := websocket.Dial(url, "", origin)
require.NoError(t, err)
defer func() {
// close websocket
err := ws.Close()
require.NoError(t, err)
}()
// fulfill parameters
param := assembleParameters(addressList, topicsList)
_, err = ws.Write([]byte(param))
require.NoError(t, err)
msg := make([]byte, 10240)
// receive subscription id
n, err := ws.Read(msg)
var res Response
require.NoError(t, err)
require.NoError(t, json.Unmarshal(msg[:n], &res))
require.Nil(t, res.Error)
subscriptionId := string(res.Result)
log.Printf("test case %d: websocket %s is created successfully, expect receive %d logs \n", index, subscriptionId, expected)
for i := 0; i < expected; i++ {
n, err = ws.Read(msg)
require.NoError(t, err)
var notification websockets.SubscriptionNotification
require.NoError(t, json.Unmarshal(msg[:n], ¬ification))
}
// cancel the subscription
cancelMsg := fmt.Sprintf(`{"id": 2, "method": "eth_unsubscribe", "params": [%s]}`, subscriptionId)
_, err = ws.Write([]byte(cancelMsg))
require.NoError(t, err)
log.Printf("test case %d: webdocket %s receive %d logs, then close successfully", index, subscriptionId, expected)
}
func assembleParameters(addressList string, topicsList string) string {
var param string
if addressList == "" {
param = topicsList
}
if topicsList == "" {
param = addressList
}
if addressList != "" && topicsList != "" {
param = addressList + "," + topicsList
}
return fmt.Sprintf(`{"id": 2, "method": "eth_subscribe", "params": ["logs",{%s}]}`, param)
}
func sendTxs(t *testing.T, wg *sync.WaitGroup, contractAddrs ...string) {
dataList := []string{
// 0. mint 4294967295coin -> 0x2cf4ea7df75b513509d95946b43062e26bd88035
"0x40c10f190000000000000000000000002cf4ea7df75b513509d95946b43062e26bd8803500000000000000000000000000000000000000000000000000000000ffffffff",
// 1. approve 12345678coin -> 0x9ad84c8630e0282f78e5479b46e64e17779e3cfb
"0x095ea7b30000000000000000000000009ad84c8630e0282f78e5479b46e64e17779e3cfb0000000000000000000000000000000000000000000000000000000000bc614e",
// 2. approve 12345678coin -> 0xc9c9b43322f5e1dc401252076fa4e699c9122cd6
"0x095ea7b3000000000000000000000000c9c9b43322f5e1dc401252076fa4e699c9122cd60000000000000000000000000000000000000000000000000000000000bc614e",
// 3. approve 12345678coin -> 0x2B5Cf24AeBcE90f0B8f80Bc42603157b27cFbf47
"0x095ea7b30000000000000000000000002b5cf24aebce90f0b8f80bc42603157b27cfbf470000000000000000000000000000000000000000000000000000000000bc614e",
// 4. transfer 1234coin -> 0x9ad84c8630e0282f78e5479b46e64e17779e3cfb
"0xa9059cbb0000000000000000000000009ad84c8630e0282f78e5479b46e64e17779e3cfb00000000000000000000000000000000000000000000000000000000000004d2",
// 5. transfer 1234coin -> 0xc9c9b43322f5e1dc401252076fa4e699c9122cd6
"0xa9059cbb000000000000000000000000c9c9b43322f5e1dc401252076fa4e699c9122cd600000000000000000000000000000000000000000000000000000000000004d2",
// 6. transfer 1234coin -> 0x2B5Cf24AeBcE90f0B8f80Bc42603157b27cFbf47
"0xa9059cbb0000000000000000000000002b5cf24aebce90f0b8f80bc42603157b27cfbf4700000000000000000000000000000000000000000000000000000000000004d2",
}
defer wg.Done()
for _, contractAddr := range contractAddrs {
for i := 0; i < 7; i++ {
param := make([]map[string]string, 1)
param[0] = make(map[string]string)
param[0]["from"] = hexAddr1.Hex()
param[0]["to"] = contractAddr
param[0]["data"] = dataList[i]
param[0]["gasPrice"] = (*hexutil.Big)(defaultGasPrice.Amount.BigInt()).String()
rpcRes := Call(t, "eth_sendTransaction", param)
var hash ethcmn.Hash
require.NoError(t, json.Unmarshal(rpcRes.Result, &hash))
time.Sleep(time.Second * 1)
}
}
}
|
[
"\"MODE\""
] |
[] |
[
"MODE"
] |
[]
|
["MODE"]
|
go
| 1 | 0 | |
vendor/github.com/onsi/ginkgo/types/deprecation_support.go
|
package types
import (
"os"
"strconv"
"strings"
"unicode"
"github.com/onsi/ginkgo/config"
"github.com/onsi/ginkgo/formatter"
)
type Deprecation struct {
Message string
DocLink string
Version string
}
type deprecations struct{}
var Deprecations = deprecations{}
func (d deprecations) CustomReporter() Deprecation {
return Deprecation{
Message: "You are using a custom reporter. Support for custom reporters will likely be removed in V2. Most users were using them to generate junit or teamcity reports and this functionality will be merged into the core reporter. In addition, Ginkgo 2.0 will support emitting a JSON-formatted report that users can then manipulate to generate custom reports.\n\n{{red}}{{bold}}If this change will be impactful to you please leave a comment on {{cyan}}{{underline}}https://github.com/onsi/ginkgo/issues/711{{/}}",
DocLink: "removed-custom-reporters",
Version: "1.16.0",
}
}
func (d deprecations) V1Reporter() Deprecation {
return Deprecation{
Message: "You are using a V1 Ginkgo Reporter. Please update your custom reporter to the new V2 Reporter interface.",
DocLink: "changed-reporter-interface",
Version: "1.16.0",
}
}
func (d deprecations) Async() Deprecation {
return Deprecation{
Message: "You are passing a Done channel to a test node to test asynchronous behavior. This is deprecated in Ginkgo V2. Your test will run synchronously and the timeout will be ignored.",
DocLink: "removed-async-testing",
Version: "1.16.0",
}
}
func (d deprecations) Measure() Deprecation {
return Deprecation{
Message: "Measure is deprecated and will be removed in Ginkgo V2. Please migrate to gomega/gmeasure.",
DocLink: "removed-measure",
Version: "1.16.3",
}
}
func (d deprecations) ParallelNode() Deprecation {
return Deprecation{
Message: "GinkgoParallelNode is deprecated and will be removed in Ginkgo V2. Please use GinkgoParallelProcess instead.",
DocLink: "renamed-ginkgoparallelnode",
Version: "1.16.5",
}
}
func (d deprecations) Convert() Deprecation {
return Deprecation{
Message: "The convert command is deprecated in Ginkgo V2",
DocLink: "removed-ginkgo-convert",
Version: "1.16.0",
}
}
func (d deprecations) Blur() Deprecation {
return Deprecation{
Message: "The blur command is deprecated in Ginkgo V2. Use 'ginkgo unfocus' instead.",
Version: "1.16.0",
}
}
type DeprecationTracker struct {
deprecations map[Deprecation][]CodeLocation
}
func NewDeprecationTracker() *DeprecationTracker {
return &DeprecationTracker{
deprecations: map[Deprecation][]CodeLocation{},
}
}
func (d *DeprecationTracker) TrackDeprecation(deprecation Deprecation, cl ...CodeLocation) {
ackVersion := os.Getenv("ACK_GINKGO_DEPRECATIONS")
if deprecation.Version != "" && ackVersion != "" {
ack := ParseSemVer(ackVersion)
version := ParseSemVer(deprecation.Version)
if ack.GreaterThanOrEqualTo(version) {
return
}
}
if len(cl) == 1 {
d.deprecations[deprecation] = append(d.deprecations[deprecation], cl[0])
} else {
d.deprecations[deprecation] = []CodeLocation{}
}
}
func (d *DeprecationTracker) DidTrackDeprecations() bool {
return len(d.deprecations) > 0
}
func (d *DeprecationTracker) DeprecationsReport() string {
out := formatter.F("\n{{light-yellow}}You're using deprecated Ginkgo functionality:{{/}}\n")
out += formatter.F("{{light-yellow}}============================================={{/}}\n")
out += formatter.F("{{bold}}{{green}}Ginkgo 2.0{{/}} is under active development and will introduce several new features, improvements, and a small handful of breaking changes.\n")
out += formatter.F("A release candidate for 2.0 is now available and 2.0 should GA in Fall 2021. {{bold}}Please give the RC a try and send us feedback!{{/}}\n")
out += formatter.F(" - To learn more, view the migration guide at {{cyan}}{{underline}}https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md{{/}}\n")
out += formatter.F(" - For instructions on using the Release Candidate visit {{cyan}}{{underline}}https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md#using-the-beta{{/}}\n")
out += formatter.F(" - To comment, chime in at {{cyan}}{{underline}}https://github.com/onsi/ginkgo/issues/711{{/}}\n\n")
for deprecation, locations := range d.deprecations {
out += formatter.Fi(1, "{{yellow}}"+deprecation.Message+"{{/}}\n")
if deprecation.DocLink != "" {
out += formatter.Fi(1, "{{bold}}Learn more at:{{/}} {{cyan}}{{underline}}https://github.com/onsi/ginkgo/blob/ver2/docs/MIGRATING_TO_V2.md#%s{{/}}\n", deprecation.DocLink)
}
for _, location := range locations {
out += formatter.Fi(2, "{{gray}}%s{{/}}\n", location)
}
}
out += formatter.F("\n{{gray}}To silence deprecations that can be silenced set the following environment variable:{{/}}\n")
out += formatter.Fi(1, "{{gray}}ACK_GINKGO_DEPRECATIONS=%s{{/}}\n", config.VERSION)
return out
}
type SemVer struct {
Major int
Minor int
Patch int
}
func (s SemVer) GreaterThanOrEqualTo(o SemVer) bool {
return (s.Major > o.Major) ||
(s.Major == o.Major && s.Minor > o.Minor) ||
(s.Major == o.Major && s.Minor == o.Minor && s.Patch >= o.Patch)
}
func ParseSemVer(semver string) SemVer {
out := SemVer{}
semver = strings.TrimFunc(semver, func(r rune) bool {
return !(unicode.IsNumber(r) || r == '.')
})
components := strings.Split(semver, ".")
if len(components) > 0 {
out.Major, _ = strconv.Atoi(components[0])
}
if len(components) > 1 {
out.Minor, _ = strconv.Atoi(components[1])
}
if len(components) > 2 {
out.Patch, _ = strconv.Atoi(components[2])
}
return out
}
|
[
"\"ACK_GINKGO_DEPRECATIONS\""
] |
[] |
[
"ACK_GINKGO_DEPRECATIONS"
] |
[]
|
["ACK_GINKGO_DEPRECATIONS"]
|
go
| 1 | 0 | |
tests/test_recipe.py
|
import os
import pytest
import types
import unittest
import warnings
from unittest import mock
from backports import tempfile
from pythonforandroid.build import Context
from pythonforandroid.recipe import Recipe, import_recipe
from pythonforandroid.archs import ArchAarch_64
from pythonforandroid.bootstrap import Bootstrap
from pythonforandroid.util import build_platform
from test_bootstrap import BaseClassSetupBootstrap
def patch_logger(level):
return mock.patch('pythonforandroid.recipe.{}'.format(level))
def patch_logger_info():
return patch_logger('info')
def patch_logger_debug():
return patch_logger('debug')
def patch_urlretrieve():
return mock.patch('pythonforandroid.recipe.urlretrieve')
class DummyRecipe(Recipe):
pass
class TestRecipe(unittest.TestCase):
def test_recipe_dirs(self):
"""
Trivial `recipe_dirs()` test.
Makes sure the list is not empty and has the root directory.
"""
ctx = Context()
recipes_dir = Recipe.recipe_dirs(ctx)
# by default only the root dir `recipes` directory
self.assertEqual(len(recipes_dir), 1)
self.assertTrue(recipes_dir[0].startswith(ctx.root_dir))
def test_list_recipes(self):
"""
Trivial test verifying list_recipes returns a generator with some recipes.
"""
ctx = Context()
recipes = Recipe.list_recipes(ctx)
self.assertTrue(isinstance(recipes, types.GeneratorType))
recipes = list(recipes)
self.assertIn('python3', recipes)
def test_get_recipe(self):
"""
Makes sure `get_recipe()` returns a `Recipe` object when possible.
"""
ctx = Context()
recipe_name = 'python3'
recipe = Recipe.get_recipe(recipe_name, ctx)
self.assertTrue(isinstance(recipe, Recipe))
self.assertEqual(recipe.name, recipe_name)
recipe_name = 'does_not_exist'
with self.assertRaises(ValueError) as e:
Recipe.get_recipe(recipe_name, ctx)
self.assertEqual(
e.exception.args[0], 'Recipe does not exist: {}'.format(recipe_name))
def test_import_recipe(self):
"""
Verifies we can dynamically import a recipe without warnings.
"""
p4a_root_dir = os.path.dirname(os.path.dirname(__file__))
name = 'pythonforandroid.recipes.python3'
pathname = os.path.join(
*([p4a_root_dir] + name.split('.') + ['__init__.py'])
)
with warnings.catch_warnings(record=True) as recorded_warnings:
warnings.simplefilter("always")
module = import_recipe(name, pathname)
assert module is not None
assert recorded_warnings == []
def test_download_if_necessary(self):
"""
Download should happen via `Recipe.download()` only if the recipe
specific environment variable is not set.
"""
# download should happen as the environment variable is not set
recipe = DummyRecipe()
with mock.patch.object(Recipe, 'download') as m_download:
recipe.download_if_necessary()
assert m_download.call_args_list == [mock.call()]
# after setting it the download should be skipped
env_var = 'P4A_test_recipe_DIR'
env_dict = {env_var: '1'}
with mock.patch.object(Recipe, 'download') as m_download, mock.patch.dict(os.environ, env_dict):
recipe.download_if_necessary()
assert m_download.call_args_list == []
def test_download_url_not_set(self):
"""
Verifies that no download happens when URL is not set.
"""
recipe = DummyRecipe()
with patch_logger_info() as m_info:
recipe.download()
assert m_info.call_args_list == [
mock.call('Skipping test_recipe download as no URL is set')]
@staticmethod
def get_dummy_python_recipe_for_download_tests():
"""
Helper method for creating a test recipe used in download tests.
"""
recipe = DummyRecipe()
filename = 'Python-3.7.4.tgz'
url = 'https://www.python.org/ftp/python/3.7.4/{}'.format(filename)
recipe._url = url
recipe.ctx = Context()
return recipe, filename
def test_download_url_is_set(self):
"""
Verifies the actual download gets triggered when the URL is set.
"""
recipe, filename = self.get_dummy_python_recipe_for_download_tests()
url = recipe.url
with (
patch_logger_debug()) as m_debug, (
mock.patch.object(Recipe, 'download_file')) as m_download_file, (
mock.patch('pythonforandroid.recipe.sh.touch')) as m_touch, (
tempfile.TemporaryDirectory()) as temp_dir:
recipe.ctx.setup_dirs(temp_dir)
recipe.download()
assert m_download_file.call_args_list == [mock.call(url, filename)]
assert m_debug.call_args_list == [
mock.call(
'Downloading test_recipe from '
'https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz')]
assert m_touch.call_count == 1
def test_download_file_scheme_https(self):
"""
Verifies `urlretrieve()` is being called on https downloads.
"""
recipe, filename = self.get_dummy_python_recipe_for_download_tests()
url = recipe.url
with (
patch_urlretrieve()) as m_urlretrieve, (
tempfile.TemporaryDirectory()) as temp_dir:
recipe.ctx.setup_dirs(temp_dir)
assert recipe.download_file(url, filename) == filename
assert m_urlretrieve.call_args_list == [
mock.call(url, filename, mock.ANY)
]
def test_download_file_scheme_https_oserror(self):
"""
Checks `urlretrieve()` is being retried on `OSError`.
After a number of retries the exception is re-reaised.
"""
recipe, filename = self.get_dummy_python_recipe_for_download_tests()
url = recipe.url
with (
patch_urlretrieve()) as m_urlretrieve, (
mock.patch('pythonforandroid.recipe.time.sleep')) as m_sleep, (
pytest.raises(OSError)), (
tempfile.TemporaryDirectory()) as temp_dir:
recipe.ctx.setup_dirs(temp_dir)
m_urlretrieve.side_effect = OSError
assert recipe.download_file(url, filename) == filename
retry = 5
expected_call_args_list = [mock.call(url, filename, mock.ANY)] * retry
assert m_urlretrieve.call_args_list == expected_call_args_list
expected_call_args_list = [mock.call(2**i) for i in range(retry - 1)]
assert m_sleep.call_args_list == expected_call_args_list
class TestLibraryRecipe(BaseClassSetupBootstrap, unittest.TestCase):
def setUp(self):
"""
Initialize a Context with a Bootstrap and a Distribution to properly
test an library recipe, to do so we reuse `BaseClassSetupBootstrap`
"""
super().setUp()
self.ctx.bootstrap = Bootstrap().get_bootstrap('sdl2', self.ctx)
self.setUp_distribution_with_bootstrap(self.ctx.bootstrap)
def test_built_libraries(self):
"""The openssl recipe is a library recipe, so it should have set the
attribute `built_libraries`, but not the case of `pyopenssl` recipe.
"""
recipe = Recipe.get_recipe('openssl', self.ctx)
self.assertTrue(recipe.built_libraries)
recipe = Recipe.get_recipe('pyopenssl', self.ctx)
self.assertFalse(recipe.built_libraries)
@mock.patch('pythonforandroid.recipe.exists')
def test_should_build(self, mock_exists):
# avoid trying to find the recipe in a non-existing storage directory
self.ctx.storage_dir = None
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('openssl', self.ctx)
recipe.ctx = self.ctx
self.assertFalse(recipe.should_build(arch))
mock_exists.return_value = False
self.assertTrue(recipe.should_build(arch))
@mock.patch('pythonforandroid.recipe.Recipe.get_libraries')
@mock.patch('pythonforandroid.recipe.Recipe.install_libs')
def test_install_libraries(self, mock_install_libs, mock_get_libraries):
mock_get_libraries.return_value = {
'/build_lib/libsample1.so',
'/build_lib/libsample2.so',
}
self.ctx.recipe_build_order = [
"hostpython3",
"openssl",
"python3",
"sdl2",
"kivy",
]
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('openssl', self.ctx)
recipe.install_libraries(arch)
mock_install_libs.assert_called_once_with(
arch, *mock_get_libraries.return_value
)
class TesSTLRecipe(BaseClassSetupBootstrap, unittest.TestCase):
def setUp(self):
"""
Initialize a Context with a Bootstrap and a Distribution to properly
test a recipe which depends on android's STL library, to do so we reuse
`BaseClassSetupBootstrap`
"""
super().setUp()
self.ctx.bootstrap = Bootstrap().get_bootstrap('sdl2', self.ctx)
self.setUp_distribution_with_bootstrap(self.ctx.bootstrap)
self.ctx.python_recipe = Recipe.get_recipe('python3', self.ctx)
def test_get_stl_lib_dir(self):
"""
Test that :meth:`~pythonforandroid.recipe.STLRecipe.get_stl_lib_dir`
returns the expected path for the stl library
"""
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('icu', self.ctx)
self.assertTrue(recipe.need_stl_shared)
self.assertEqual(
recipe.get_stl_lib_dir(arch),
os.path.join(
self.ctx.ndk_dir,
'sources/cxx-stl/llvm-libc++/libs/{arch}'.format(
arch=arch.arch
),
),
)
@mock.patch("pythonforandroid.archs.glob")
@mock.patch('pythonforandroid.archs.find_executable')
@mock.patch('pythonforandroid.build.ensure_dir')
def test_get_recipe_env_with(
self, mock_ensure_dir, mock_find_executable, mock_glob
):
"""
Test that :meth:`~pythonforandroid.recipe.STLRecipe.get_recipe_env`
returns some expected keys and values.
.. note:: We don't check all the env variables, only those one specific
of :class:`~pythonforandroid.recipe.STLRecipe`, the others
should be tested in the proper test.
"""
expected_compiler = (
f"/opt/android/android-ndk/toolchains/"
f"llvm/prebuilt/{build_platform}/bin/clang"
)
mock_find_executable.return_value = expected_compiler
mock_glob.return_value = ["llvm"]
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('icu', self.ctx)
assert recipe.need_stl_shared, True
env = recipe.get_recipe_env(arch)
# check that the mocks have been called
mock_glob.assert_called()
mock_ensure_dir.assert_called()
mock_find_executable.assert_called_once_with(
expected_compiler, path=os.environ['PATH']
)
self.assertIsInstance(env, dict)
# check `CPPFLAGS`
expected_cppflags = {
'-I{stl_include}'.format(stl_include=recipe.stl_include_dir)
}
self.assertIn('CPPFLAGS', env)
for flags in expected_cppflags:
self.assertIn(flags, env['CPPFLAGS'])
# check `LIBS`
self.assertIn('LDFLAGS', env)
self.assertIn('-L' + recipe.get_stl_lib_dir(arch), env['LDFLAGS'])
self.assertIn('LIBS', env)
self.assertIn('-lc++_shared', env['LIBS'])
# check `CXXFLAGS` and `CXX`
for flag in {'CXXFLAGS', 'CXX'}:
self.assertIn(flag, env)
self.assertIn('-frtti -fexceptions', env[flag])
@mock.patch('pythonforandroid.recipe.Recipe.install_libs')
@mock.patch('pythonforandroid.recipe.isfile')
@mock.patch('pythonforandroid.build.ensure_dir')
def test_install_stl_lib(
self, mock_ensure_dir, mock_isfile, mock_install_lib
):
"""
Test that :meth:`~pythonforandroid.recipe.STLRecipe.install_stl_lib`,
calls the method :meth:`~pythonforandroid.recipe.Recipe.install_libs`
with the proper arguments: a subclass of
:class:`~pythonforandroid.archs.Arch` and our stl lib
(:attr:`~pythonforandroid.recipe.STLRecipe.stl_lib_name`)
"""
mock_isfile.return_value = False
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('icu', self.ctx)
recipe.ctx = self.ctx
assert recipe.need_stl_shared, True
recipe.install_stl_lib(arch)
mock_install_lib.assert_called_once_with(
arch,
'{ndk_dir}/sources/cxx-stl/llvm-libc++/'
'libs/{arch}/lib{stl_lib}.so'.format(
ndk_dir=self.ctx.ndk_dir,
arch=arch.arch,
stl_lib=recipe.stl_lib_name,
),
)
mock_ensure_dir.assert_called()
@mock.patch('pythonforandroid.recipe.Recipe.install_stl_lib')
def test_postarch_build(self, mock_install_stl_lib):
arch = ArchAarch_64(self.ctx)
recipe = Recipe.get_recipe('icu', self.ctx)
assert recipe.need_stl_shared, True
recipe.postbuild_arch(arch)
mock_install_stl_lib.assert_called_once_with(arch)
|
[] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
python
| 1 | 0 | |
003-firehose-record-converter/lambdas/data-sourcer/index.py
|
import base64
import json
import logging
import time
import urllib.request as requests
import os
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
output = []
source_api_endpoint = 'https://data.melbourne.vic.gov.au/resource/d6mv-s43h.json'
firehose_client = boto3.client('firehose')
def get_pedestrian_data(count):
try:
#Get the data from the API
request_obj = requests.Request(source_api_endpoint)
raw_response = requests.urlopen(request_obj).read()
pesdestrian_counts = json.loads(raw_response.decode('utf-8'))
except:
#Handle exception with a retry. Fail on second retry (failure is just a cloudwatch error)
if count == 0:
logger.warning('Failed to retrieve pedestrian data. Retrying in 3 seconds...')
time.sleep(3)
get_pedestrian_data(1)
else:
logger.error('Failed to retrieve pedestrian data. Not retrying.')
return pesdestrian_counts
def chunk_up_sensor_counts(sensor_counts, chunk_size):
number_of_sensor_counts = len(sensor_counts)
chunks = []
if number_of_sensor_counts > chunk_size:
chunk_start = 0
chunk_end = chunk_size
while number_of_sensor_counts >= chunk_size:
logger.debug('Getting records %d to %d',chunk_start, chunk_end)
chunks.append(sensor_counts[chunk_start:chunk_end])
chunk_start += chunk_size
chunk_end += chunk_size
number_of_sensor_counts -= chunk_size
else:
chunks.append(sensor_counts)
return chunks
def send_to_firehose(chunks, firehose_name):
for chunk in chunks:
chunk_records = []
for record in chunk:
delimited_record = json.dumps(record) + '\n'
chunk_records.append({'Data': delimited_record.encode('utf-8')})
firehose_response = firehose_client.put_record_batch(
DeliveryStreamName=firehose_name,
Records=chunk_records
)
logger.info(firehose_response)
def lambda_handler(event, context):
firehose_name = os.environ['FirehoseName']
# Call API to get data
logger.debug('Calling the %s endpoint',source_api_endpoint)
sensor_counts = get_pedestrian_data(0)
#Chunk up the sensor counts into batches of 500 records
chunks = chunk_up_sensor_counts(sensor_counts, 500)
#Send each batch to firehose
send_to_firehose(chunks, firehose_name)
return
|
[] |
[] |
[
"FirehoseName"
] |
[]
|
["FirehoseName"]
|
python
| 1 | 0 | |
main.go
|
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"time"
"go.opencensus.io/stats/view"
"github.com/application-research/estuary/build"
"github.com/application-research/estuary/config"
drpc "github.com/application-research/estuary/drpc"
"github.com/application-research/estuary/metrics"
"github.com/application-research/estuary/node"
"github.com/application-research/estuary/pinner"
"github.com/application-research/estuary/stagingbs"
"github.com/application-research/estuary/util"
"github.com/application-research/estuary/util/gateway"
"github.com/application-research/filclient"
"github.com/google/uuid"
"github.com/ipfs/go-cid"
gsimpl "github.com/ipfs/go-graphsync/impl"
logging "github.com/ipfs/go-log/v2"
routed "github.com/libp2p/go-libp2p/p2p/host/routed"
"github.com/mitchellh/go-homedir"
"github.com/whyrusleeping/memo"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"golang.org/x/xerrors"
datatransfer "github.com/filecoin-project/go-data-transfer"
"github.com/filecoin-project/lotus/api"
lcli "github.com/filecoin-project/lotus/cli"
cli "github.com/urfave/cli/v2"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func init() {
if os.Getenv("FULLNODE_API_INFO") == "" {
os.Setenv("FULLNODE_API_INFO", "wss://api.chain.love")
}
}
var log = logging.Logger("estuary")
type storageMiner struct {
gorm.Model
Address util.DbAddr `gorm:"unique"`
Suspended bool
SuspendedReason string
Name string
Version string
Location string
Owner uint
}
type Content struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Cid util.DbCID `json:"cid"`
Name string `json:"name"`
UserID uint `json:"userId" gorm:"index"`
Description string `json:"description"`
Size int64 `json:"size"`
Type util.ContentType `json:"type"`
Active bool `json:"active"`
Offloaded bool `json:"offloaded"`
Replication int `json:"replication"`
// TODO: shift most of the 'state' booleans in here into a single state
// field, should make reasoning about things much simpler
AggregatedIn uint `json:"aggregatedIn" gorm:"index:,option:CONCURRENTLY"`
Aggregate bool `json:"aggregate"`
Pinning bool `json:"pinning"`
PinMeta string `json:"pinMeta"`
Failed bool `json:"failed"`
Location string `json:"location"`
// TODO: shift location tracking to just use the ID of the shuttle
// Also move towards recording content movement intentions in the database,
// making that process more resilient to failures
// LocID uint `json:"locID"`
// LocIntent uint `json:"locIntent"`
// If set, this content is part of a split dag.
// In such a case, the 'root' content should be advertised on the dht, but
// not have deals made for it, and the children should have deals made for
// them (unlike with aggregates)
DagSplit bool `json:"dagSplit"`
SplitFrom uint `json:"splitFrom"`
}
type Object struct {
ID uint `gorm:"primarykey"`
Cid util.DbCID `gorm:"index"`
Size int
Reads int
LastAccess time.Time
}
type ObjRef struct {
ID uint `gorm:"primarykey"`
Content uint `gorm:"index:,option:CONCURRENTLY"`
Object uint `gorm:"index:,option:CONCURRENTLY"`
Offloaded uint
}
// updateAutoretrieveIndex ticks every tickInterval and checks for new information to add to autoretrieve
// If so, it updates the filecoin index with the new CIDs, saying they are present on autoretrieve
// With that, clients using bitswap can query autoretrieve servers using bitswap and get data from estuary
func (s *Server) updateAutoretrieveIndex(tickInterval time.Duration, quit chan struct{}) error {
var autoretrieves []Autoretrieve
var lastTickTime time.Time
ticker := time.NewTicker(tickInterval)
defer ticker.Stop()
for {
lastTickTime = time.Now().UTC().Add(-tickInterval)
// Find all autoretrieve servers that are online (that sent heartbeat)
err := s.DB.Find(&autoretrieves, "last_connection > ?", lastTickTime).Error
if err != nil {
log.Errorf("unable to query autoretrieve servers from database: %s", err)
return err
}
if len(autoretrieves) > 0 {
for _, ar := range autoretrieves {
fmt.Println("online: ", ar) // TODO: remove
}
} else {
log.Info("no autoretrieve servers online")
}
// wait for next tick, or quit
select {
case <-ticker.C:
continue
case <-quit:
break
}
}
}
func overrideSetOptions(flags []cli.Flag, cctx *cli.Context, cfg *config.Estuary) error {
var err error
for _, flag := range flags {
name := flag.Names()[0]
if cctx.IsSet(name) {
log.Debugf("Flag %s is set to %s", name, cctx.String(name))
} else {
continue
}
switch name {
case "datadir":
cfg.SetDataDir(cctx.String("datadir"))
case "blockstore":
cfg.NodeConfig.BlockstoreDir, err = config.MakeAbsolute(cfg.DataDir, cctx.String("blockstore"))
case "write-log-truncate":
cfg.NodeConfig.WriteLogTruncate = cctx.Bool("write-log-truncate")
case "write-log":
cfg.NodeConfig.WriteLogDir, err = config.MakeAbsolute(cfg.DataDir, cctx.String("write-log"))
case "database":
cfg.DatabaseConnString = cctx.String("database")
case "apilisten":
cfg.ApiListen = cctx.String("apilisten")
case "lightstep-token":
cfg.LightstepToken = cctx.String("lightstep-token")
case "hostname":
cfg.Hostname = cctx.String("hostname")
case "default-replication":
cfg.Replication = cctx.Int("default-replication")
case "lowmem":
cfg.LowMem = cctx.Bool("lowmem")
case "no-storage-cron":
cfg.DisableFilecoinStorage = cctx.Bool("no-storage-cron")
case "disable-deal-making":
cfg.DealConfig.Disable = cctx.Bool("disable-deal-making")
case "fail-deals-on-transfer-failure":
cfg.DealConfig.FailOnTransferFailure = cctx.Bool("fail-deals-on-transfer-failure")
case "disable-local-content-adding":
cfg.ContentConfig.DisableLocalAdding = cctx.Bool("disable-local-content-adding")
case "disable-content-adding":
cfg.ContentConfig.DisableGlobalAdding = cctx.Bool("disable-content-adding")
case "jaeger-tracing":
cfg.JaegerConfig.EnableTracing = cctx.Bool("jaeger-tracing")
case "jaeger-provider-url":
cfg.JaegerConfig.ProviderUrl = cctx.String("jaeger-provider-url")
case "jaeger-sampler-ratio":
cfg.JaegerConfig.SamplerRatio = cctx.Float64("jaeger-sampler-ratio")
case "logging":
cfg.LoggingConfig.ApiEndpointLogging = cctx.Bool("logging")
default:
// Do nothing
}
if (err) != nil {
return err
}
}
return err
}
func main() {
logging.SetLogLevel("dt-impl", "debug")
logging.SetLogLevel("estuary", "debug")
logging.SetLogLevel("paych", "debug")
logging.SetLogLevel("filclient", "debug")
logging.SetLogLevel("dt_graphsync", "debug")
//logging.SetLogLevel("graphsync_allocator", "debug")
logging.SetLogLevel("dt-chanmon", "debug")
logging.SetLogLevel("markets", "debug")
logging.SetLogLevel("data_transfer_network", "debug")
logging.SetLogLevel("rpc", "info")
logging.SetLogLevel("bs-wal", "info")
logging.SetLogLevel("provider.batched", "info")
logging.SetLogLevel("bs-migrate", "info")
app := cli.NewApp()
home, _ := homedir.Dir()
cfg := config.NewEstuary()
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "repo",
Value: "~/.lotus",
},
&cli.StringFlag{
Name: "config",
Value: filepath.Join(home, ".estuary"),
Usage: "specify configuration file location",
},
&cli.StringFlag{
Name: "database",
Usage: "specify connection string for estuary database",
Value: cfg.DatabaseConnString,
EnvVars: []string{"ESTUARY_DATABASE"},
},
&cli.StringFlag{
Name: "apilisten",
Usage: "address for the api server to listen on",
Value: cfg.ApiListen,
EnvVars: []string{"ESTUARY_API_LISTEN"},
},
&cli.StringFlag{
Name: "datadir",
Usage: "directory to store data in",
Value: cfg.DataDir,
EnvVars: []string{"ESTUARY_DATADIR"},
},
&cli.StringFlag{
Name: "write-log",
Usage: "enable write log blockstore in specified directory",
Value: cfg.NodeConfig.WriteLogDir,
Hidden: true,
},
&cli.BoolFlag{
Name: "no-storage-cron",
Usage: "run estuary without processing files into deals",
Value: cfg.DisableFilecoinStorage,
},
&cli.BoolFlag{
Name: "logging",
Usage: "enable api endpoint logging",
Value: cfg.LoggingConfig.ApiEndpointLogging,
},
&cli.BoolFlag{
Name: "enable-auto-retrieve",
Hidden: true,
Value: cfg.AutoRetrieve,
},
&cli.StringFlag{
Name: "lightstep-token",
Usage: "specify lightstep access token for enabling trace exports",
EnvVars: []string{"ESTUARY_LIGHTSTEP_TOKEN"},
Value: cfg.LightstepToken,
},
&cli.StringFlag{
Name: "hostname",
Usage: "specify hostname this node will be reachable at",
Value: cfg.Hostname,
},
&cli.BoolFlag{
Name: "fail-deals-on-transfer-failure",
Usage: "consider deals failed when the transfer to the miner fails",
Value: cfg.DealConfig.FailOnTransferFailure,
},
&cli.BoolFlag{
Name: "disable-deal-making",
Usage: "do not create any new deals (existing deals will still be processed)",
Value: cfg.DealConfig.Disable,
},
&cli.BoolFlag{
Name: "disable-content-adding",
Usage: "disallow new content ingestion globally",
Value: cfg.ContentConfig.DisableGlobalAdding,
},
&cli.BoolFlag{
Name: "disable-local-content-adding",
Usage: "disallow new content ingestion on this node (shuttles are unaffected)",
Value: cfg.ContentConfig.DisableLocalAdding,
},
&cli.StringFlag{
Name: "blockstore",
Usage: "specify blockstore parameters",
Value: cfg.NodeConfig.BlockstoreDir,
},
&cli.BoolFlag{
Name: "write-log-truncate",
Value: cfg.NodeConfig.WriteLogTruncate,
},
&cli.IntFlag{
Name: "default-replication",
Value: cfg.Replication,
},
&cli.BoolFlag{
Name: "lowmem",
Usage: "TEMP: turns down certain parameters to attempt to use less memory (will be replaced by a more specific flag later)",
Value: cfg.LowMem,
},
&cli.BoolFlag{
Name: "jaeger-tracing",
Value: cfg.JaegerConfig.EnableTracing,
},
&cli.StringFlag{
Name: "jaeger-provider-url",
Value: cfg.JaegerConfig.ProviderUrl,
},
&cli.Float64Flag{
Name: "jaeger-sampler-ratio",
Usage: "If less than 1 probabilistic metrics will be used.",
Value: cfg.JaegerConfig.SamplerRatio,
},
}
app.Commands = []*cli.Command{
{
Name: "setup",
Usage: "Creates an initial auth token under new user \"admin\"",
Action: func(cctx *cli.Context) error {
cfg.Load(cctx.String("config"))
overrideSetOptions(app.Flags, cctx, cfg)
db, err := setupDatabase(cfg)
if err != nil {
return err
}
quietdb := db.Session(&gorm.Session{
Logger: logger.Discard,
})
username := "admin"
passHash := ""
if err := quietdb.First(&User{}, "username = ?", username).Error; err == nil {
return fmt.Errorf("an admin user already exists")
}
newUser := &User{
UUID: uuid.New().String(),
Username: username,
PassHash: passHash,
Perm: 100,
}
if err := db.Create(newUser).Error; err != nil {
return fmt.Errorf("admin user creation failed: %w", err)
}
authToken := &AuthToken{
Token: "EST" + uuid.New().String() + "ARY",
User: newUser.ID,
Expiry: time.Now().Add(time.Hour * 24 * 365),
}
if err := db.Create(authToken).Error; err != nil {
return fmt.Errorf("admin token creation failed: %w", err)
}
fmt.Printf("Auth Token: %v\n", authToken.Token)
return nil
},
}, {
Name: "configure",
Usage: "Saves a configuration file to the location specified by the config parameter",
Action: func(cctx *cli.Context) error {
configuration := cctx.String("config")
cfg.Load(configuration) // Assume error means no configuration file exists
log.Info("test")
overrideSetOptions(app.Flags, cctx, cfg)
return cfg.Save(configuration)
},
},
}
app.Action = func(cctx *cli.Context) error {
cfg.Load(cctx.String("config")) // Ignore error for now; eventually error out if no configuration file
overrideSetOptions(app.Flags, cctx, cfg)
db, err := setupDatabase(cfg)
if err != nil {
return err
}
init := Initializer{&cfg.NodeConfig, db, nil}
nd, err := node.Setup(context.Background(), &init)
if err != nil {
return err
}
if err = view.Register(
metrics.DefaultViews...,
); err != nil {
log.Fatalf("Cannot register the OpenCensus view: %v", err)
return err
}
addr, err := nd.Wallet.GetDefault()
if err != nil {
return err
}
sbmgr, err := stagingbs.NewStagingBSMgr(cfg.StagingDataDir)
if err != nil {
return err
}
api, closer, err := lcli.GetGatewayAPI(cctx)
// api, closer, err := lcli.GetFullNodeAPI(cctx)
if err != nil {
return err
}
defer closer()
// setup tracing to jaeger if enabled
if cfg.JaegerConfig.EnableTracing {
tp, err := metrics.NewJaegerTraceProvider("estuary",
cfg.JaegerConfig.ProviderUrl, cfg.JaegerConfig.SamplerRatio)
if err != nil {
return err
}
otel.SetTracerProvider(tp)
}
s := &Server{
Node: nd,
Api: api,
StagingMgr: sbmgr,
tracer: otel.Tracer("api"),
cacher: memo.NewCacher(),
gwayHandler: gateway.NewGatewayHandler(nd.Blockstore),
}
// TODO: this is an ugly self referential hack... should fix
pinmgr := pinner.NewPinManager(s.doPinning, nil, &pinner.PinManagerOpts{
MaxActivePerUser: 20,
})
go pinmgr.Run(50)
rhost := routed.Wrap(nd.Host, nd.FilDht)
var opts []func(*filclient.Config)
if cfg.LowMem {
opts = append(opts, func(cfg *filclient.Config) {
cfg.GraphsyncOpts = []gsimpl.Option{
gsimpl.MaxInProgressIncomingRequests(100),
gsimpl.MaxInProgressOutgoingRequests(100),
gsimpl.MaxMemoryResponder(4 << 30),
gsimpl.MaxMemoryPerPeerResponder(16 << 20),
gsimpl.MaxInProgressIncomingRequestsPerPeer(10),
gsimpl.MessageSendRetries(2),
gsimpl.SendMessageTimeout(2 * time.Minute),
}
})
}
fc, err := filclient.NewClient(rhost, api, nd.Wallet, addr, nd.Blockstore, nd.Datastore, cfg.DataDir)
if err != nil {
return err
}
s.FilClient = fc
for _, a := range nd.Host.Addrs() {
fmt.Printf("%s/p2p/%s\n", a, nd.Host.ID())
}
go func() {
for _, ai := range node.BootstrapPeers {
if err := nd.Host.Connect(context.TODO(), ai); err != nil {
fmt.Println("failed to connect to bootstrapper: ", err)
continue
}
}
if err := nd.Dht.Bootstrap(context.TODO()); err != nil {
fmt.Println("dht bootstrapping failed: ", err)
}
}()
s.DB = db
cm, err := NewContentManager(db, api, fc, init.trackingBstore, s.Node.NotifBlockstore, nd.Provider, pinmgr, nd, cfg.Hostname)
if err != nil {
return err
}
fc.SetPieceCommFunc(cm.getPieceCommitment)
cm.FailDealOnTransferFailure = cfg.DealConfig.FailOnTransferFailure
cm.isDealMakingDisabled = cfg.DealConfig.Disable
cm.contentAddingDisabled = cfg.ContentConfig.DisableGlobalAdding
cm.localContentAddingDisabled = cfg.ContentConfig.DisableLocalAdding
cm.tracer = otel.Tracer("replicator")
if cctx.Bool("enable-auto-retrive") {
init.trackingBstore.SetCidReqFunc(cm.RefreshContentForCid)
}
if !cfg.DisableFilecoinStorage {
go cm.ContentWatcher()
}
s.CM = cm
if !cm.contentAddingDisabled {
go func() {
// wait for shuttles to reconnect
// This is a bit of a hack, and theres probably a better way to
// solve this. but its good enough for now
time.Sleep(time.Second * 10)
if err := cm.refreshPinQueue(); err != nil {
log.Errorf("failed to refresh pin queue: %s", err)
}
}()
}
// start autoretrieve index updater task every INDEX_UPDATE_INTERVAL minutes
updateInterval, ok := os.LookupEnv("INDEX_UPDATE_INTERVAL")
if !ok {
updateInterval = "720"
}
intervalMinutes, err := strconv.Atoi(updateInterval)
if err != nil {
return err
}
stopUpdateIndex := make(chan struct{})
go s.updateAutoretrieveIndex(time.Duration(intervalMinutes)*time.Minute, stopUpdateIndex)
go func() {
time.Sleep(time.Second * 10)
if err := s.RestartAllTransfersForLocation(context.TODO(), "local"); err != nil {
log.Errorf("failed to restart transfers: %s", err)
}
}()
return s.ServeAPI(cfg.ApiListen, cfg.LoggingConfig.ApiEndpointLogging, cfg.LightstepToken, filepath.Join(cfg.DataDir, "cache"))
}
if err := app.Run(os.Args); err != nil {
fmt.Println(err)
}
}
type Autoretrieve struct {
gorm.Model
Handle string `gorm:"unique"`
Token string `gorm:"unique"`
LastConnection time.Time
PeerID string `gorm:"unique"`
Addresses string
}
func setupDatabase(cfg *config.Estuary) (*gorm.DB, error) {
/* TODO: change this default
ddir := cctx.String("datadir")
if dbval == defaultDatabaseValue && ddir != "." {
dbval = "sqlite=" + filepath.Join(ddir, "estuary.db")
}
*/
db, err := util.SetupDatabase(cfg.DatabaseConnString)
if err != nil {
return nil, err
}
db.AutoMigrate(&Content{})
db.AutoMigrate(&Object{})
db.AutoMigrate(&ObjRef{})
db.AutoMigrate(&Collection{})
db.AutoMigrate(&CollectionRef{})
db.AutoMigrate(&contentDeal{})
db.AutoMigrate(&dfeRecord{})
db.AutoMigrate(&PieceCommRecord{})
db.AutoMigrate(&proposalRecord{})
db.AutoMigrate(&util.RetrievalFailureRecord{})
db.AutoMigrate(&retrievalSuccessRecord{})
db.AutoMigrate(&minerStorageAsk{})
db.AutoMigrate(&storageMiner{})
db.AutoMigrate(&User{})
db.AutoMigrate(&AuthToken{})
db.AutoMigrate(&InviteCode{})
db.AutoMigrate(&Shuttle{})
db.AutoMigrate(&Autoretrieve{})
// 'manually' add unique composite index on collection fields because gorms syntax for it is tricky
if err := db.Exec("create unique index if not exists collection_refs_paths on collection_refs (path,collection)").Error; err != nil {
return nil, fmt.Errorf("failed to create collection paths index: %w", err)
}
var count int64
if err := db.Model(&storageMiner{}).Count(&count).Error; err != nil {
return nil, err
}
if count == 0 {
fmt.Println("adding default miner list to database...")
for _, m := range build.DefaultMiners {
db.Create(&storageMiner{Address: util.DbAddr{m}})
}
}
return db, nil
}
type Server struct {
tracer trace.Tracer
Node *node.Node
DB *gorm.DB
FilClient *filclient.FilClient
Api api.Gateway
CM *ContentManager
StagingMgr *stagingbs.StagingBSMgr
gwayHandler *gateway.GatewayHandler
cacher *memo.Cacher
}
func (s *Server) GarbageCollect(ctx context.Context) error {
// since we're reference counting all the content, garbage collection becomes easy
// its even easier if we don't care that its 'perfect'
// We can probably even just remove stuff when its references are removed from the database
keych, err := s.Node.Blockstore.AllKeysChan(ctx)
if err != nil {
return err
}
for c := range keych {
keep, err := s.trackingObject(c)
if err != nil {
return err
}
if !keep {
// can batch these deletes and execute them at the datastore layer for more perfs
if err := s.Node.Blockstore.DeleteBlock(ctx, c); err != nil {
return err
}
}
}
return nil
}
func (s *Server) trackingObject(c cid.Cid) (bool, error) {
var count int64
if err := s.DB.Model(&Object{}).Where("cid = ?", c.Bytes()).Count(&count).Error; err != nil {
if xerrors.Is(err, gorm.ErrRecordNotFound) {
return false, nil
}
return false, err
}
return count > 0, nil
}
func jsondump(o interface{}) {
data, _ := json.MarshalIndent(o, "", " ")
fmt.Println(string(data))
}
func (s *Server) RestartAllTransfersForLocation(ctx context.Context, loc string) error {
var deals []contentDeal
if err := s.DB.Model(contentDeal{}).
Joins("left join contents on contents.id = content_deals.content").
Where("not content_deals.failed and content_deals.deal_id = 0 and content_deals.dt_chan != '' and location = ?", loc).
Scan(&deals).Error; err != nil {
return err
}
for _, d := range deals {
chid, err := d.ChannelID()
if err != nil {
log.Errorf("failed to get channel id from deal %d: %s", d.ID, err)
continue
}
if err := s.CM.RestartTransfer(ctx, loc, chid); err != nil {
log.Errorf("failed to restart transfer: %s", err)
continue
}
}
return nil
}
func (cm *ContentManager) RestartTransfer(ctx context.Context, loc string, chanid datatransfer.ChannelID) error {
if loc == "local" {
st, err := cm.FilClient.TransferStatus(ctx, &chanid)
if err != nil {
return err
}
if util.TransferTerminated(st) {
return fmt.Errorf("deal in database as being in progress, but data transfer is terminated: %d", st.Status)
}
return cm.FilClient.RestartTransfer(ctx, &chanid)
}
return cm.sendRestartTransferCmd(ctx, loc, chanid)
}
func (cm *ContentManager) sendRestartTransferCmd(ctx context.Context, loc string, chanid datatransfer.ChannelID) error {
return cm.sendShuttleCommand(ctx, loc, &drpc.Command{
Op: drpc.CMD_RestartTransfer,
Params: drpc.CmdParams{
RestartTransfer: &drpc.RestartTransfer{
ChanID: chanid,
},
},
})
}
|
[
"\"FULLNODE_API_INFO\""
] |
[] |
[
"FULLNODE_API_INFO"
] |
[]
|
["FULLNODE_API_INFO"]
|
go
| 1 | 0 | |
azuredevops/internal/client/client.go
|
package client
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/httpclient"
"github.com/microsoft/azure-devops-go-api/azuredevops"
"github.com/microsoft/azure-devops-go-api/azuredevops/build"
"github.com/microsoft/azure-devops-go-api/azuredevops/core"
"github.com/microsoft/azure-devops-go-api/azuredevops/featuremanagement"
"github.com/microsoft/azure-devops-go-api/azuredevops/git"
"github.com/microsoft/azure-devops-go-api/azuredevops/graph"
"github.com/microsoft/azure-devops-go-api/azuredevops/memberentitlementmanagement"
"github.com/microsoft/azure-devops-go-api/azuredevops/operations"
"github.com/microsoft/azure-devops-go-api/azuredevops/policy"
"github.com/microsoft/azure-devops-go-api/azuredevops/serviceendpoint"
"github.com/microsoft/azure-devops-go-api/azuredevops/taskagent"
"github.com/microsoft/terraform-provider-azuredevops/version"
)
// AggregatedClient aggregates all of the underlying clients into a single data
// type. Each client is ready to use and fully configured with the correct
// AzDO PAT/organization
//
// AggregatedClient uses interfaces derived from the underlying client structs to
// allow for mocking to support unit testing of the funcs that invoke the
// Azure DevOps client.
type AggregatedClient struct {
OrganizationURL string
CoreClient core.Client
BuildClient build.Client
GitReposClient git.Client
GraphClient graph.Client
OperationsClient operations.Client
PolicyClient policy.Client
ServiceEndpointClient serviceendpoint.Client
TaskAgentClient taskagent.Client
MemberEntitleManagementClient memberentitlementmanagement.Client
FeatureManagementClient featuremanagement.Client
Ctx context.Context
}
// GetAzdoClient builds and provides a connection to the Azure DevOps API
func GetAzdoClient(azdoPAT string, organizationURL string, tfVersion string) (*AggregatedClient, error) {
ctx := context.Background()
if strings.EqualFold(azdoPAT, "") {
return nil, fmt.Errorf("the personal access token is required")
}
if strings.EqualFold(organizationURL, "") {
return nil, fmt.Errorf("the url of the Azure DevOps is required")
}
connection := azuredevops.NewPatConnection(organizationURL, azdoPAT)
setUserAgent(connection, tfVersion)
// client for these APIs (includes CRUD for AzDO projects...):
// https://docs.microsoft.com/en-us/rest/api/azure/devops/core/?view=azure-devops-rest-5.1
coreClient, err := core.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): core.NewClient failed.")
return nil, err
}
// client for these APIs (includes CRUD for AzDO build pipelines...):
// https://docs.microsoft.com/en-us/rest/api/azure/devops/build/?view=azure-devops-rest-5.1
buildClient, err := build.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): build.NewClient failed.")
return nil, err
}
// client for these APIs (monitor async operations...):
// https://docs.microsoft.com/en-us/rest/api/azure/devops/operations/operations?view=azure-devops-rest-5.1
operationsClient := operations.NewClient(ctx, connection)
// client for these APIs (includes CRUD for AzDO service endpoints a.k.a. service connections...):
// https://docs.microsoft.com/en-us/rest/api/azure/devops/serviceendpoint/endpoints?view=azure-devops-rest-5.1
serviceEndpointClient, err := serviceendpoint.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): serviceendpoint.NewClient failed.")
return nil, err
}
// client for these APIs (includes CRUD for AzDO variable groups):
taskagentClient, err := taskagent.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): taskagent.NewClient failed.")
return nil, err
}
// client for these APIs:
// https://docs.microsoft.com/en-us/rest/api/azure/devops/git/?view=azure-devops-rest-5.1
gitReposClient, err := git.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): git.NewClient failed.")
return nil, err
}
// https://docs.microsoft.com/en-us/rest/api/azure/devops/graph/?view=azure-devops-rest-5.1
graphClient, err := graph.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): graph.NewClient failed.")
return nil, err
}
memberentitlementmanagementClient, err := memberentitlementmanagement.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): memberentitlementmanagement.NewClient failed.")
return nil, err
}
// https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create?view=azure-devops-rest-5.1
policyClient, err := policy.NewClient(ctx, connection)
if err != nil {
log.Printf("getAzdoClient(): policy.NewClient failed.")
return nil, err
}
featuremanagement := featuremanagement.NewClient(ctx, connection)
aggregatedClient := &AggregatedClient{
OrganizationURL: organizationURL,
CoreClient: coreClient,
BuildClient: buildClient,
GitReposClient: gitReposClient,
GraphClient: graphClient,
OperationsClient: operationsClient,
PolicyClient: policyClient,
ServiceEndpointClient: serviceEndpointClient,
TaskAgentClient: taskagentClient,
MemberEntitleManagementClient: memberentitlementmanagementClient,
FeatureManagementClient: featuremanagement,
Ctx: ctx,
}
log.Printf("getAzdoClient(): Created core, build, operations, and serviceendpoint clients successfully!")
return aggregatedClient, nil
}
// setUserAgent set UserAgent for http headers
func setUserAgent(connection *azuredevops.Connection, tfVersion string) {
tfUserAgent := httpclient.TerraformUserAgent(tfVersion)
providerUserAgent := fmt.Sprintf("%s terraform-provider-azuredevops/%s", tfUserAgent, version.ProviderVersion)
connection.UserAgent = strings.TrimSpace(fmt.Sprintf("%s %s", connection.UserAgent, providerUserAgent))
// append the CloudShell version to the user agent if it exists
if azureAgent := os.Getenv("AZURE_HTTP_USER_AGENT"); azureAgent != "" {
connection.UserAgent = fmt.Sprintf("%s %s", connection.UserAgent, azureAgent)
}
log.Printf("[DEBUG] AzureRM Client User Agent: %s\n", connection.UserAgent)
}
|
[
"\"AZURE_HTTP_USER_AGENT\""
] |
[] |
[
"AZURE_HTTP_USER_AGENT"
] |
[]
|
["AZURE_HTTP_USER_AGENT"]
|
go
| 1 | 0 | |
papyrus/asgi.py
|
"""
ASGI config for papyrus 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', 'papyrus.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
atelier_de_soi_app/asgi.py
|
"""
ASGI config for atelier_de_soi project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'atelier_de_soi.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
go-apps/meep-loc-serv/server/loc-serv.go
|
/*
* Copyright (c) 2019 InterDigital Communications, 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 server
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
sbi "github.com/InterDigitalInc/AdvantEDGE/go-apps/meep-loc-serv/sbi"
dkm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-key-mgr"
httpLog "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-http-logger"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
redis "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-redis"
sm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-sessions"
"github.com/gorilla/mux"
)
const moduleName = "meep-loc-serv"
const LocServBasePath = "/location/v2/"
const locServKey string = "loc-serv:"
const logModuleLocServ string = "meep-loc-serv"
const typeZone = "zone"
const typeAccessPoint = "accessPoint"
const typeUser = "user"
const typeZonalSubscription = "zonalsubs"
const typeUserSubscription = "usersubs"
const typeZoneStatusSubscription = "zonestatus"
type UeUserData struct {
queryZoneId []string
queryApId []string
queryAddress []string
userList *UserList
}
type ApUserData struct {
queryInterestRealm string
apList *AccessPointList
}
var nextZonalSubscriptionIdAvailable int
var nextUserSubscriptionIdAvailable int
var nextZoneStatusSubscriptionIdAvailable int
var zonalSubscriptionEnteringMap = map[int]string{}
var zonalSubscriptionLeavingMap = map[int]string{}
var zonalSubscriptionTransferringMap = map[int]string{}
var zonalSubscriptionMap = map[int]string{}
var userSubscriptionEnteringMap = map[int]string{}
var userSubscriptionLeavingMap = map[int]string{}
var userSubscriptionTransferringMap = map[int]string{}
var userSubscriptionMap = map[int]string{}
var zoneStatusSubscriptionMap = map[int]*ZoneStatusCheck{}
type ZoneStatusCheck struct {
ZoneId string
Serviceable bool
Unserviceable bool
Unknown bool
NbUsersInZoneThreshold int32
NbUsersInAPThreshold int32
}
var LOC_SERV_DB = 0
var currentStoreName = ""
var redisAddr string = "meep-redis-master.default.svc.cluster.local:6379"
var influxAddr string = "http://meep-influxdb.default.svc.cluster.local:8086"
var rc *redis.Connector
var hostUrl *url.URL
var sandboxName string
var basePath string
var baseKey string
var sessionMgr *sm.SessionMgr
var mutex sync.Mutex
func notImplemented(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotImplemented)
}
// Init - Location Service initialization
func Init() (err error) {
sandboxNameEnv := strings.TrimSpace(os.Getenv("MEEP_SANDBOX_NAME"))
if sandboxNameEnv != "" {
sandboxName = sandboxNameEnv
}
if sandboxName == "" {
err = errors.New("MEEP_SANDBOX_NAME env variable not set")
log.Error(err.Error())
return err
}
log.Info("MEEP_SANDBOX_NAME: ", sandboxName)
// hostUrl is the url of the node serving the resourceURL
// Retrieve public url address where service is reachable, if not present, use Host URL environment variable
hostUrl, err = url.Parse(strings.TrimSpace(os.Getenv("MEEP_PUBLIC_URL")))
if err != nil || hostUrl == nil || hostUrl.String() == "" {
hostUrl, err = url.Parse(strings.TrimSpace(os.Getenv("MEEP_HOST_URL")))
if err != nil {
hostUrl = new(url.URL)
}
}
log.Info("resource URL: ", hostUrl)
// Set base path
basePath = "/" + sandboxName + LocServBasePath
// Get base storage key
baseKey = dkm.GetKeyRoot(sandboxName) + locServKey
// Connect to Redis DB
rc, err = redis.NewConnector(redisAddr, LOC_SERV_DB)
if err != nil {
log.Error("Failed connection to Redis DB. Error: ", err)
return err
}
_ = rc.DBFlush(baseKey)
log.Info("Connected to Redis DB, location service table")
// Connect to Session Manager
sessionMgr, err = sm.NewSessionMgr(moduleName, sandboxName, redisAddr, redisAddr)
if err != nil {
log.Error("Failed connection to Session Manager: ", err.Error())
return err
}
log.Info("Connected to Session Manager")
userTrackingReInit()
zonalTrafficReInit()
zoneStatusReInit()
// Initialize SBI
sbiCfg := sbi.SbiCfg{
SandboxName: sandboxName,
RedisAddr: redisAddr,
UserInfoCb: updateUserInfo,
ZoneInfoCb: updateZoneInfo,
ApInfoCb: updateAccessPointInfo,
ScenarioNameCb: updateStoreName,
CleanUpCb: cleanUp,
}
err = sbi.Init(sbiCfg)
if err != nil {
log.Error("Failed initialize SBI. Error: ", err)
return err
}
log.Info("SBI Initialized")
return nil
}
// Run - Start Location Service
func Run() (err error) {
return sbi.Run()
}
// Stop - Stop RNIS
func Stop() (err error) {
return sbi.Stop()
}
func deregisterZoneStatus(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
zoneStatusSubscriptionMap[subsId] = nil
}
func registerZoneStatus(zoneId string, nbOfUsersZoneThreshold int32, nbOfUsersAPThreshold int32, opStatus []OperationStatus, subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
var zoneStatus ZoneStatusCheck
if opStatus != nil {
for i := 0; i < len(opStatus); i++ {
switch opStatus[i] {
case SERVICEABLE:
zoneStatus.Serviceable = true
case UNSERVICEABLE:
zoneStatus.Unserviceable = true
case OPSTATUS_UNKNOWN:
zoneStatus.Unknown = true
default:
}
}
}
zoneStatus.NbUsersInZoneThreshold = nbOfUsersZoneThreshold
zoneStatus.NbUsersInAPThreshold = nbOfUsersAPThreshold
zoneStatus.ZoneId = zoneId
mutex.Lock()
defer mutex.Unlock()
zoneStatusSubscriptionMap[subsId] = &zoneStatus
}
func deregisterZonal(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
zonalSubscriptionMap[subsId] = ""
zonalSubscriptionEnteringMap[subsId] = ""
zonalSubscriptionLeavingMap[subsId] = ""
zonalSubscriptionTransferringMap[subsId] = ""
}
func registerZonal(zoneId string, event []UserEventType, subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
if event != nil {
for i := 0; i < len(event); i++ {
switch event[i] {
case ENTERING_EVENT:
zonalSubscriptionEnteringMap[subsId] = zoneId
case LEAVING_EVENT:
zonalSubscriptionLeavingMap[subsId] = zoneId
case TRANSFERRING_EVENT:
zonalSubscriptionTransferringMap[subsId] = zoneId
default:
}
}
} else {
zonalSubscriptionEnteringMap[subsId] = zoneId
zonalSubscriptionLeavingMap[subsId] = zoneId
zonalSubscriptionTransferringMap[subsId] = zoneId
}
zonalSubscriptionMap[subsId] = zoneId
}
func deregisterUser(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
userSubscriptionMap[subsId] = ""
userSubscriptionEnteringMap[subsId] = ""
userSubscriptionLeavingMap[subsId] = ""
userSubscriptionTransferringMap[subsId] = ""
}
func registerUser(userAddress string, event []UserEventType, subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
if event != nil {
for i := 0; i < len(event); i++ {
switch event[i] {
case ENTERING_EVENT:
userSubscriptionEnteringMap[subsId] = userAddress
case LEAVING_EVENT:
userSubscriptionLeavingMap[subsId] = userAddress
case TRANSFERRING_EVENT:
userSubscriptionTransferringMap[subsId] = userAddress
default:
}
}
} else {
userSubscriptionEnteringMap[subsId] = userAddress
userSubscriptionLeavingMap[subsId] = userAddress
userSubscriptionTransferringMap[subsId] = userAddress
}
userSubscriptionMap[subsId] = userAddress
}
func checkNotificationRegisteredZoneStatus(zoneId string, apId string, nbUsersInAP int32, nbUsersInZone int32, previousNbUsersInAP int32, previousNbUsersInZone int32) {
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, zoneStatus := range zoneStatusSubscriptionMap {
if zoneStatus == nil {
continue
}
if zoneStatus.ZoneId == zoneId {
zoneWarning := false
apWarning := false
if nbUsersInZone != -1 {
if previousNbUsersInZone != nbUsersInZone && nbUsersInZone >= zoneStatus.NbUsersInZoneThreshold {
zoneWarning = true
}
}
if nbUsersInAP != -1 {
if previousNbUsersInAP != nbUsersInAP && nbUsersInAP >= zoneStatus.NbUsersInAPThreshold {
apWarning = true
}
}
if zoneWarning || apWarning {
subsIdStr := strconv.Itoa(subsId)
jsonInfo, _ := rc.JSONGetEntry(baseKey+typeZoneStatusSubscription+":"+subsIdStr, ".")
if jsonInfo == "" {
return
}
subscription := convertJsonToZoneStatusSubscription(jsonInfo)
var zoneStatusNotif ZoneStatusNotification
zoneStatusNotif.ZoneId = zoneId
if apWarning {
zoneStatusNotif.AccessPointId = apId
zoneStatusNotif.NumberOfUsersInAP = nbUsersInAP
}
if zoneWarning {
zoneStatusNotif.NumberOfUsersInZone = nbUsersInZone
}
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
zoneStatusNotif.Timestamp = ×tamp
var inlineZoneStatusNotification InlineZoneStatusNotification
inlineZoneStatusNotification.ZoneStatusNotification = &zoneStatusNotif
sendStatusNotification(subscription.CallbackReference.NotifyURL, inlineZoneStatusNotification)
if apWarning {
log.Info("Zone Status Notification" + "(" + subsIdStr + "): " + "For event in zone " + zoneId + " which has " + strconv.Itoa(int(nbUsersInAP)) + " users in AP " + apId)
} else {
log.Info("Zone Status Notification" + "(" + subsIdStr + "): " + "For event in zone " + zoneId + " which has " + strconv.Itoa(int(nbUsersInZone)) + " users in total")
}
}
}
}
}
func checkNotificationRegisteredUsers(oldZoneId string, newZoneId string, oldApId string, newApId string, userId string) {
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, value := range userSubscriptionMap {
if value == userId {
subsIdStr := strconv.Itoa(subsId)
jsonInfo, _ := rc.JSONGetEntry(baseKey+typeUserSubscription+":"+subsIdStr, ".")
if jsonInfo == "" {
return
}
subscription := convertJsonToUserSubscription(jsonInfo)
var zonal ZonalPresenceNotification
zonal.Address = userId
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
zonal.Timestamp = ×tamp
zonal.CallbackData = subscription.ClientCorrelator
if newZoneId != oldZoneId {
//process LEAVING events prior to entering ones
if oldZoneId != "" {
if userSubscriptionLeavingMap[subsId] != "" {
zonal.ZoneId = oldZoneId
zonal.CurrentAccessPointId = oldApId
event := new(UserEventType)
*event = LEAVING_EVENT
zonal.UserEventType = event
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("User Notification" + "(" + subsIdStr + "): " + "Leaving event in zone " + oldZoneId + " for user " + userId)
}
}
if userSubscriptionEnteringMap[subsId] != "" && newZoneId != "" {
zonal.ZoneId = newZoneId
zonal.CurrentAccessPointId = newApId
event := new(UserEventType)
*event = ENTERING_EVENT
zonal.UserEventType = event
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("User Notification" + "(" + subsIdStr + "): " + "Entering event in zone " + newZoneId + " for user " + userId)
}
} else {
if newApId != oldApId {
if userSubscriptionTransferringMap[subsId] != "" {
zonal.ZoneId = newZoneId
zonal.CurrentAccessPointId = newApId
zonal.PreviousAccessPointId = oldApId
event := new(UserEventType)
*event = TRANSFERRING_EVENT
zonal.UserEventType = event
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("User Notification" + "(" + subsIdStr + "): " + " Transferring event within zone " + newZoneId + " for user " + userId + " from Ap " + oldApId + " to " + newApId)
}
}
}
}
}
}
func sendZonalPresenceNotification(notifyUrl string, notification InlineZonalPresenceNotification) {
startTime := time.Now()
jsonNotif, err := json.Marshal(notification)
if err != nil {
log.Error(err)
return
}
resp, err := http.Post(notifyUrl, "application/json", bytes.NewBuffer(jsonNotif))
_ = httpLog.LogTx(notifyUrl, "POST", string(jsonNotif), resp, startTime)
if err != nil {
log.Error(err)
return
}
defer resp.Body.Close()
}
func sendStatusNotification(notifyUrl string, notification InlineZoneStatusNotification) {
startTime := time.Now()
jsonNotif, err := json.Marshal(notification)
if err != nil {
log.Error(err)
return
}
resp, err := http.Post(notifyUrl, "application/json", bytes.NewBuffer(jsonNotif))
_ = httpLog.LogTx(notifyUrl, "POST", string(jsonNotif), resp, startTime)
if err != nil {
log.Error(err)
return
}
defer resp.Body.Close()
}
func checkNotificationRegisteredZones(oldZoneId string, newZoneId string, oldApId string, newApId string, userId string) {
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, value := range zonalSubscriptionMap {
if value == newZoneId {
if newZoneId != oldZoneId {
if zonalSubscriptionEnteringMap[subsId] != "" {
subsIdStr := strconv.Itoa(subsId)
jsonInfo, _ := rc.JSONGetEntry(baseKey+typeZonalSubscription+":"+subsIdStr, ".")
if jsonInfo != "" {
subscription := convertJsonToZonalSubscription(jsonInfo)
var zonal ZonalPresenceNotification
zonal.ZoneId = newZoneId
zonal.CurrentAccessPointId = newApId
zonal.Address = userId
event := new(UserEventType)
*event = ENTERING_EVENT
zonal.UserEventType = event
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
zonal.Timestamp = ×tamp
zonal.CallbackData = subscription.ClientCorrelator
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("Zonal Notify Entering event in zone " + newZoneId + " for user " + userId)
}
}
} else {
if newApId != oldApId {
if zonalSubscriptionTransferringMap[subsId] != "" {
subsIdStr := strconv.Itoa(subsId)
jsonInfo, _ := rc.JSONGetEntry(baseKey+typeZonalSubscription+":"+subsIdStr, ".")
if jsonInfo != "" {
subscription := convertJsonToZonalSubscription(jsonInfo)
var zonal ZonalPresenceNotification
zonal.ZoneId = newZoneId
zonal.CurrentAccessPointId = newApId
zonal.PreviousAccessPointId = oldApId
zonal.Address = userId
event := new(UserEventType)
*event = TRANSFERRING_EVENT
zonal.UserEventType = event
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
zonal.Timestamp = ×tamp
zonal.CallbackData = subscription.ClientCorrelator
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("Zonal Notify Transferring event in zone " + newZoneId + " for user " + userId + " from Ap " + oldApId + " to " + newApId)
}
}
}
}
} else {
if value == oldZoneId {
if zonalSubscriptionLeavingMap[subsId] != "" {
subsIdStr := strconv.Itoa(subsId)
jsonInfo, _ := rc.JSONGetEntry(baseKey+typeZonalSubscription+":"+subsIdStr, ".")
if jsonInfo != "" {
subscription := convertJsonToZonalSubscription(jsonInfo)
var zonal ZonalPresenceNotification
zonal.ZoneId = oldZoneId
zonal.CurrentAccessPointId = oldApId
zonal.Address = userId
event := new(UserEventType)
*event = LEAVING_EVENT
zonal.UserEventType = event
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
zonal.Timestamp = ×tamp
zonal.CallbackData = subscription.ClientCorrelator
var inlineZonal InlineZonalPresenceNotification
inlineZonal.ZonalPresenceNotification = &zonal
sendZonalPresenceNotification(subscription.CallbackReference.NotifyURL, inlineZonal)
log.Info("Zonal Notify Leaving event in zone " + oldZoneId + " for user " + userId)
}
}
}
}
}
}
func usersGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var userData UeUserData
// Retrieve query parameters
u, _ := url.Parse(r.URL.String())
log.Info("url: ", u.RequestURI())
q := u.Query()
userData.queryZoneId = q["zoneId"]
userData.queryApId = q["accessPointId"]
userData.queryAddress = q["address"]
// Get user list from DB
var response InlineUserList
var userList UserList
userList.ResourceURL = hostUrl.String() + basePath + "queries/users"
response.UserList = &userList
userData.userList = &userList
keyName := baseKey + typeUser + ":*"
err := rc.ForEachJSONEntry(keyName, populateUserList, &userData)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send response
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func populateUserList(key string, jsonInfo string, userData interface{}) error {
// Get query params & userlist from user data
data := userData.(*UeUserData)
if data == nil || data.userList == nil {
return errors.New("userList not found in userData")
}
// Retrieve user info from DB
var userInfo UserInfo
err := json.Unmarshal([]byte(jsonInfo), &userInfo)
if err != nil {
return err
}
// Ignore entries with no zoneID or AP ID
if userInfo.ZoneId == "" || userInfo.AccessPointId == "" {
return nil
}
//query parameters looked through using OR within same query parameter and AND between different query parameters
//example returning users matching zoneId : (zone01 OR zone02) AND accessPointId : (ap1 OR ap2 OR ap3) AND address: (ipAddress1 OR ipAddress2)
foundAMatch := false
// Filter using query params
if len(data.queryZoneId) > 0 {
foundAMatch = false
for _, queryZoneId := range data.queryZoneId {
if userInfo.ZoneId == queryZoneId {
foundAMatch = true
}
}
if !foundAMatch {
return nil
}
}
if len(data.queryApId) > 0 {
foundAMatch = false
for _, queryApId := range data.queryApId {
if userInfo.AccessPointId == queryApId {
foundAMatch = true
}
}
if !foundAMatch {
return nil
}
}
if len(data.queryAddress) > 0 {
foundAMatch = false
for _, queryAddress := range data.queryAddress {
if userInfo.Address == queryAddress {
foundAMatch = true
}
}
if !foundAMatch {
return nil
}
}
// Add user info to list
data.userList.User = append(data.userList.User, userInfo)
return nil
}
func apGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var userData ApUserData
vars := mux.Vars(r)
// Retrieve query parameters
u, _ := url.Parse(r.URL.String())
log.Info("url: ", u.RequestURI())
q := u.Query()
userData.queryInterestRealm = q.Get("interestRealm")
// Get user list from DB
var response InlineAccessPointList
var apList AccessPointList
apList.ZoneId = vars["zoneId"]
apList.ResourceURL = hostUrl.String() + basePath + "queries/zones/" + vars["zoneId"] + "/accessPoints"
response.AccessPointList = &apList
userData.apList = &apList
keyName := baseKey + typeZone + ":" + vars["zoneId"] + ":*"
err := rc.ForEachJSONEntry(keyName, populateApList, &userData)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send response
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func apByIdGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineAccessPointInfo
var apInfo AccessPointInfo
response.AccessPointInfo = &apInfo
jsonApInfo, _ := rc.JSONGetEntry(baseKey+typeZone+":"+vars["zoneId"]+":"+typeAccessPoint+":"+vars["accessPointId"], ".")
if jsonApInfo == "" {
w.WriteHeader(http.StatusNotFound)
return
}
err := json.Unmarshal([]byte(jsonApInfo), &apInfo)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zonesGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineZoneList
var zoneList ZoneList
zoneList.ResourceURL = hostUrl.String() + basePath + "queries/zones"
response.ZoneList = &zoneList
keyName := baseKey + typeZone + ":*"
err := rc.ForEachJSONEntry(keyName, populateZoneList, &zoneList)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zonesByIdGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineZoneInfo
var zoneInfo ZoneInfo
response.ZoneInfo = &zoneInfo
jsonZoneInfo, _ := rc.JSONGetEntry(baseKey+typeZone+":"+vars["zoneId"], ".")
if jsonZoneInfo == "" {
w.WriteHeader(http.StatusNotFound)
return
}
err := json.Unmarshal([]byte(jsonZoneInfo), &zoneInfo)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func populateZoneList(key string, jsonInfo string, userData interface{}) error {
zoneList := userData.(*ZoneList)
var zoneInfo ZoneInfo
// Format response
err := json.Unmarshal([]byte(jsonInfo), &zoneInfo)
if err != nil {
return err
}
if zoneInfo.ZoneId != "" {
zoneList.Zone = append(zoneList.Zone, zoneInfo)
}
return nil
}
func populateApList(key string, jsonInfo string, userData interface{}) error {
// Get query params & aplist from user data
data := userData.(*ApUserData)
if data == nil || data.apList == nil {
return errors.New("apList not found in userData")
}
// Retrieve AP info from DB
var apInfo AccessPointInfo
err := json.Unmarshal([]byte(jsonInfo), &apInfo)
if err != nil {
return err
}
// Ignore entries with no AP ID
if apInfo.AccessPointId == "" {
return nil
}
// Filter using query params
if data.queryInterestRealm != "" && apInfo.InterestRealm != data.queryInterestRealm {
return nil
}
// Add AP info to list
data.apList.AccessPoint = append(data.apList.AccessPoint, apInfo)
return nil
}
func userTrackingSubDelete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
err := rc.JSONDelEntry(baseKey+typeUserSubscription+":"+vars["subscriptionId"], ".")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
deregisterUser(vars["subscriptionId"])
w.WriteHeader(http.StatusNoContent)
}
func userTrackingSubListGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineNotificationSubscriptionList
var userTrackingSubList NotificationSubscriptionList
userTrackingSubList.ResourceURL = hostUrl.String() + basePath + "subscriptions/userTracking"
response.NotificationSubscriptionList = &userTrackingSubList
keyName := baseKey + typeUserSubscription + "*"
err := rc.ForEachJSONEntry(keyName, populateUserTrackingList, &userTrackingSubList)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func userTrackingSubGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineUserTrackingSubscription
var userTrackingSub UserTrackingSubscription
response.UserTrackingSubscription = &userTrackingSub
jsonUserTrackingSub, _ := rc.JSONGetEntry(baseKey+typeUserSubscription+":"+vars["subscriptionId"], ".")
if jsonUserTrackingSub == "" {
w.WriteHeader(http.StatusNotFound)
return
}
err := json.Unmarshal([]byte(jsonUserTrackingSub), &userTrackingSub)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func userTrackingSubPost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineUserTrackingSubscription
var body InlineUserTrackingSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userTrackingSub := body.UserTrackingSubscription
if userTrackingSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if userTrackingSub.CallbackReference == nil || userTrackingSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if userTrackingSub.Address == "" {
log.Error("Mandatory Address parameter not present")
http.Error(w, "Mandatory Address parameter not present", http.StatusBadRequest)
return
}
newSubsId := nextUserSubscriptionIdAvailable
nextUserSubscriptionIdAvailable++
subsIdStr := strconv.Itoa(newSubsId)
registerUser(userTrackingSub.Address, userTrackingSub.UserEventCriteria, subsIdStr)
userTrackingSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/userTracking/" + subsIdStr
_ = rc.JSONSetEntry(baseKey+typeUserSubscription+":"+subsIdStr, ".", convertUserSubscriptionToJson(userTrackingSub))
response.UserTrackingSubscription = userTrackingSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, string(jsonResponse))
}
func userTrackingSubPut(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineUserTrackingSubscription
var body InlineUserTrackingSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userTrackingSub := body.UserTrackingSubscription
if userTrackingSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if userTrackingSub.CallbackReference == nil || userTrackingSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if userTrackingSub.Address == "" {
log.Error("Mandatory Address parameter not present")
http.Error(w, "Mandatory Address parameter not present", http.StatusBadRequest)
return
}
if userTrackingSub.ResourceURL == "" {
log.Error("Mandatory ResourceURL parameter not present")
http.Error(w, "Mandatory ResourceURL parameter not present", http.StatusBadRequest)
return
}
subsIdParamStr := vars["subscriptionId"]
selfUrl := strings.Split(userTrackingSub.ResourceURL, "/")
subsIdStr := selfUrl[len(selfUrl)-1]
//Body content not matching parameters
if subsIdStr != subsIdParamStr {
log.Error("SubscriptionId in endpoint and in body not matching")
http.Error(w, "SubscriptionId in endpoint and in body not matching", http.StatusBadRequest)
return
}
userTrackingSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/userTracking/" + subsIdStr
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
if userSubscriptionMap[subsId] == "" {
w.WriteHeader(http.StatusNotFound)
return
}
_ = rc.JSONSetEntry(baseKey+typeUserSubscription+":"+subsIdStr, ".", convertUserSubscriptionToJson(userTrackingSub))
deregisterUser(subsIdStr)
registerUser(userTrackingSub.Address, userTrackingSub.UserEventCriteria, subsIdStr)
response.UserTrackingSubscription = userTrackingSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func populateUserTrackingList(key string, jsonInfo string, userData interface{}) error {
userList := userData.(*NotificationSubscriptionList)
var userInfo UserTrackingSubscription
// Format response
err := json.Unmarshal([]byte(jsonInfo), &userInfo)
if err != nil {
return err
}
userList.UserTrackingSubscription = append(userList.UserTrackingSubscription, userInfo)
return nil
}
func zonalTrafficSubDelete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
err := rc.JSONDelEntry(baseKey+typeZonalSubscription+":"+vars["subscriptionId"], ".")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
deregisterZonal(vars["subscriptionId"])
w.WriteHeader(http.StatusNoContent)
}
func zonalTrafficSubListGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineNotificationSubscriptionList
var zonalTrafficSubList NotificationSubscriptionList
zonalTrafficSubList.ResourceURL = hostUrl.String() + basePath + "subscriptions/zonalTraffic"
response.NotificationSubscriptionList = &zonalTrafficSubList
keyName := baseKey + typeZonalSubscription + "*"
err := rc.ForEachJSONEntry(keyName, populateZonalTrafficList, &zonalTrafficSubList)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zonalTrafficSubGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineZonalTrafficSubscription
var zonalTrafficSub ZonalTrafficSubscription
response.ZonalTrafficSubscription = &zonalTrafficSub
jsonZonalTrafficSub, _ := rc.JSONGetEntry(baseKey+typeZonalSubscription+":"+vars["subscriptionId"], ".")
if jsonZonalTrafficSub == "" {
w.WriteHeader(http.StatusNotFound)
return
}
err := json.Unmarshal([]byte(jsonZonalTrafficSub), &zonalTrafficSub)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zonalTrafficSubPost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineZonalTrafficSubscription
var body InlineZonalTrafficSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
zonalTrafficSub := body.ZonalTrafficSubscription
if zonalTrafficSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if zonalTrafficSub.CallbackReference == nil || zonalTrafficSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if zonalTrafficSub.ZoneId == "" {
log.Error("Mandatory ZoneId parameter not present")
http.Error(w, "Mandatory ZoneId parameter not present", http.StatusBadRequest)
return
}
newSubsId := nextZonalSubscriptionIdAvailable
nextZonalSubscriptionIdAvailable++
subsIdStr := strconv.Itoa(newSubsId)
/*
if zonalTrafficSub.Duration > 0 {
//TODO start a timer mecanism and expire subscription
}
//else, lasts forever or until subscription is deleted
*/
if zonalTrafficSub.Duration != 0 { //used to be string -> zonalTrafficSub.Duration != "" && zonalTrafficSub.Duration != "0" {
//TODO start a timer mecanism and expire subscription
log.Info("Non zero duration")
}
//else, lasts forever or until subscription is deleted
zonalTrafficSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/zonalTraffic/" + subsIdStr
_ = rc.JSONSetEntry(baseKey+typeZonalSubscription+":"+subsIdStr, ".", convertZonalSubscriptionToJson(zonalTrafficSub))
registerZonal(zonalTrafficSub.ZoneId, zonalTrafficSub.UserEventCriteria, subsIdStr)
response.ZonalTrafficSubscription = zonalTrafficSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, string(jsonResponse))
}
func zonalTrafficSubPut(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineZonalTrafficSubscription
var body InlineZonalTrafficSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
zonalTrafficSub := body.ZonalTrafficSubscription
if zonalTrafficSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if zonalTrafficSub.CallbackReference == nil || zonalTrafficSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if zonalTrafficSub.ZoneId == "" {
log.Error("Mandatory ZoneId parameter not present")
http.Error(w, "Mandatory ZoneId parameter not present", http.StatusBadRequest)
return
}
if zonalTrafficSub.ResourceURL == "" {
log.Error("Mandatory ResourceURL parameter not present")
http.Error(w, "Mandatory ResourceURL parameter not present", http.StatusBadRequest)
return
}
subsIdParamStr := vars["subscriptionId"]
selfUrl := strings.Split(zonalTrafficSub.ResourceURL, "/")
subsIdStr := selfUrl[len(selfUrl)-1]
//body content not matching parameters
if subsIdStr != subsIdParamStr {
log.Error("SubscriptionId in endpoint and in body not matching")
http.Error(w, "SubscriptionId in endpoint and in body not matching", http.StatusBadRequest)
return
}
zonalTrafficSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/zonalTraffic/" + subsIdStr
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
if zonalSubscriptionMap[subsId] == "" {
w.WriteHeader(http.StatusNotFound)
return
}
_ = rc.JSONSetEntry(baseKey+typeZonalSubscription+":"+subsIdStr, ".", convertZonalSubscriptionToJson(zonalTrafficSub))
deregisterZonal(subsIdStr)
registerZonal(zonalTrafficSub.ZoneId, zonalTrafficSub.UserEventCriteria, subsIdStr)
response.ZonalTrafficSubscription = zonalTrafficSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func populateZonalTrafficList(key string, jsonInfo string, userData interface{}) error {
zoneList := userData.(*NotificationSubscriptionList)
var zoneInfo ZonalTrafficSubscription
// Format response
err := json.Unmarshal([]byte(jsonInfo), &zoneInfo)
if err != nil {
return err
}
zoneList.ZonalTrafficSubscription = append(zoneList.ZonalTrafficSubscription, zoneInfo)
return nil
}
func zoneStatusSubDelete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
err := rc.JSONDelEntry(baseKey+typeZoneStatusSubscription+":"+vars["subscriptionId"], ".")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
deregisterZoneStatus(vars["subscriptionId"])
w.WriteHeader(http.StatusNoContent)
}
func zoneStatusSubListGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineNotificationSubscriptionList
var zoneStatusSubList NotificationSubscriptionList
zoneStatusSubList.ResourceURL = hostUrl.String() + basePath + "subscriptions/zoneStatus"
response.NotificationSubscriptionList = &zoneStatusSubList
keyName := baseKey + typeZoneStatusSubscription + "*"
err := rc.ForEachJSONEntry(keyName, populateZoneStatusList, &zoneStatusSubList)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zoneStatusSubGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineZoneStatusSubscription
var zoneStatusSub ZoneStatusSubscription
response.ZoneStatusSubscription = &zoneStatusSub
jsonZoneStatusSub, _ := rc.JSONGetEntry(baseKey+typeZoneStatusSubscription+":"+vars["subscriptionId"], ".")
if jsonZoneStatusSub == "" {
w.WriteHeader(http.StatusNotFound)
return
}
err := json.Unmarshal([]byte(jsonZoneStatusSub), &zoneStatusSub)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func zoneStatusSubPost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response InlineZoneStatusSubscription
var body InlineZoneStatusSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
zoneStatusSub := body.ZoneStatusSubscription
if zoneStatusSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if zoneStatusSub.CallbackReference == nil || zoneStatusSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if zoneStatusSub.ZoneId == "" {
log.Error("Mandatory ZoneId parameter not present")
http.Error(w, "Mandatory ZoneId parameter not present", http.StatusBadRequest)
return
}
newSubsId := nextZoneStatusSubscriptionIdAvailable
nextZoneStatusSubscriptionIdAvailable++
subsIdStr := strconv.Itoa(newSubsId)
zoneStatusSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/zoneStatus/" + subsIdStr
_ = rc.JSONSetEntry(baseKey+typeZoneStatusSubscription+":"+subsIdStr, ".", convertZoneStatusSubscriptionToJson(zoneStatusSub))
registerZoneStatus(zoneStatusSub.ZoneId, zoneStatusSub.NumberOfUsersZoneThreshold, zoneStatusSub.NumberOfUsersAPThreshold,
zoneStatusSub.OperationStatus, subsIdStr)
response.ZoneStatusSubscription = zoneStatusSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, string(jsonResponse))
}
func zoneStatusSubPut(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var response InlineZoneStatusSubscription
var body InlineZoneStatusSubscription
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
zoneStatusSub := body.ZoneStatusSubscription
if zoneStatusSub == nil {
log.Error("Body not present")
http.Error(w, "Body not present", http.StatusBadRequest)
return
}
//checking for mandatory properties
if zoneStatusSub.CallbackReference == nil || zoneStatusSub.CallbackReference.NotifyURL == "" {
log.Error("Mandatory CallbackReference parameter not present")
http.Error(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if zoneStatusSub.ZoneId == "" {
log.Error("Mandatory ZoneId parameter not present")
http.Error(w, "Mandatory ZoneId parameter not present", http.StatusBadRequest)
return
}
if zoneStatusSub.ResourceURL == "" {
log.Error("Mandatory ResourceURL parameter not present")
http.Error(w, "Mandatory ResourceURL parameter not present", http.StatusBadRequest)
return
}
subsIdParamStr := vars["subscriptionId"]
selfUrl := strings.Split(zoneStatusSub.ResourceURL, "/")
subsIdStr := selfUrl[len(selfUrl)-1]
//body content not matching parameters
if subsIdStr != subsIdParamStr {
log.Error("SubscriptionId in endpoint and in body not matching")
http.Error(w, "SubscriptionId in endpoint and in body not matching", http.StatusBadRequest)
return
}
zoneStatusSub.ResourceURL = hostUrl.String() + basePath + "subscriptions/zoneStatus/" + subsIdStr
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
if zoneStatusSubscriptionMap[subsId] == nil {
w.WriteHeader(http.StatusNotFound)
return
}
_ = rc.JSONSetEntry(baseKey+typeZoneStatusSubscription+":"+subsIdStr, ".", convertZoneStatusSubscriptionToJson(zoneStatusSub))
deregisterZoneStatus(subsIdStr)
registerZoneStatus(zoneStatusSub.ZoneId, zoneStatusSub.NumberOfUsersZoneThreshold, zoneStatusSub.NumberOfUsersAPThreshold,
zoneStatusSub.OperationStatus, subsIdStr)
response.ZoneStatusSubscription = zoneStatusSub
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(jsonResponse))
}
func populateZoneStatusList(key string, jsonInfo string, userData interface{}) error {
zoneList := userData.(*NotificationSubscriptionList)
var zoneInfo ZoneStatusSubscription
// Format response
err := json.Unmarshal([]byte(jsonInfo), &zoneInfo)
if err != nil {
return err
}
zoneList.ZoneStatusSubscription = append(zoneList.ZoneStatusSubscription, zoneInfo)
return nil
}
func cleanUp() {
log.Info("Terminate all")
rc.DBFlush(baseKey)
nextZonalSubscriptionIdAvailable = 1
nextUserSubscriptionIdAvailable = 1
nextZoneStatusSubscriptionIdAvailable = 1
mutex.Lock()
defer mutex.Unlock()
zonalSubscriptionEnteringMap = map[int]string{}
zonalSubscriptionLeavingMap = map[int]string{}
zonalSubscriptionTransferringMap = map[int]string{}
zonalSubscriptionMap = map[int]string{}
userSubscriptionEnteringMap = map[int]string{}
userSubscriptionLeavingMap = map[int]string{}
userSubscriptionTransferringMap = map[int]string{}
userSubscriptionMap = map[int]string{}
zoneStatusSubscriptionMap = map[int]*ZoneStatusCheck{}
updateStoreName("")
}
func updateStoreName(storeName string) {
if currentStoreName != storeName {
currentStoreName = storeName
_ = httpLog.ReInit(logModuleLocServ, sandboxName, storeName, redisAddr, influxAddr)
}
}
func updateUserInfo(address string, zoneId string, accessPointId string, longitude *float32, latitude *float32) {
var oldZoneId string
var oldApId string
// Get User Info from DB
jsonUserInfo, _ := rc.JSONGetEntry(baseKey+typeUser+":"+address, ".")
userInfo := convertJsonToUserInfo(jsonUserInfo)
// Create new user info if necessary
if userInfo == nil {
userInfo = new(UserInfo)
userInfo.Address = address
userInfo.ResourceURL = hostUrl.String() + basePath + "queries/users?address=" + address
} else {
// Get old zone & AP IDs
oldZoneId = userInfo.ZoneId
oldApId = userInfo.AccessPointId
}
userInfo.ZoneId = zoneId
userInfo.AccessPointId = accessPointId
// Update position
if longitude == nil || latitude == nil {
userInfo.LocationInfo = nil
} else {
if userInfo.LocationInfo == nil {
userInfo.LocationInfo = new(LocationInfo)
}
//we only support shape == 2 in locationInfo, so we ignore any conditional parameters based on shape
userInfo.LocationInfo.Shape = 2
userInfo.LocationInfo.Longitude = nil
userInfo.LocationInfo.Longitude = append(userInfo.LocationInfo.Longitude, *longitude)
userInfo.LocationInfo.Latitude = nil
userInfo.LocationInfo.Latitude = append(userInfo.LocationInfo.Latitude, *latitude)
seconds := time.Now().Unix()
var timeStamp TimeStamp
timeStamp.Seconds = int32(seconds)
userInfo.LocationInfo.Timestamp = &timeStamp
}
// Update User info in DB & Send notifications
_ = rc.JSONSetEntry(baseKey+typeUser+":"+address, ".", convertUserInfoToJson(userInfo))
checkNotificationRegisteredUsers(oldZoneId, zoneId, oldApId, accessPointId, address)
checkNotificationRegisteredZones(oldZoneId, zoneId, oldApId, accessPointId, address)
}
func updateZoneInfo(zoneId string, nbAccessPoints int, nbUnsrvAccessPoints int, nbUsers int) {
// Get Zone Info from DB
jsonZoneInfo, _ := rc.JSONGetEntry(baseKey+typeZone+":"+zoneId, ".")
zoneInfo := convertJsonToZoneInfo(jsonZoneInfo)
// Create new zone info if necessary
if zoneInfo == nil {
zoneInfo = new(ZoneInfo)
zoneInfo.ZoneId = zoneId
zoneInfo.ResourceURL = hostUrl.String() + basePath + "queries/zones/" + zoneId
}
previousNbUsers := zoneInfo.NumberOfUsers
// Update info
if nbAccessPoints != -1 {
zoneInfo.NumberOfAccessPoints = int32(nbAccessPoints)
}
if nbUnsrvAccessPoints != -1 {
zoneInfo.NumberOfUnserviceableAccessPoints = int32(nbUnsrvAccessPoints)
}
if nbUsers != -1 {
zoneInfo.NumberOfUsers = int32(nbUsers)
}
// Update Zone info in DB & Send notifications
_ = rc.JSONSetEntry(baseKey+typeZone+":"+zoneId, ".", convertZoneInfoToJson(zoneInfo))
checkNotificationRegisteredZoneStatus(zoneId, "", int32(-1), int32(nbUsers), int32(-1), previousNbUsers)
}
func updateAccessPointInfo(zoneId string, apId string, conTypeStr string, opStatusStr string, nbUsers int, longitude *float32, latitude *float32) {
// Get AP Info from DB
jsonApInfo, _ := rc.JSONGetEntry(baseKey+typeZone+":"+zoneId+":"+typeAccessPoint+":"+apId, ".")
apInfo := convertJsonToAccessPointInfo(jsonApInfo)
// Create new AP info if necessary
if apInfo == nil {
apInfo = new(AccessPointInfo)
apInfo.AccessPointId = apId
apInfo.ResourceURL = hostUrl.String() + basePath + "queries/zones/" + zoneId + "/accessPoints/" + apId
}
previousNbUsers := apInfo.NumberOfUsers
// Update info
if opStatusStr != "" {
opStatus := convertStringToOperationStatus(opStatusStr)
apInfo.OperationStatus = &opStatus
}
if conTypeStr != "" {
conType := convertStringToConnectionType(conTypeStr)
apInfo.ConnectionType = &conType
}
if nbUsers != -1 {
apInfo.NumberOfUsers = int32(nbUsers)
}
// Update position
if longitude == nil || latitude == nil {
apInfo.LocationInfo = nil
} else {
if apInfo.LocationInfo == nil {
apInfo.LocationInfo = new(LocationInfo)
apInfo.LocationInfo.Accuracy = 1
}
//we only support shape != 7 in locationInfo
apInfo.LocationInfo.Shape = 2
apInfo.LocationInfo.Longitude = nil
apInfo.LocationInfo.Longitude = append(apInfo.LocationInfo.Longitude, *longitude)
apInfo.LocationInfo.Latitude = nil
apInfo.LocationInfo.Latitude = append(apInfo.LocationInfo.Latitude, *latitude)
seconds := time.Now().Unix()
var timeStamp TimeStamp
timeStamp.Seconds = int32(seconds)
apInfo.LocationInfo.Timestamp = &timeStamp
}
// Update AP info in DB & Send notifications
_ = rc.JSONSetEntry(baseKey+typeZone+":"+zoneId+":"+typeAccessPoint+":"+apId, ".", convertAccessPointInfoToJson(apInfo))
checkNotificationRegisteredZoneStatus(zoneId, apId, int32(nbUsers), int32(-1), previousNbUsers, int32(-1))
}
func zoneStatusReInit() {
//reusing the object response for the get multiple zoneStatusSubscription
var zoneList NotificationSubscriptionList
keyName := baseKey + typeZoneStatusSubscription + "*"
_ = rc.ForEachJSONEntry(keyName, populateZoneStatusList, &zoneList)
maxZoneStatusSubscriptionId := 0
mutex.Lock()
defer mutex.Unlock()
for _, zone := range zoneList.ZoneStatusSubscription {
resourceUrl := strings.Split(zone.ResourceURL, "/")
subscriptionId, err := strconv.Atoi(resourceUrl[len(resourceUrl)-1])
if err != nil {
log.Error(err)
} else {
if subscriptionId > maxZoneStatusSubscriptionId {
maxZoneStatusSubscriptionId = subscriptionId
}
var zoneStatus ZoneStatusCheck
opStatus := zone.OperationStatus
if opStatus != nil {
for i := 0; i < len(opStatus); i++ {
switch opStatus[i] {
case SERVICEABLE:
zoneStatus.Serviceable = true
case UNSERVICEABLE:
zoneStatus.Unserviceable = true
case OPSTATUS_UNKNOWN:
zoneStatus.Unknown = true
default:
}
}
}
zoneStatus.NbUsersInZoneThreshold = zone.NumberOfUsersZoneThreshold
zoneStatus.NbUsersInAPThreshold = zone.NumberOfUsersAPThreshold
zoneStatus.ZoneId = zone.ZoneId
zoneStatusSubscriptionMap[subscriptionId] = &zoneStatus
}
}
nextZoneStatusSubscriptionIdAvailable = maxZoneStatusSubscriptionId + 1
}
func zonalTrafficReInit() {
//reusing the object response for the get multiple zonalSubscription
var zoneList NotificationSubscriptionList
keyName := baseKey + typeZonalSubscription + "*"
_ = rc.ForEachJSONEntry(keyName, populateZonalTrafficList, &zoneList)
maxZonalSubscriptionId := 0
mutex.Lock()
defer mutex.Unlock()
for _, zone := range zoneList.ZonalTrafficSubscription {
resourceUrl := strings.Split(zone.ResourceURL, "/")
subscriptionId, err := strconv.Atoi(resourceUrl[len(resourceUrl)-1])
if err != nil {
log.Error(err)
} else {
if subscriptionId > maxZonalSubscriptionId {
maxZonalSubscriptionId = subscriptionId
}
for i := 0; i < len(zone.UserEventCriteria); i++ {
switch zone.UserEventCriteria[i] {
case ENTERING_EVENT:
zonalSubscriptionEnteringMap[subscriptionId] = zone.ZoneId
case LEAVING_EVENT:
zonalSubscriptionLeavingMap[subscriptionId] = zone.ZoneId
case TRANSFERRING_EVENT:
zonalSubscriptionTransferringMap[subscriptionId] = zone.ZoneId
default:
}
}
zonalSubscriptionMap[subscriptionId] = zone.ZoneId
}
}
nextZonalSubscriptionIdAvailable = maxZonalSubscriptionId + 1
}
func userTrackingReInit() {
//reusing the object response for the get multiple zonalSubscription
var userList NotificationSubscriptionList
keyName := baseKey + typeUserSubscription + "*"
_ = rc.ForEachJSONEntry(keyName, populateUserTrackingList, &userList)
maxUserSubscriptionId := 0
mutex.Lock()
defer mutex.Unlock()
for _, user := range userList.UserTrackingSubscription {
resourceUrl := strings.Split(user.ResourceURL, "/")
subscriptionId, err := strconv.Atoi(resourceUrl[len(resourceUrl)-1])
if err != nil {
log.Error(err)
} else {
if subscriptionId > maxUserSubscriptionId {
maxUserSubscriptionId = subscriptionId
}
for i := 0; i < len(user.UserEventCriteria); i++ {
switch user.UserEventCriteria[i] {
case ENTERING_EVENT:
userSubscriptionEnteringMap[subscriptionId] = user.Address
case LEAVING_EVENT:
userSubscriptionLeavingMap[subscriptionId] = user.Address
case TRANSFERRING_EVENT:
userSubscriptionTransferringMap[subscriptionId] = user.Address
default:
}
}
userSubscriptionMap[subscriptionId] = user.Address
}
}
nextUserSubscriptionIdAvailable = maxUserSubscriptionId + 1
}
|
[
"\"MEEP_SANDBOX_NAME\"",
"\"MEEP_PUBLIC_URL\"",
"\"MEEP_HOST_URL\""
] |
[] |
[
"MEEP_HOST_URL",
"MEEP_PUBLIC_URL",
"MEEP_SANDBOX_NAME"
] |
[]
|
["MEEP_HOST_URL", "MEEP_PUBLIC_URL", "MEEP_SANDBOX_NAME"]
|
go
| 3 | 0 | |
arrays/src/array_manipulation/Solution.java
|
package array_manipulation;
import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the arrayManipulation function below.
static long arrayManipulation(int n, int[][] queries) {
long[] arr = new long[n+1];
Arrays.fill(arr,0);
for(int[] query: queries){
arr[query[0]-1]+=query[2];
arr[query[1]]-=query[2];
}
long sum =0;
long max = 0;
for (int i = 0; i <n ; i++) {
sum+= arr[i];
if (sum > max){
max = sum;
}
}
return max;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nm = scanner.nextLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);
int[][] queries = new int[m][3];
for (int i = 0; i < m; i++) {
String[] queriesRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 3; j++) {
int queriesItem = Integer.parseInt(queriesRowItems[j]);
queries[i][j] = queriesItem;
}
}
long result = arrayManipulation(n, queries);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
[
"\"OUTPUT_PATH\""
] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
java
| 1 | 0 | |
tests/unit/conftest.py
|
import json
import os
from pytest import fixture
from hypothesis import settings, HealthCheck
from chalice.app import Chalice
# From:
# http://hypothesis.readthedocs.io/en/latest/settings.html#settings-profiles
# On travis we'll have it run through more iterations.
settings.register_profile(
'ci', settings(max_examples=2000,
use_coverage=False,
suppress_health_check=[HealthCheck.too_slow]),
)
# When you're developing locally, we'll only run a few examples
# to keep unit tests fast. If you want to run more iterations
# locally just set HYPOTHESIS_PROFILE=ci.
settings.register_profile('dev', settings(use_coverage=False,
max_examples=10))
settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'dev'))
print("HYPOTHESIS PROFILE: %s" % os.environ.get("HYPOTHESIS_PROFILE"))
@fixture(autouse=True)
def ensure_no_local_config(no_local_config):
pass
@fixture
def sample_app():
app = Chalice('sample')
@app.route('/')
def foo():
return {}
return app
@fixture
def sample_app_with_auth():
app = Chalice('sampleauth')
@app.authorizer('myauth')
def myauth(auth_request):
pass
@app.route('/', authorizer=myauth)
def foo():
return {}
return app
@fixture
def sample_app_schedule_only():
app = Chalice('schedule_only')
@app.schedule('rate(5 minutes)')
def cron(event):
pass
return app
@fixture
def sample_app_lambda_only():
app = Chalice('lambda_only')
@app.lambda_function()
def myfunction(event, context):
pass
return app
@fixture
def create_event():
def create_event_inner(uri, method, path, content_type='application/json'):
return {
'requestContext': {
'httpMethod': method,
'resourcePath': uri,
},
'headers': {
'Content-Type': content_type,
},
'pathParameters': path,
'multiValueQueryStringParameters': None,
'body': "",
'stageVariables': {},
}
return create_event_inner
@fixture
def create_empty_header_event():
def create_empty_header_event_inner(uri, method, path,
content_type='application/json'):
return {
'requestContext': {
'httpMethod': method,
'resourcePath': uri,
},
'headers': None,
'pathParameters': path,
'multiValueQueryStringParameters': None,
'body': "",
'stageVariables': {},
}
return create_empty_header_event_inner
@fixture
def create_event_with_body():
def create_event_with_body_inner(body, uri='/', method='POST',
content_type='application/json'):
event = create_event()(uri, method, {}, content_type)
if content_type == 'application/json':
body = json.dumps(body)
event['body'] = body
return event
return create_event_with_body_inner
|
[] |
[] |
[
"HYPOTHESIS_PROFILE"
] |
[]
|
["HYPOTHESIS_PROFILE"]
|
python
| 1 | 0 | |
tests/py/test_subprocess.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
#
# Extends the subprocess module to use runtime checkers, and report stderr output.
import os
import re
import subprocess
import tempfile
from subprocess import PIPE
def in_path(name):
"""Look for name in the PATH"""
for path in os.environ["PATH"].split(os.pathsep):
f = os.path.join(path, name)
if os.path.isfile(f) and os.access(f, os.X_OK):
return f
class TestProcessError(Exception):
def __init__(self, proc, what, output=None):
self.output = output
sep = "\n%s stderr(%s) %s\n" % ("_" * 32, proc.pid, "_" * 32)
error = sep + proc.error + sep if proc.error else ""
super(TestProcessError, self).__init__("%s pid=%s exit=%s: %s%s" % (
proc.cmd, proc.pid, proc.returncode, what, error))
class Popen(subprocess.Popen):
"""
Add TEST_EXE_PREFIX to the command, check stderr for runtime checker output.
In a 'with' statement it runs check_wait() on exit from the block, or
check_kill() if initialized with kill_me=True
"""
def __init__(self, *args, **kwargs):
"""
Takes all args and kwargs of subprocess.Popen except stdout, stderr, universal_newlines
kill_me=True runs check_kill() in __exit__() instead of check_wait()
"""
self.on_exit = self.check_kill if kwargs.pop('kill_me', False) else self.check_wait
self.errfile = tempfile.NamedTemporaryFile(delete=False)
kwargs.update({'universal_newlines': True, 'stdout': PIPE, 'stderr': self.errfile})
prefix = os.environ.get("TEST_EXE_PREFIX")
if prefix:
args = [prefix.split() + args[0]] + list(args[1:])
self.cmd = args[0]
super(Popen, self).__init__(*args, **kwargs)
def check_wait(self):
if self.wait() or self.error:
raise TestProcessError(self, "check_wait")
def communicate(self, *args, **kwargs):
result = super(Popen, self).communicate(*args, **kwargs)
if self.returncode or self.error:
raise TestProcessError(self, "check_communicate", result[0])
return result
def check_kill(self):
"""Raise if process has already exited, kill and raise if self.error is not empty"""
if self.poll() is None:
self.kill()
self.wait()
self.stdout.close() # Doesn't get closed if killed
if self.error:
raise TestProcessError(self, "check_kill found error output")
else:
raise TestProcessError(self, "check_kill process not running")
def expect(self, pattern):
line = self.stdout.readline()
match = re.search(pattern, line)
if not match:
raise TestProcessError(self, "can't find '%s' in '%s'" % (pattern, line))
return match
@property
def error(self):
"""Return stderr as string, may only be used after process has terminated."""
assert(self.poll is not None)
if not hasattr(self, "_error"):
self.errfile.close() # Not auto-deleted
with open(self.errfile.name) as f: # Re-open to read
self._error = f.read().strip()
os.unlink(self.errfile.name)
return self._error
def __enter__(self):
return self
def __exit__(self, *args):
self.on_exit()
def check_output(*args, **kwargs):
return Popen(*args, **kwargs).communicate()[0]
class Server(Popen):
"""A process that prints 'listening on <port>' to stdout"""
def __init__(self, *args, **kwargs):
super(Server, self).__init__(*args, **kwargs)
self.port = self.expect("listening on ([0-9]+)$").group(1)
|
[] |
[] |
[
"PATH",
"TEST_EXE_PREFIX"
] |
[]
|
["PATH", "TEST_EXE_PREFIX"]
|
python
| 2 | 0 | |
gateway/logger/dynamo.go
|
package logger
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/guregu/dynamo"
"log"
"os"
)
type accessLogDB struct {
client *dynamo.DB
accessLogTable string
}
var (
db accessLogDB
)
func init() {
accessLogTable := os.Getenv("DYNAMO_TABLE_ACCESS_LOG")
if accessLogTable == "" {
log.Fatal("missing DYNAMO_TABLE_ACCESS_LOG env")
}
dbEndpoint := os.Getenv("DYNAMO_ACCESS_LOG_ENDPOINT")
if dbEndpoint != "" {
db = accessLogDB{
client: dynamo.New(session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Profile: "local",
Config: aws.Config{Endpoint: aws.String(dbEndpoint)},
}))),
accessLogTable: accessLogTable,
}
} else {
db = accessLogDB{
client: dynamo.New(session.Must(session.NewSession())),
accessLogTable: accessLogTable,
}
}
}
func (ad accessLogDB) postAccessLogDB(ctx context.Context, item LogItem) error {
return ad.client.Table(ad.accessLogTable).
Put(item).RunWithContext(ctx)
}
|
[
"\"DYNAMO_TABLE_ACCESS_LOG\"",
"\"DYNAMO_ACCESS_LOG_ENDPOINT\""
] |
[] |
[
"DYNAMO_TABLE_ACCESS_LOG",
"DYNAMO_ACCESS_LOG_ENDPOINT"
] |
[]
|
["DYNAMO_TABLE_ACCESS_LOG", "DYNAMO_ACCESS_LOG_ENDPOINT"]
|
go
| 2 | 0 | |
vendor/github.com/coreos/go-systemd/daemon/watchdog_test.go
|
// Copyright 2016 CoreOS, 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 daemon
import (
"os"
"strconv"
"testing"
"time"
)
func must(err error) {
if err != nil {
panic(err)
}
}
func TestSdWatchdogEnabled(t *testing.T) {
mypid := strconv.Itoa(os.Getpid())
tests := []struct {
usec string // empty => unset
pid string // empty => unset
unsetEnv bool // arbitrarily set across testcases
werr bool
wdelay time.Duration
}{
// Success cases
{"100", mypid, true, false, 100 * time.Microsecond},
{"50", mypid, true, false, 50 * time.Microsecond},
{"1", mypid, false, false, 1 * time.Microsecond},
{"1", "", true, false, 1 * time.Microsecond},
// No-op cases
{"", mypid, true, false, 0}, // WATCHDOG_USEC not set
{"1", "0", false, false, 0}, // WATCHDOG_PID doesn't match
{"", "", true, false, 0}, // Both not set
// Failure cases
{"-1", mypid, true, true, 0}, // Negative USEC
{"string", "1", false, true, 0}, // Non-integer USEC value
{"1", "string", true, true, 0}, // Non-integer PID value
{"stringa", "stringb", false, true, 0}, // E v e r y t h i n g
{"-10239", "-eleventythree", true, true, 0}, // i s w r o n g
}
for i, tt := range tests {
if tt.usec != "" {
must(os.Setenv("WATCHDOG_USEC", tt.usec))
} else {
must(os.Unsetenv("WATCHDOG_USEC"))
}
if tt.pid != "" {
must(os.Setenv("WATCHDOG_PID", tt.pid))
} else {
must(os.Unsetenv("WATCHDOG_PID"))
}
delay, err := SdWatchdogEnabled(tt.unsetEnv)
if tt.werr && err == nil {
t.Errorf("#%d: want non-nil err, got nil", i)
} else if !tt.werr && err != nil {
t.Errorf("#%d: want nil err, got %v", i, err)
}
if tt.wdelay != delay {
t.Errorf("#%d: want delay=%d, got %d", i, tt.wdelay, delay)
}
if tt.unsetEnv && (os.Getenv("WATCHDOG_PID") != "" || os.Getenv("WATCHDOG_USEC") != "") {
t.Errorf("#%d: environment variables not cleaned up", i)
}
}
}
|
[
"\"WATCHDOG_PID\"",
"\"WATCHDOG_USEC\""
] |
[] |
[
"WATCHDOG_PID",
"WATCHDOG_USEC"
] |
[]
|
["WATCHDOG_PID", "WATCHDOG_USEC"]
|
go
| 2 | 0 | |
junos/resource_rib_group_test.go
|
package junos_test
import (
"os"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)
func TestAccJunosRibGroup_basic(t *testing.T) {
if os.Getenv("TESTACC_SWITCH") == "" {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccJunosRibGroupConfigCreate(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_policy.#", "1"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_policy.0", "testacc_ribGroup"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_rib.#", "1"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_rib.0", "testacc_ribGroup1.inet.0"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"export_rib", "testacc_ribGroup1.inet.0"),
),
},
{
Config: testAccJunosRibGroupConfigUpdate(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_rib.#", "2"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"import_rib.1", "testacc_ribGroup2.inet.0"),
resource.TestCheckResourceAttr("junos_rib_group.testacc_ribGroup",
"export_rib", "testacc_ribGroup2.inet.0"),
),
},
{
ResourceName: "junos_rib_group.testacc_ribGroup",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
}
func testAccJunosRibGroupConfigCreate() string {
return `
resource junos_routing_instance "testacc_ribGroup1" {
name = "testacc_ribGroup1"
}
resource junos_policyoptions_policy_statement "testacc_ribGroup" {
name = "testacc_ribGroup"
then {
action = "accept"
}
}
resource junos_rib_group testacc_ribGroup {
name = "testacc_ribGroup-test"
import_policy = [junos_policyoptions_policy_statement.testacc_ribGroup.name, ]
import_rib = [
"${junos_routing_instance.testacc_ribGroup1.name}.inet.0",
]
export_rib = "${junos_routing_instance.testacc_ribGroup1.name}.inet.0"
}
`
}
func testAccJunosRibGroupConfigUpdate() string {
return `
resource junos_routing_instance "testacc_ribGroup1" {
name = "testacc_ribGroup1"
}
resource junos_routing_instance "testacc_ribGroup2" {
name = "testacc_ribGroup2"
}
resource junos_policyoptions_policy_statement "testacc_ribGroup" {
name = "testacc_ribGroup"
then {
action = "accept"
}
}
resource junos_rib_group testacc_ribGroup {
name = "testacc_ribGroup-test"
import_policy = [junos_policyoptions_policy_statement.testacc_ribGroup.name, ]
import_rib = [
"${junos_routing_instance.testacc_ribGroup1.name}.inet.0",
"${junos_routing_instance.testacc_ribGroup2.name}.inet.0",
]
export_rib = "${junos_routing_instance.testacc_ribGroup2.name}.inet.0"
}
`
}
|
[
"\"TESTACC_SWITCH\""
] |
[] |
[
"TESTACC_SWITCH"
] |
[]
|
["TESTACC_SWITCH"]
|
go
| 1 | 0 | |
vendor/github.com/cloudfoundry-incubator/cf-test-helpers/cf/as_user.go
|
package cf
import (
"fmt"
"io/ioutil"
"os"
"time"
ginkgoconfig "github.com/onsi/ginkgo/config"
"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)
var AsUser = func(userContext UserContext, timeout time.Duration, actions func()) {
originalCfHomeDir, currentCfHomeDir := InitiateUserContext(userContext, timeout)
defer func() {
RestoreUserContext(userContext, timeout, originalCfHomeDir, currentCfHomeDir)
}()
TargetSpace(userContext, timeout)
actions()
}
func InitiateUserContext(userContext UserContext, timeout time.Duration) (originalCfHomeDir, currentCfHomeDir string) {
originalCfHomeDir = os.Getenv("CF_HOME")
currentCfHomeDir, err := ioutil.TempDir("", fmt.Sprintf("cf_home_%d", ginkgoconfig.GinkgoConfig.ParallelNode))
if err != nil {
panic("Error: could not create temporary home directory: " + err.Error())
}
os.Setenv("CF_HOME", currentCfHomeDir)
cfSetApiArgs := []string{"api", userContext.ApiUrl}
if userContext.SkipSSLValidation {
cfSetApiArgs = append(cfSetApiArgs, "--skip-ssl-validation")
}
runner.NewCmdRunner(Cf(cfSetApiArgs...), timeout).Run()
runner.NewCmdRunner(Cf("auth", userContext.Username, userContext.Password), timeout).Run()
return
}
func TargetSpace(userContext UserContext, timeout time.Duration) {
if userContext.Org != "" {
if userContext.Space != "" {
runner.NewCmdRunner(Cf("target", "-o", userContext.Org, "-s", userContext.Space), timeout).Run()
} else {
runner.NewCmdRunner(Cf("target", "-o", userContext.Org), timeout).Run()
}
}
}
func RestoreUserContext(_ UserContext, timeout time.Duration, originalCfHomeDir, currentCfHomeDir string) {
runner.NewCmdRunner(Cf("logout"), timeout).Run()
os.Setenv("CF_HOME", originalCfHomeDir)
os.RemoveAll(currentCfHomeDir)
}
|
[
"\"CF_HOME\""
] |
[] |
[
"CF_HOME"
] |
[]
|
["CF_HOME"]
|
go
| 1 | 0 | |
hth/public/views.py
|
import os
from django.shortcuts import render
from twilio.util import TwilioCapability
def home(request):
capability = TwilioCapability(os.environ['ACCOUNT_SID'], os.environ['AUTH_TOKEN'])
capability.allow_client_outgoing(os.environ['APPLICATION_SID'])
return render(request, 'public/home_page.html', {'twilio_token': capability.generate()})
|
[] |
[] |
[
"ACCOUNT_SID",
"APPLICATION_SID",
"AUTH_TOKEN"
] |
[]
|
["ACCOUNT_SID", "APPLICATION_SID", "AUTH_TOKEN"]
|
python
| 3 | 0 | |
apiproject/apiproject/asgi.py
|
"""
ASGI config for apiproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiproject.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
app.py
|
import os
from dotenv import load_dotenv
from flask import Flask, render_template, request, abort
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import VideoGrant, ChatGrant
load_dotenv()
twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
twilio_api_key_sid = os.environ.get('TWILIO_API_KEY_SID')
twilio_api_key_secret = os.environ.get('TWILIO_API_KEY_SECRET')
twilio_chat_service_sid = os.environ.get('TWILIO_CHAT_SERVICE_SID')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['POST'])
def login():
username = request.get_json(force=True).get('username')
if not username:
abort(401)
token = AccessToken(twilio_account_sid, twilio_api_key_sid,
twilio_api_key_secret, identity=username)
token.add_grant(VideoGrant(room='My Room'))
token.add_grant(ChatGrant(service_sid=twilio_chat_service_sid))
return {'token': token.to_jwt().decode()}
|
[] |
[] |
[
"TWILIO_CHAT_SERVICE_SID",
"TWILIO_API_KEY_SID",
"TWILIO_API_KEY_SECRET",
"TWILIO_ACCOUNT_SID"
] |
[]
|
["TWILIO_CHAT_SERVICE_SID", "TWILIO_API_KEY_SID", "TWILIO_API_KEY_SECRET", "TWILIO_ACCOUNT_SID"]
|
python
| 4 | 0 | |
python/cuml/test/dask/test_datasets.py
|
#
# Copyright (c) 2020, NVIDIA 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.
#
import pytest
import dask.array as da
import numpy as np
import cupy as cp
from dask.distributed import Client
from cuml.dask.datasets import make_blobs
from cuml.test.utils import unit_param, quality_param, stress_param
@pytest.mark.parametrize('nrows', [unit_param(1e3), quality_param(1e5),
stress_param(1e6)])
@pytest.mark.parametrize('ncols', [unit_param(10), quality_param(100),
stress_param(1000)])
@pytest.mark.parametrize('centers', [10])
@pytest.mark.parametrize("cluster_std", [0.1])
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
@pytest.mark.parametrize("nparts", [unit_param(1), unit_param(7),
quality_param(100),
stress_param(1000)])
@pytest.mark.parametrize("order", ['F', 'C'])
@pytest.mark.parametrize("output", ['array', 'dataframe'])
def test_make_blobs(nrows,
ncols,
centers,
cluster_std,
dtype,
nparts,
cluster,
order,
output):
c = Client(cluster)
try:
X, y = make_blobs(nrows, ncols,
centers=centers,
cluster_std=cluster_std,
dtype=dtype,
n_parts=nparts,
output=output,
order=order)
assert X.npartitions == nparts
assert y.npartitions == nparts
X_local = X.compute()
y_local = y.compute()
assert X_local.shape == (nrows, ncols)
if output == 'dataframe':
assert len(y_local[0].unique()) == centers
assert X_local.dtypes.unique() == [dtype]
assert y_local.shape == (nrows, 1)
elif output == 'array':
import cupy as cp
assert len(cp.unique(y_local)) == centers
assert y_local.dtype == dtype
assert y_local.shape == (nrows, )
finally:
c.close()
@pytest.mark.parametrize('n_samples', [unit_param(int(1e3)),
stress_param(int(1e6))])
@pytest.mark.parametrize('n_features', [unit_param(int(1e2)),
stress_param(int(1e3))])
@pytest.mark.parametrize('n_informative', [7])
@pytest.mark.parametrize('n_targets', [1, 3])
@pytest.mark.parametrize('bias', [-4.0])
@pytest.mark.parametrize('effective_rank', [None, 6])
@pytest.mark.parametrize('tail_strength', [0.5])
@pytest.mark.parametrize('noise', [1.0])
@pytest.mark.parametrize('shuffle', [True, False])
@pytest.mark.parametrize('coef', [True, False])
@pytest.mark.parametrize('random_state', [None, 1234])
@pytest.mark.parametrize('n_parts', [unit_param(1),
stress_param(3)])
def test_make_regression(n_samples, n_features, n_informative,
n_targets, bias, effective_rank,
tail_strength, noise, shuffle,
coef, random_state, n_parts,
cluster):
c = Client(cluster)
try:
from cuml.dask.datasets import make_regression
result = make_regression(n_samples=n_samples, n_features=n_features,
n_informative=n_informative,
n_targets=n_targets, bias=bias,
effective_rank=effective_rank, noise=noise,
shuffle=shuffle, coef=coef,
random_state=random_state, n_parts=n_parts)
if coef:
out, values, coefs = result
else:
out, values = result
assert out.shape == (n_samples, n_features), "out shape mismatch"
if n_targets > 1:
assert values.shape == (n_samples, n_targets), \
"values shape mismatch"
else:
assert values.shape == (n_samples,), "values shape mismatch"
assert len(out.chunks[0]) == n_parts
assert len(out.chunks[1]) == 1
if coef:
if n_targets > 1:
assert coefs.shape == (n_features, n_targets), \
"coefs shape mismatch"
assert len(coefs.chunks[1]) == 1
else:
assert coefs.shape == (n_features,), "coefs shape mismatch"
assert len(coefs.chunks[0]) == 1
test1 = da.all(da.sum(coefs != 0.0, axis=0) == n_informative)
std_test2 = da.std(values - (da.dot(out, coefs) + bias), axis=0)
test1, std_test2 = da.compute(test1, std_test2)
diff = cp.abs(1.0 - std_test2)
test2 = cp.all(diff < 1.5 * 10**(-1.))
assert test1, \
"Unexpected number of informative features"
assert test2, "Unexpectedly incongruent outputs"
finally:
c.close()
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
pkg/mod/golang.org/x/[email protected]/unix/syscall_unix_test.go
|
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
package unix_test
import (
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"syscall"
"testing"
"time"
"golang.org/x/sys/unix"
)
// Tests that below functions, structures and constants are consistent
// on all Unix-like systems.
func _() {
// program scheduling priority functions and constants
var (
_ func(int, int, int) error = unix.Setpriority
_ func(int, int) (int, error) = unix.Getpriority
)
const (
_ int = unix.PRIO_USER
_ int = unix.PRIO_PROCESS
_ int = unix.PRIO_PGRP
)
// termios constants
const (
_ int = unix.TCIFLUSH
_ int = unix.TCIOFLUSH
_ int = unix.TCOFLUSH
)
// fcntl file locking structure and constants
var (
_ = unix.Flock_t{
Type: int16(0),
Whence: int16(0),
Start: int64(0),
Len: int64(0),
Pid: int32(0),
}
)
const (
_ = unix.F_GETLK
_ = unix.F_SETLK
_ = unix.F_SETLKW
)
}
func TestErrnoSignalName(t *testing.T) {
testErrors := []struct {
num syscall.Errno
name string
}{
{syscall.EPERM, "EPERM"},
{syscall.EINVAL, "EINVAL"},
{syscall.ENOENT, "ENOENT"},
}
for _, te := range testErrors {
t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
e := unix.ErrnoName(te.num)
if e != te.name {
t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
}
})
}
testSignals := []struct {
num syscall.Signal
name string
}{
{syscall.SIGHUP, "SIGHUP"},
{syscall.SIGPIPE, "SIGPIPE"},
{syscall.SIGSEGV, "SIGSEGV"},
}
for _, ts := range testSignals {
t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
s := unix.SignalName(ts.num)
if s != ts.name {
t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
}
})
}
}
func TestSignalNum(t *testing.T) {
testSignals := []struct {
name string
want syscall.Signal
}{
{"SIGHUP", syscall.SIGHUP},
{"SIGPIPE", syscall.SIGPIPE},
{"SIGSEGV", syscall.SIGSEGV},
{"NONEXISTS", 0},
}
for _, ts := range testSignals {
t.Run(fmt.Sprintf("%s/%d", ts.name, ts.want), func(t *testing.T) {
got := unix.SignalNum(ts.name)
if got != ts.want {
t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
}
})
}
}
func TestFcntlInt(t *testing.T) {
t.Parallel()
file, err := ioutil.TempFile("", "TestFcntlInt")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
defer file.Close()
f := file.Fd()
flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
if err != nil {
t.Fatal(err)
}
if flags&unix.FD_CLOEXEC == 0 {
t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
}
}
// TestFcntlFlock tests whether the file locking structure matches
// the calling convention of each kernel.
func TestFcntlFlock(t *testing.T) {
name := filepath.Join(os.TempDir(), "TestFcntlFlock")
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
if err != nil {
t.Fatalf("Open failed: %v", err)
}
defer unix.Unlink(name)
defer unix.Close(fd)
flock := unix.Flock_t{
Type: unix.F_RDLCK,
Start: 0, Len: 0, Whence: 1,
}
if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
t.Fatalf("FcntlFlock failed: %v", err)
}
}
// TestPassFD tests passing a file descriptor over a Unix socket.
//
// This test involved both a parent and child process. The parent
// process is invoked as a normal test, with "go test", which then
// runs the child process by running the current test binary with args
// "-test.run=^TestPassFD$" and an environment variable used to signal
// that the test should become the child process instead.
func TestPassFD(t *testing.T) {
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" {
t.Skip("cannot exec subprocess on iOS, skipping test")
}
if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
passFDChild()
return
}
if runtime.GOOS == "aix" {
// Unix network isn't properly working on AIX
// 7.2 with Technical Level < 2
out, err := exec.Command("oslevel", "-s").Output()
if err != nil {
t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
}
if len(out) < len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
t.Skip("skipping on AIX because oslevel -s hasn't the right length")
}
aixVer := string(out[:4])
tl, err := strconv.Atoi(string(out[5:7]))
if err != nil {
t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
}
if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
t.Skip("skipped on AIX versions previous to 7.2 TL 2")
}
}
tempDir, err := ioutil.TempDir("", "TestPassFD")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
if err != nil {
t.Fatalf("Socketpair: %v", err)
}
writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
defer writeFile.Close()
defer readFile.Close()
cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
}
cmd.ExtraFiles = []*os.File{writeFile}
out, err := cmd.CombinedOutput()
if len(out) > 0 || err != nil {
t.Fatalf("child process: %q, %v", out, err)
}
c, err := net.FileConn(readFile)
if err != nil {
t.Fatalf("FileConn: %v", err)
}
defer c.Close()
uc, ok := c.(*net.UnixConn)
if !ok {
t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
}
buf := make([]byte, 32) // expect 1 byte
oob := make([]byte, 32) // expect 24 bytes
closeUnix := time.AfterFunc(5*time.Second, func() {
t.Logf("timeout reading from unix socket")
uc.Close()
})
_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
if err != nil {
t.Fatalf("ReadMsgUnix: %v", err)
}
closeUnix.Stop()
scms, err := unix.ParseSocketControlMessage(oob[:oobn])
if err != nil {
t.Fatalf("ParseSocketControlMessage: %v", err)
}
if len(scms) != 1 {
t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
}
scm := scms[0]
gotFds, err := unix.ParseUnixRights(&scm)
if err != nil {
t.Fatalf("unix.ParseUnixRights: %v", err)
}
if len(gotFds) != 1 {
t.Fatalf("wanted 1 fd; got %#v", gotFds)
}
f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
defer f.Close()
got, err := ioutil.ReadAll(f)
want := "Hello from child process!\n"
if string(got) != want {
t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
}
}
// passFDChild is the child process used by TestPassFD.
func passFDChild() {
defer os.Exit(0)
// Look for our fd. It should be fd 3, but we work around an fd leak
// bug here (http://golang.org/issue/2603) to let it be elsewhere.
var uc *net.UnixConn
for fd := uintptr(3); fd <= 10; fd++ {
f := os.NewFile(fd, "unix-conn")
var ok bool
netc, _ := net.FileConn(f)
uc, ok = netc.(*net.UnixConn)
if ok {
break
}
}
if uc == nil {
fmt.Println("failed to find unix fd")
return
}
// Make a file f to send to our parent process on uc.
// We make it in tempDir, which our parent will clean up.
flag.Parse()
tempDir := flag.Arg(0)
f, err := ioutil.TempFile(tempDir, "")
if err != nil {
fmt.Printf("TempFile: %v", err)
return
}
f.Write([]byte("Hello from child process!\n"))
f.Seek(0, 0)
rights := unix.UnixRights(int(f.Fd()))
dummyByte := []byte("x")
n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
if err != nil {
fmt.Printf("WriteMsgUnix: %v", err)
return
}
if n != 1 || oobn != len(rights) {
fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
return
}
}
// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
// and ParseUnixRights are able to successfully round-trip lists of file descriptors.
func TestUnixRightsRoundtrip(t *testing.T) {
testCases := [...][][]int{
{{42}},
{{1, 2}},
{{3, 4, 5}},
{{}},
{{1, 2}, {3, 4, 5}, {}, {7}},
}
for _, testCase := range testCases {
b := []byte{}
var n int
for _, fds := range testCase {
// Last assignment to n wins
n = len(b) + unix.CmsgLen(4*len(fds))
b = append(b, unix.UnixRights(fds...)...)
}
// Truncate b
b = b[:n]
scms, err := unix.ParseSocketControlMessage(b)
if err != nil {
t.Fatalf("ParseSocketControlMessage: %v", err)
}
if len(scms) != len(testCase) {
t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
}
for i, scm := range scms {
gotFds, err := unix.ParseUnixRights(&scm)
if err != nil {
t.Fatalf("ParseUnixRights: %v", err)
}
wantFds := testCase[i]
if len(gotFds) != len(wantFds) {
t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
}
for j, fd := range gotFds {
if fd != wantFds[j] {
t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
}
}
}
}
}
func TestRlimit(t *testing.T) {
var rlimit, zero unix.Rlimit
err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
if err != nil {
t.Fatalf("Getrlimit: save failed: %v", err)
}
if zero == rlimit {
t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
}
set := rlimit
set.Cur = set.Max - 1
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && set.Cur > 4096 {
// rlim_min for RLIMIT_NOFILE should be equal to
// or lower than kern.maxfilesperproc, which on
// some machines are 4096. See #40564.
set.Cur = 4096
}
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
if err != nil {
t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
}
var get unix.Rlimit
err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
if err != nil {
t.Fatalf("Getrlimit: get failed: %v", err)
}
set = rlimit
set.Cur = set.Max - 1
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && set.Cur > 4096 {
set.Cur = 4096
}
if set != get {
// Seems like Darwin requires some privilege to
// increase the soft limit of rlimit sandbox, though
// Setrlimit never reports an error.
switch runtime.GOOS {
case "darwin", "ios":
default:
t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
}
}
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
if err != nil {
t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
}
// make sure RLIM_INFINITY can be assigned to Rlimit members
_ = unix.Rlimit{
Cur: unix.RLIM_INFINITY,
Max: unix.RLIM_INFINITY,
}
}
func TestSeekFailure(t *testing.T) {
_, err := unix.Seek(-1, 0, 0)
if err == nil {
t.Fatalf("Seek(-1, 0, 0) did not fail")
}
str := err.Error() // used to crash on Linux
t.Logf("Seek: %v", str)
if str == "" {
t.Fatalf("Seek(-1, 0, 0) return error with empty message")
}
}
func TestSetsockoptString(t *testing.T) {
// should not panic on empty string, see issue #31277
err := unix.SetsockoptString(-1, 0, 0, "")
if err == nil {
t.Fatalf("SetsockoptString: did not fail")
}
}
func TestDup(t *testing.T) {
file, err := ioutil.TempFile("", "TestDup")
if err != nil {
t.Fatalf("Tempfile failed: %v", err)
}
defer os.Remove(file.Name())
defer file.Close()
f := int(file.Fd())
newFd, err := unix.Dup(f)
if err != nil {
t.Fatalf("Dup: %v", err)
}
// Create and reserve a file descriptor.
// Dup2 automatically closes it before reusing it.
nullFile, err := os.Open("/dev/null")
if err != nil {
t.Fatal(err)
}
dupFd := int(file.Fd())
err = unix.Dup2(newFd, dupFd)
if err != nil {
t.Fatalf("Dup2: %v", err)
}
// Keep the dummy file open long enough to not be closed in
// its finalizer.
runtime.KeepAlive(nullFile)
b1 := []byte("Test123")
b2 := make([]byte, 7)
_, err = unix.Write(dupFd, b1)
if err != nil {
t.Fatalf("Write to dup2 fd failed: %v", err)
}
_, err = unix.Seek(f, 0, 0)
if err != nil {
t.Fatalf("Seek failed: %v", err)
}
_, err = unix.Read(f, b2)
if err != nil {
t.Fatalf("Read back failed: %v", err)
}
if string(b1) != string(b2) {
t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
}
}
func TestPoll(t *testing.T) {
if runtime.GOOS == "android" ||
((runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64") {
t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
}
defer chtmpdir(t)()
f, cleanup := mktmpfifo(t)
defer cleanup()
const timeout = 100
ok := make(chan bool, 1)
go func() {
select {
case <-time.After(10 * timeout * time.Millisecond):
t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
case <-ok:
}
}()
for {
fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
n, err := unix.Poll(fds, timeout)
ok <- true
if err == unix.EINTR {
t.Logf("Poll interrupted")
continue
} else if err != nil {
t.Errorf("Poll: unexpected error: %v", err)
return
}
if n != 0 {
t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
}
break
}
}
func TestSelect(t *testing.T) {
for {
n, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
if err == unix.EINTR {
t.Logf("Select interrupted")
continue
} else if err != nil {
t.Fatalf("Select: %v", err)
}
if n != 0 {
t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
}
break
}
dur := 250 * time.Millisecond
var took time.Duration
for {
// On some platforms (e.g. Linux), the passed-in timeval is
// updated by select(2). Make sure to reset to the full duration
// in case of an EINTR.
tv := unix.NsecToTimeval(int64(dur))
start := time.Now()
n, err := unix.Select(0, nil, nil, nil, &tv)
took = time.Since(start)
if err == unix.EINTR {
t.Logf("Select interrupted after %v", took)
continue
} else if err != nil {
t.Fatalf("Select: %v", err)
}
if n != 0 {
t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
}
break
}
// On some BSDs the actual timeout might also be slightly less than the requested.
// Add an acceptable margin to avoid flaky tests.
if took < dur*2/3 {
t.Errorf("Select: got %v timeout, expected at least %v", took, dur)
}
rr, ww, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer rr.Close()
defer ww.Close()
if _, err := ww.Write([]byte("HELLO GOPHER")); err != nil {
t.Fatal(err)
}
rFdSet := &unix.FdSet{}
fd := int(rr.Fd())
rFdSet.Set(fd)
for {
n, err := unix.Select(fd+1, rFdSet, nil, nil, nil)
if err == unix.EINTR {
t.Log("Select interrupted")
continue
} else if err != nil {
t.Fatalf("Select: %v", err)
}
if n != 1 {
t.Fatalf("Select: got %v ready file descriptors, expected 1", n)
}
break
}
}
func TestGetwd(t *testing.T) {
fd, err := os.Open(".")
if err != nil {
t.Fatalf("Open .: %s", err)
}
defer fd.Close()
// Directory list for test. Do not worry if any are symlinks or do not
// exist on some common unix desktop environments. That will be checked.
dirs := []string{"/", "/usr/bin", "/etc", "/var", "/opt"}
switch runtime.GOOS {
case "android":
dirs = []string{"/", "/system/bin"}
case "darwin", "ios":
switch runtime.GOARCH {
case "arm64":
d1, err := ioutil.TempDir("", "d1")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
d2, err := ioutil.TempDir("", "d2")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
dirs = []string{d1, d2}
}
}
oldwd := os.Getenv("PWD")
for _, d := range dirs {
// Check whether d exists, is a dir and that d's path does not contain a symlink
fi, err := os.Stat(d)
if err != nil || !fi.IsDir() {
t.Logf("Test dir %s stat error (%v) or not a directory, skipping", d, err)
continue
}
check, err := filepath.EvalSymlinks(d)
if err != nil || check != d {
t.Logf("Test dir %s (%s) is symlink or other error (%v), skipping", d, check, err)
continue
}
err = os.Chdir(d)
if err != nil {
t.Fatalf("Chdir: %v", err)
}
pwd, err := unix.Getwd()
if err != nil {
t.Fatalf("Getwd in %s: %s", d, err)
}
os.Setenv("PWD", oldwd)
err = fd.Chdir()
if err != nil {
// We changed the current directory and cannot go back.
// Don't let the tests continue; they'll scribble
// all over some other directory.
fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
os.Exit(1)
}
if pwd != d {
t.Fatalf("Getwd returned %q want %q", pwd, d)
}
}
}
func compareStat_t(t *testing.T, otherStat string, st1, st2 *unix.Stat_t) {
if st2.Dev != st1.Dev {
t.Errorf("%s/Fstatat: got dev %v, expected %v", otherStat, st2.Dev, st1.Dev)
}
if st2.Ino != st1.Ino {
t.Errorf("%s/Fstatat: got ino %v, expected %v", otherStat, st2.Ino, st1.Ino)
}
if st2.Mode != st1.Mode {
t.Errorf("%s/Fstatat: got mode %v, expected %v", otherStat, st2.Mode, st1.Mode)
}
if st2.Uid != st1.Uid {
t.Errorf("%s/Fstatat: got uid %v, expected %v", otherStat, st2.Uid, st1.Uid)
}
if st2.Gid != st1.Gid {
t.Errorf("%s/Fstatat: got gid %v, expected %v", otherStat, st2.Gid, st1.Gid)
}
if st2.Size != st1.Size {
t.Errorf("%s/Fstatat: got size %v, expected %v", otherStat, st2.Size, st1.Size)
}
}
func TestFstatat(t *testing.T) {
defer chtmpdir(t)()
touch(t, "file1")
var st1 unix.Stat_t
err := unix.Stat("file1", &st1)
if err != nil {
t.Fatalf("Stat: %v", err)
}
var st2 unix.Stat_t
err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
if err != nil {
t.Fatalf("Fstatat: %v", err)
}
compareStat_t(t, "Stat", &st1, &st2)
err = os.Symlink("file1", "symlink1")
if err != nil {
t.Fatal(err)
}
err = unix.Lstat("symlink1", &st1)
if err != nil {
t.Fatalf("Lstat: %v", err)
}
err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
if err != nil {
t.Fatalf("Fstatat: %v", err)
}
compareStat_t(t, "Lstat", &st1, &st2)
}
func TestFchmodat(t *testing.T) {
defer chtmpdir(t)()
touch(t, "file1")
err := os.Symlink("file1", "symlink1")
if err != nil {
t.Fatal(err)
}
mode := os.FileMode(0444)
err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
if err != nil {
t.Fatalf("Fchmodat: unexpected error: %v", err)
}
fi, err := os.Stat("file1")
if err != nil {
t.Fatal(err)
}
if fi.Mode() != mode {
t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
}
mode = os.FileMode(0644)
didChmodSymlink := true
err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
if err != nil {
if (runtime.GOOS == "android" || runtime.GOOS == "linux" ||
runtime.GOOS == "solaris" || runtime.GOOS == "illumos") && err == unix.EOPNOTSUPP {
// Linux and Illumos don't support flags != 0
didChmodSymlink = false
} else {
t.Fatalf("Fchmodat: unexpected error: %v", err)
}
}
if !didChmodSymlink {
// Didn't change mode of the symlink. On Linux, the permissions
// of a symbolic link are always 0777 according to symlink(7)
mode = os.FileMode(0777)
}
var st unix.Stat_t
err = unix.Lstat("symlink1", &st)
if err != nil {
t.Fatal(err)
}
got := os.FileMode(st.Mode & 0777)
if got != mode {
t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
}
}
func TestMkdev(t *testing.T) {
major := uint32(42)
minor := uint32(7)
dev := unix.Mkdev(major, minor)
if unix.Major(dev) != major {
t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
}
if unix.Minor(dev) != minor {
t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
}
}
func TestPipe(t *testing.T) {
const s = "hello"
var pipes [2]int
err := unix.Pipe(pipes[:])
if err != nil {
t.Fatalf("pipe: %v", err)
}
r := pipes[0]
w := pipes[1]
go func() {
n, err := unix.Write(w, []byte(s))
if err != nil {
t.Errorf("bad write: %v", err)
return
}
if n != len(s) {
t.Errorf("bad write count: %d", n)
return
}
err = unix.Close(w)
if err != nil {
t.Errorf("bad close: %v", err)
return
}
}()
var buf [10 + len(s)]byte
n, err := unix.Read(r, buf[:])
if err != nil {
t.Fatalf("bad read: %v", err)
}
if n != len(s) {
t.Fatalf("bad read count: %d", n)
}
if string(buf[:n]) != s {
t.Fatalf("bad contents: %s", string(buf[:n]))
}
err = unix.Close(r)
if err != nil {
t.Fatalf("bad close: %v", err)
}
}
func TestRenameat(t *testing.T) {
defer chtmpdir(t)()
from, to := "renamefrom", "renameto"
touch(t, from)
err := unix.Renameat(unix.AT_FDCWD, from, unix.AT_FDCWD, to)
if err != nil {
t.Fatalf("Renameat: unexpected error: %v", err)
}
_, err = os.Stat(to)
if err != nil {
t.Error(err)
}
_, err = os.Stat(from)
if err == nil {
t.Errorf("Renameat: stat of renamed file %q unexpectedly succeeded", from)
}
}
func TestUtimesNanoAt(t *testing.T) {
defer chtmpdir(t)()
symlink := "symlink1"
os.Remove(symlink)
err := os.Symlink("nonexisting", symlink)
if err != nil {
t.Fatal(err)
}
// Some filesystems only support microsecond resolution. Account for
// that in Nsec.
ts := []unix.Timespec{
{Sec: 1111, Nsec: 2000},
{Sec: 3333, Nsec: 4000},
}
err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW)
if err != nil {
t.Fatalf("UtimesNanoAt: %v", err)
}
var st unix.Stat_t
err = unix.Lstat(symlink, &st)
if err != nil {
t.Fatalf("Lstat: %v", err)
}
// Only check Mtim, Atim might not be supported by the underlying filesystem
expected := ts[1]
if st.Mtim.Nsec == 0 {
// Some filesystems only support 1-second time stamp resolution
// and will always set Nsec to 0.
expected.Nsec = 0
}
if st.Mtim != expected {
t.Errorf("UtimesNanoAt: wrong mtime: got %v, expected %v", st.Mtim, expected)
}
}
// mktmpfifo creates a temporary FIFO and provides a cleanup function.
func mktmpfifo(t *testing.T) (*os.File, func()) {
err := unix.Mkfifo("fifo", 0666)
if err != nil {
t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
}
f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
if err != nil {
os.Remove("fifo")
t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
}
return f, func() {
f.Close()
os.Remove("fifo")
}
}
// utilities taken from os/os_test.go
func touch(t *testing.T, name string) {
f, err := os.Create(name)
if err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
// chtmpdir changes the working directory to a new temporary directory and
// provides a cleanup function. Used when PWD is read-only.
func chtmpdir(t *testing.T) func() {
oldwd, err := os.Getwd()
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
d, err := ioutil.TempDir("", "test")
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
if err := os.Chdir(d); err != nil {
t.Fatalf("chtmpdir: %v", err)
}
return func() {
if err := os.Chdir(oldwd); err != nil {
t.Fatalf("chtmpdir: %v", err)
}
os.RemoveAll(d)
}
}
|
[
"\"GO_WANT_HELPER_PROCESS\"",
"\"LD_LIBRARY_PATH\"",
"\"PWD\""
] |
[] |
[
"PWD",
"GO_WANT_HELPER_PROCESS",
"LD_LIBRARY_PATH"
] |
[]
|
["PWD", "GO_WANT_HELPER_PROCESS", "LD_LIBRARY_PATH"]
|
go
| 3 | 0 | |
pkg/platform/packet/packet.go
|
// Copyright 2020 The Lokomotive 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 packet
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/mitchellh/go-homedir"
"github.com/kinvolk/lokomotive/pkg/dns"
"github.com/kinvolk/lokomotive/pkg/helm"
"github.com/kinvolk/lokomotive/pkg/oidc"
"github.com/kinvolk/lokomotive/pkg/platform"
"github.com/kinvolk/lokomotive/pkg/terraform"
)
type nodeRole int
const (
controller = iota
worker
)
type workerPool struct {
Name string `hcl:"pool_name,label"`
Count int `hcl:"count"`
DisableBGP bool `hcl:"disable_bgp,optional"`
IPXEScriptURL string `hcl:"ipxe_script_url,optional"`
OSArch string `hcl:"os_arch,optional"`
OSChannel string `hcl:"os_channel,optional"`
OSVersion string `hcl:"os_version,optional"`
NodeType string `hcl:"node_type,optional"`
Labels map[string]string `hcl:"labels,optional"`
Taints map[string]string `hcl:"taints,optional"`
ReservationIDs map[string]string `hcl:"reservation_ids,optional"`
ReservationIDsDefault string `hcl:"reservation_ids_default,optional"`
SetupRaid bool `hcl:"setup_raid,optional"`
SetupRaidHDD bool `hcl:"setup_raid_hdd,optional"`
SetupRaidSSD bool `hcl:"setup_raid_ssd,optional"`
SetupRaidSSDFS bool `hcl:"setup_raid_ssd_fs,optional"`
CLCSnippets []string `hcl:"clc_snippets,optional"`
Tags map[string]string `hcl:"tags,optional"`
NodesDependOn []string // Not exposed to the user
}
type config struct {
AssetDir string `hcl:"asset_dir"`
AuthToken string `hcl:"auth_token,optional"`
ClusterName string `hcl:"cluster_name"`
Tags map[string]string `hcl:"tags,optional"`
ControllerCount int `hcl:"controller_count"`
ControllerType string `hcl:"controller_type,optional"`
ControllerCLCSnippets []string `hcl:"controller_clc_snippets,optional"`
DNS dns.Config `hcl:"dns,block"`
Facility string `hcl:"facility"`
ProjectID string `hcl:"project_id"`
SSHPubKeys []string `hcl:"ssh_pubkeys"`
OSArch string `hcl:"os_arch,optional"`
OSChannel string `hcl:"os_channel,optional"`
OSVersion string `hcl:"os_version,optional"`
IPXEScriptURL string `hcl:"ipxe_script_url,optional"`
ManagementCIDRs []string `hcl:"management_cidrs"`
NodePrivateCIDR string `hcl:"node_private_cidr"`
EnableAggregation bool `hcl:"enable_aggregation,optional"`
NetworkMTU int `hcl:"network_mtu,optional"`
PodCIDR string `hcl:"pod_cidr,optional"`
ServiceCIDR string `hcl:"service_cidr,optional"`
ClusterDomainSuffix string `hcl:"cluster_domain_suffix,optional"`
EnableReporting bool `hcl:"enable_reporting,optional"`
ReservationIDs map[string]string `hcl:"reservation_ids,optional"`
ReservationIDsDefault string `hcl:"reservation_ids_default,optional"`
CertsValidityPeriodHours int `hcl:"certs_validity_period_hours,optional"`
DisableSelfHostedKubelet bool `hcl:"disable_self_hosted_kubelet,optional"`
OIDC *oidc.Config `hcl:"oidc,block"`
EnableTLSBootstrap bool `hcl:"enable_tls_bootstrap,optional"`
EncryptPodTraffic bool `hcl:"encrypt_pod_traffic,optional"`
IgnoreX509CNCheck bool `hcl:"ignore_x509_cn_check,optional"`
WorkerPools []workerPool `hcl:"worker_pool,block"`
ConntrackMaxPerCore int `hcl:"conntrack_max_per_core,optional"`
// Not exposed to the user
KubeAPIServerExtraFlags []string
NodesDependOn []string
}
const (
// Name represents Packet platform name as it should be referenced in function calls and configuration.
Name = "packet"
)
func (c *config) LoadConfig(configBody *hcl.Body, evalContext *hcl.EvalContext) hcl.Diagnostics {
if configBody == nil {
return hcl.Diagnostics{}
}
if diags := gohcl.DecodeBody(*configBody, evalContext, c); len(diags) != 0 {
return diags
}
return c.checkValidConfig()
}
func NewConfig() *config {
return &config{
EnableAggregation: true,
EnableTLSBootstrap: true,
NetworkMTU: platform.NetworkMTU,
ConntrackMaxPerCore: platform.ConntrackMaxPerCore,
}
}
func (c *config) clusterDomain() string {
return fmt.Sprintf("%s.%s", c.ClusterName, c.DNS.Zone)
}
// Meta is part of Platform interface and returns common information about the platform configuration.
func (c *config) Meta() platform.Meta {
nodes := c.ControllerCount
for _, workerpool := range c.WorkerPools {
nodes += workerpool.Count
}
charts := platform.CommonControlPlaneCharts(!c.DisableSelfHostedKubelet)
charts = append(charts, helm.LokomotiveChart{
Name: "calico-host-protection",
Namespace: "kube-system",
})
charts = append(charts, helm.LokomotiveChart{
Name: "packet-ccm",
Namespace: "kube-system",
})
return platform.Meta{
AssetDir: c.AssetDir,
ExpectedNodes: nodes,
ControlplaneCharts: charts,
}
}
func (c *config) Initialize(ex *terraform.Executor) error {
if c.AuthToken == "" && os.Getenv("PACKET_AUTH_TOKEN") == "" {
return fmt.Errorf("cannot find the Packet authentication token:\n" +
"either specify AuthToken or use the PACKET_AUTH_TOKEN environment variable")
}
if c.AuthToken == "" {
c.AuthToken = os.Getenv("PACKET_AUTH_TOKEN")
}
if err := c.DNS.Validate(); err != nil {
return fmt.Errorf("parsing DNS configuration: %w", err)
}
assetDir, err := homedir.Expand(c.AssetDir)
if err != nil {
return err
}
terraformRootDir := terraform.GetTerraformRootDir(assetDir)
return createTerraformConfigFile(c, terraformRootDir)
}
func (c *config) Apply(ex *terraform.Executor) error {
assetDir, err := homedir.Expand(c.AssetDir)
if err != nil {
return err
}
c.AssetDir = assetDir
if err := c.Initialize(ex); err != nil {
return err
}
return c.terraformSmartApply(ex, c.DNS)
}
func (c *config) Destroy(ex *terraform.Executor) error {
if err := c.Initialize(ex); err != nil {
return err
}
return ex.Destroy()
}
func createTerraformConfigFile(cfg *config, terraformPath string) error {
tmplName := "cluster.tf"
t := template.New(tmplName)
t, err := t.Parse(terraformConfigTmpl)
if err != nil {
// TODO: Use template.Must().
return fmt.Errorf("parsing template: %w", err)
}
path := filepath.Join(terraformPath, tmplName)
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("creating file %q: %w", path, err)
}
defer f.Close()
keyListBytes, err := json.Marshal(cfg.SSHPubKeys)
if err != nil {
// TODO: Render manually instead of marshaling.
return fmt.Errorf("marshaling SSH public keys: %w", err)
}
managementCIDRs, err := json.Marshal(cfg.ManagementCIDRs)
if err != nil {
// TODO: Render manually instead of marshaling.
return fmt.Errorf("marshaling management CIDRs: %w", err)
}
// Configure oidc flags and set it to KubeAPIServerExtraFlags.
if cfg.OIDC != nil {
// Skipping the error checking here because its done in checkValidConfig().
oidcFlags, _ := cfg.OIDC.ToKubeAPIServerFlags(cfg.clusterDomain())
// TODO: Use append instead of setting the oidcFlags to KubeAPIServerExtraFlags.
// Append is not used for now because Initialize is called in cli/cmd/cluster.go
// and again in Apply which duplicates the values.
cfg.KubeAPIServerExtraFlags = oidcFlags
}
// Packet does not accept tags as a key-value map but as an array of
// strings.
platform.AppendVersionTag(&cfg.Tags)
tagsList := []string{}
for k, v := range cfg.Tags {
tagsList = append(tagsList, fmt.Sprintf("%s:%s", k, v))
}
sort.Strings(tagsList)
tags, err := json.Marshal(tagsList)
if err != nil {
// TODO: Render manually instead of marshaling.
return fmt.Errorf("marshaling tags: %w", err)
}
// Append lokoctl-version tag to all worker pools.
for i := range cfg.WorkerPools {
// Using index as we are using []workerPool which creates a copy of the slice
// Hence when the template is rendered worker pool Tags is empty.
// TODO: Add tests for validating the worker pool configuration.
platform.AppendVersionTag(&cfg.WorkerPools[i].Tags)
}
// Add explicit terraform dependencies for nodes with specific hw
// reservation UUIDs.
cfg.terraformAddDeps()
terraformCfg := struct {
Config config
Tags string
SSHPublicKeys string
ManagementCIDRs string
}{
Config: *cfg,
Tags: string(tags),
SSHPublicKeys: string(keyListBytes),
ManagementCIDRs: string(managementCIDRs),
}
if err := t.Execute(f, terraformCfg); err != nil {
return fmt.Errorf("executing template: %w", err)
}
return nil
}
// terraformSmartApply applies cluster configuration.
func (c *config) terraformSmartApply(ex *terraform.Executor, dc dns.Config) error {
// If the provider isn't manual, apply everything in a single step.
if dc.Provider != dns.Manual {
return ex.Apply()
}
steps := []terraform.ExecutionStep{
// We need the controllers' IP addresses before we can apply the 'dns' module.
{
Description: "create controllers",
Args: []string{
"apply",
"-auto-approve",
fmt.Sprintf("-target=module.packet-%s.packet_device.controllers", c.ClusterName),
},
},
{
Description: "construct DNS records",
Args: []string{"apply", "-auto-approve", "-target=module.dns"},
},
// Run `terraform refresh`. This is required in order to make the outputs from the previous
// apply operations available.
// TODO: Likely caused by https://github.com/hashicorp/terraform/issues/23158.
{
Description: "refresh Terraform state",
Args: []string{"refresh"},
},
{
Description: "complete infrastructure creation",
Args: []string{"apply", "-auto-approve"},
PreExecutionHook: c.DNS.ManualConfigPrompt(),
},
}
return ex.Execute(steps...)
}
// terraformAddDeps adds explicit dependencies to cluster nodes so nodes
// with a specific hw reservation UUID are created before nodes that don't have
// a specific hw reservation UUID.
// The function modifies c.NodesDependOn and c.workerPools[].NodesDependOn,
// assigning to them a slice, of all Terraform targets needed to be created
// first. For example:
//
// // Suppose worker pool "example" is the only to use a specific hw
// // reservation IDs. IOW, the controllers (c.NodesDependOn) depends on
// // worker pool "example" to be created first.
// // Then, after calling this function, the attribute will be:
// c.NodesDependOn = []string{"module.worker-example.device_ids"}
//
//
// The explicit Terraform dependency is needed to guarantees that nodes using
// hardware reservation "next-available" won't use reservation IDS that another
// worker pool may specify with a specific UUID, and thus fail to create the
// node. This race condition is best explained here, if you want more info:
// https://github.com/terraform-providers/terraform-provider-packet/issues/176
// https://github.com/terraform-providers/terraform-provider-packet/pull/208
func (c *config) terraformAddDeps() {
// Nodes with specific hw reservation IDs.
nodesWithRes := make([]string, 0)
// Note that dependencies expressed in Terraform are using the module
// output "device_ids". And it is very important to keep it this way.
//
// If we modify it to depend only on the module, for example (just
// "module.packet" instead of "module.packet.device_ids") it
// seems to work fine. However, it breaks if the dependency later
// becomes on the controller and another worker pool (e.g.
// [ "module.packet-cluster", "module.worker-1"]) as the resources aren't of
// the same *type*. In that case, Terraform throws this error:
//
// The given value is not suitable for child module variable
// "nodes_depend_on" defined at ...:
// all list elements must have the same type.
//
// Therefore, using the output of the resources ids, this issue is
// solved: all elements of the list (no matter if the dependency is on
// workers, controller or both) will always have the same type and work
// correctly, they are just resources ids (strings).
// Also, it makes nodes depend on nodes, that is the strict dependency
// that we really have, instead of depending in the whole module. So, it
// allows Terraform to handle parallelization, and we only add
// fine-grained dependencies.
if len(c.ReservationIDs) > 0 {
// Use a dummy tf output to wait on controllers nodes.
tfTarget := clusterTarget(c.ClusterName, "device_ids")
nodesWithRes = append(nodesWithRes, tfTarget)
}
for _, w := range c.WorkerPools {
if len(w.ReservationIDs) > 0 {
// Use a dummy tf output to wait on workers nodes.
tfTarget := poolTarget(w.Name, "device_ids")
nodesWithRes = append(nodesWithRes, tfTarget)
}
}
// Collected all nodes with reservations, create a dependency on others
// to them, so those nodes are created first.
if len(c.ReservationIDs) == 0 {
c.NodesDependOn = nodesWithRes
}
for i := range c.WorkerPools {
if len(c.WorkerPools[i].ReservationIDs) > 0 {
continue
}
c.WorkerPools[i].NodesDependOn = nodesWithRes
}
}
// poolToTarget returns a string that can be used as "-target" argument to Terraform.
// For example:
// // target will be "module.worker-pool1.ex".
// target := poolTarget("pool1", "ex")
//nolint: unparam
func poolTarget(name, resource string) string {
return fmt.Sprintf("module.worker-%v.%v", name, resource)
}
// clusterTarget returns a string that can be used as "-target" argument to Terraform.
// For example:
// // target will be "module.packet-clusterName.ex".
// target := clusterTarget("clusterName", "ex")
//nolint: unparam
func clusterTarget(name, resource string) string {
return fmt.Sprintf("module.packet-%v.%v", name, resource)
}
// checkValidConfig validates cluster configuration.
func (c *config) checkValidConfig() hcl.Diagnostics {
var diagnostics hcl.Diagnostics
diagnostics = append(diagnostics, c.checkNotEmptyWorkers()...)
diagnostics = append(diagnostics, c.checkWorkerPoolNamesUnique()...)
diagnostics = append(diagnostics, c.checkReservationIDs()...)
diagnostics = append(diagnostics, c.validateOSVersion()...)
if c.ConntrackMaxPerCore < 0 {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "conntrack_max_per_core can't be negative value",
Detail: fmt.Sprintf("'conntrack_max_per_core' value is %d", c.ConntrackMaxPerCore),
})
}
if c.OIDC != nil {
_, diags := c.OIDC.ToKubeAPIServerFlags(c.clusterDomain())
diagnostics = append(diagnostics, diags...)
}
return diagnostics
}
// checkNotEmptyWorkers checks if the cluster has at least 1 node pool defined.
func (c *config) checkNotEmptyWorkers() hcl.Diagnostics {
var diagnostics hcl.Diagnostics
if len(c.WorkerPools) == 0 {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "At least one worker pool must be defined",
Detail: "Make sure to define at least one worker pool block in your cluster block",
})
}
return diagnostics
}
// checkWorkerPoolNamesUnique verifies that all worker pool names are unique.
func (c *config) checkWorkerPoolNamesUnique() hcl.Diagnostics {
var diagnostics hcl.Diagnostics
dup := make(map[string]bool)
for _, w := range c.WorkerPools {
if !dup[w.Name] {
dup[w.Name] = true
continue
}
// It is duplicated.
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Worker pools name should be unique",
Detail: fmt.Sprintf("Worker pool %q is duplicated", w.Name),
})
}
return diagnostics
}
// checkReservationIDs checks that reservations configured for controllers and
// workers are valid according to checkEachReservation().
func (c *config) checkReservationIDs() hcl.Diagnostics {
var diagnostics hcl.Diagnostics
d := checkEachReservation(c.ReservationIDs, c.ReservationIDsDefault, c.ClusterName, controller, c.ControllerCount)
diagnostics = append(diagnostics, d...)
for _, w := range c.WorkerPools {
d := checkEachReservation(w.ReservationIDs, w.ReservationIDsDefault, w.Name, worker, w.Count)
diagnostics = append(diagnostics, d...)
}
return diagnostics
}
// validateOSVersion ensures os_version is used only with ipxe_script_url.
func (c *config) validateOSVersion() hcl.Diagnostics {
var diagnostics hcl.Diagnostics
// Ensure os_version is used only with ipxe_script_url.
if c.OSVersion != "" && c.IPXEScriptURL == "" {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "os_version is unexpected",
Detail: "os_version may only be specified with ipxe_script_url",
})
}
for _, w := range c.WorkerPools {
if w.OSVersion != "" && w.IPXEScriptURL == "" {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "os_version is unexpected",
Detail: fmt.Sprintf("os_version may only be specified with ipxe_script_url for worker pool %q", w.Name),
})
}
}
return diagnostics
}
// checkEachReservation checks that hardware reservations are in the correct
// format and, when it will cause problems, that reservation IDs values in this
// pool are not mixed between using "next-available" and specific UUIDs, as this
// can't work reliably.
// For more info, see comment when calling terraformCreateReservations().
//
//nolint:funlen,lll
func checkEachReservation(reservationIDs map[string]string, resDefault, name string, role nodeRole, count int) hcl.Diagnostics {
var diagnostics hcl.Diagnostics
errorPrefix := "Worker pool"
if role == controller {
errorPrefix = "Cluster"
}
// The following (several) checks try to avoid this: having a worker
// pool that a node uses specific UUID as hardware reservation ID and
// another node in the same pool that uses "next-available".
// All different variations that in the end result in that are checked
// below, and the reason is simple: we can't guarantee for those cases
// that nodes can be created reliably. Creation granularity is per pool,
// so if one pool mixes both, we can't guarantee that another pool
// created later that needs specific UUIDs won't have them used by the
// instances using "next-available" in the previous worker pool created.
// This can be solved in two ways: adding more granularity, or forbidding
// those cases. We opt for the second option, for simplicity, given that
// in the rare case that the user needs to mix them, it can specify another
// identical worker pool with "next-available".
// Avoid cases that set (to non default values) reservation_ids and
// reservation_ids_default.
if len(reservationIDs) > 0 && resDefault != "" {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%v can't set both: reservation_ids and reservation_ids_default", errorPrefix),
Detail: fmt.Sprintf("%v: %q sets both, instead add an entry in reservations_ids for each node", errorPrefix, name),
})
}
// Check reservation_ids map doesn't use "next-available" as a value.
for _, v := range reservationIDs {
if v == "next-available" {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%v reservations_ids entries can't use \"next-available\"", errorPrefix),
Detail: fmt.Sprintf("%v: %q uses it, use specific UUIDs or reservations_ids_default only", errorPrefix, name),
})
}
if v == "" {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%v reservations_ids entries can't be empty", errorPrefix),
Detail: fmt.Sprintf("%v: %q is empty", errorPrefix, name),
})
}
}
// Check format is:
// controller-<int> or worker-<int>
// If not, Terraform code will silently ignore it. We don't want that.
resPrefix := "worker-"
if role == controller {
resPrefix = "controller-"
}
d := checkResFormat(reservationIDs, name, errorPrefix, resPrefix)
diagnostics = append(diagnostics, d...)
if len(reservationIDs) > 0 && len(reservationIDs) != count {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%v reservations_ids does not match count field", errorPrefix),
Detail: fmt.Sprintf("%v: %q all nodes in pool must have reservation IDs set", errorPrefix, name),
})
}
return diagnostics
}
// checkResFormat checks that format for every key in reservationIDs is:
// <resPrefix>-<int>. resPrefix can't contain a "-" character.
func checkResFormat(reservationIDs map[string]string, name, errorPrefix, resPrefix string) hcl.Diagnostics {
var diagnostics hcl.Diagnostics
deviceIndexes := []int{}
expectedIndexes := []int{}
index := 0
for key := range reservationIDs {
expectedIndexes = append(expectedIndexes, index)
index++
hclErr := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid reservation ID",
Detail: fmt.Sprintf("%v: %q used %q, format should be \"%v<int>\"",
errorPrefix, name, key, resPrefix),
}
// The expected format is: <resPrefix>-<int>.
// Let's check it is this way.
if !strings.HasPrefix(key, resPrefix) {
diagnostics = append(diagnostics, hclErr)
// Don't duplicate the same error, show it one per key.
continue
}
resEntry := strings.Split(key, "-")
if len(resEntry) != 2 { //nolint:gomnd
diagnostics = append(diagnostics, hclErr)
// Don't duplicate the same error, show it one per key.
continue
}
// Check a valid number is used after "controller-" or
// "worker-".
index := resEntry[1]
i, err := strconv.Atoi(index)
if err == nil {
deviceIndexes = append(deviceIndexes, i)
continue
}
diagnostics = append(diagnostics, hclErr)
}
sort.Ints(deviceIndexes)
if !reflect.DeepEqual(deviceIndexes, expectedIndexes) {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid reservation ID",
Detail: fmt.Sprintf("%v: reservation IDs must be sequential and start from 0", errorPrefix),
})
}
return diagnostics
}
|
[
"\"PACKET_AUTH_TOKEN\"",
"\"PACKET_AUTH_TOKEN\""
] |
[] |
[
"PACKET_AUTH_TOKEN"
] |
[]
|
["PACKET_AUTH_TOKEN"]
|
go
| 1 | 0 | |
pkg/pinger/config.go
|
package pinger
import (
"flag"
"github.com/spf13/pflag"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
"os"
"time"
)
type Configuration struct {
KubeConfigFile string
KubeClient kubernetes.Interface
Port int
DaemonSetNamespace string
DaemonSetName string
Interval int
Mode string
InternalDNS string
ExternalDNS string
NodeName string
HostIP string
PodName string
PodIP string
ExternalAddress string
NetworkMode string
}
func ParseFlags() (*Configuration, error) {
var (
argPort = pflag.Int("port", 8080, "metrics port")
argKubeConfigFile = pflag.String("kubeconfig", "", "Path to kubeconfig file with authorization and master location information. If not set use the inCluster token.")
argDaemonSetNameSpace = pflag.String("ds-namespace", "kube-system", "kube-ovn-pinger daemonset namespace")
argDaemonSetName = pflag.String("ds-name", "kube-ovn-pinger", "kube-ovn-pinger daemonset name")
argInterval = pflag.Int("interval", 5, "interval seconds between consecutive pings")
argMode = pflag.String("mode", "server", "server or job Mode")
argInternalDns = pflag.String("internal-dns", "kubernetes.default", "check dns from pod")
argExternalDns = pflag.String("external-dns", "alauda.cn", "check external dns resolve from pod")
argExternalAddress = pflag.String("external-address", "114.114.114.114", "check ping connection to an external address, default empty that will disable external check")
argNetworkMode = pflag.String("network-mode", "kube-ovn", "The cni plugin current cluster used, default: kube-ovn")
)
klogFlags := flag.NewFlagSet("klog", flag.ExitOnError)
klog.InitFlags(klogFlags)
// Sync the glog and klog flags.
flag.CommandLine.VisitAll(func(f1 *flag.Flag) {
f2 := klogFlags.Lookup(f1.Name)
if f2 != nil {
value := f1.Value.String()
if err := f2.Value.Set(value); err != nil {
klog.Fatalf("failed to set flag %v", err)
}
}
})
pflag.CommandLine.AddGoFlagSet(klogFlags)
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
config := &Configuration{
KubeConfigFile: *argKubeConfigFile,
KubeClient: nil,
Port: *argPort,
DaemonSetNamespace: *argDaemonSetNameSpace,
DaemonSetName: *argDaemonSetName,
Interval: *argInterval,
Mode: *argMode,
InternalDNS: *argInternalDns,
ExternalDNS: *argExternalDns,
PodIP: os.Getenv("POD_IP"),
HostIP: os.Getenv("HOST_IP"),
NodeName: os.Getenv("NODE_NAME"),
PodName: os.Getenv("POD_NAME"),
ExternalAddress: *argExternalAddress,
NetworkMode: *argNetworkMode,
}
if err := config.initKubeClient(); err != nil {
return nil, err
}
klog.Infof("pinger config is %+v", config)
return config, nil
}
func (config *Configuration) initKubeClient() error {
var cfg *rest.Config
var err error
if config.KubeConfigFile == "" {
cfg, err = rest.InClusterConfig()
if err != nil {
klog.Errorf("use in cluster config failed %v", err)
return err
}
} else {
cfg, err = clientcmd.BuildConfigFromFlags("", config.KubeConfigFile)
if err != nil {
klog.Errorf("use --kubeconfig %s failed %v", config.KubeConfigFile, err)
return err
}
}
cfg.Timeout = 15 * time.Second
cfg.QPS = 1000
cfg.Burst = 2000
cfg.ContentType = "application/vnd.kubernetes.protobuf"
cfg.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
klog.Errorf("init kubernetes client failed %v", err)
return err
}
config.KubeClient = kubeClient
return nil
}
|
[
"\"POD_IP\"",
"\"HOST_IP\"",
"\"NODE_NAME\"",
"\"POD_NAME\""
] |
[] |
[
"HOST_IP",
"POD_IP",
"NODE_NAME",
"POD_NAME"
] |
[]
|
["HOST_IP", "POD_IP", "NODE_NAME", "POD_NAME"]
|
go
| 4 | 0 | |
terraform/lambda_functions/Kubectl_Command/Kubectl_Command.py
|
import logging, os
from kubernetes import client, config
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
node_list_keys = ('name', 'role', 'status', 'last_message', 'cpu_allocation', 'creation')
v1 = 0
""" --- Helpers to build responses which match the structure of the necessary dialog actions --- """
def get_slots(intent_request):
return intent_request['currentIntent']['slots']
def close(intent_request, fulfillment_state, message):
# check if request is from slack bot
# See https://github.com/timoludwig/devops-chatbot/wiki/AWS-Lambda-Notes
if intent_request['requestAttributes'] is not None and \
'x-amz-lex:channel-name' in intent_request['requestAttributes'] and \
intent_request['requestAttributes']['x-amz-lex:channel-name'] == 'Slack':
# if message is a list -> transform it into table with slack code escaping
if (type(message) is list):
message = "```" + print_table(message) + "```"
else:
# if message is a list -> transform it into sentence
if (type(message) is list):
message = print_sentence(message, intent_request)
response = {
'sessionAttributes': intent_request['sessionAttributes'],
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': {'contentType': 'PlainText',
'content': message}
}
}
return response
def print_table(rows):
# figure out column widths
widths = [len(max(columns, key=len)) for columns in zip(*rows)]
# print the header
header, data = rows[0], rows[1:]
result = ' | '.join(format(title, "%ds" % width) for width, title in zip(widths, header)) + "\n"
# print the separator
result += '-+-'.join('-' * width for width in widths) + "\n"
# print the data
for row in data:
result += " | ".join(format(cdata, "%ds" % width) for width, cdata in zip(widths, row)) + "\n"
return result
def print_sentence(rows, intent_request):
get_resource = get_slots(intent_request)["resource"]
header, data = rows[0], rows[1:]
message = "There are " + str(len(data)) + " " + get_resource + "s in total. "
status = {}
for row in data:
if row[2] in status:
status[(row[2])] += 1
else:
status[(row[2])] = 1
for stat, count in status.items():
message += "There are " + str(count) + " " + get_resource + "s with status " + stat
return message
""" --- Functions that control the bot's behavior --- """
def kubectl_get_api_call(intent_request):
"""
Performs dialog management and fulfillment.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting.
"""
global v1
get_resource = get_slots(intent_request)["resource"]
result = "error: the resource is not supported yet or does not exist"
source = intent_request['invocationSource']
if source == 'DialogCodeHook':
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt for the first violation detected.
slots = get_slots(intent_request)
# Validate slots here, not needed because it's a get call
logger.debug("The resource lex understood: " + get_resource)
if get_resource == 'node' or get_resource == 'nodes':
logger.debug("api call list_node")
result = v1.list_node()
rows = [node_list_keys]
for node in result.items:
# More info on kubectl cpu allocation: https://github.com/kubernetes/kubernetes/issues/17512
cpu_node = 0
pod_result = v1.list_pod_for_all_namespaces(field_selector="spec.nodeName=" + node.metadata.name)
for pod in pod_result.items:
for container in pod.spec.containers:
cpu_node += int(container.resources.requests['cpu'].replace('m', ''))
row = (node.metadata.name,
node.metadata.labels['kubernetes.io/role'],
node.status.conditions[-1].type,
node.status.conditions[-1].message,
str(cpu_node / 10) + "%",
node.metadata.creation_timestamp.strftime("%Y-%m-%d %H:%M:%S"))
rows.append(row)
result = rows
elif get_resource == 'componentstatus':
logger.debug("api call list_component_status")
result = v1.list_component_status()
elif get_resource == 'configmap' or get_resource == 'configmaps':
logger.debug("api call list_config_map_for_all_namespaces")
result = v1.list_config_map_for_all_namespaces()
elif get_resource == 'deployment' or get_resource == 'deployments':
logger.warning("api call not in core api v1")
result = {"message": "error: the core api v1 does not implement the resource " + get_resource + " yet."}
return close(intent_request, 'Fulfilled', result)
""" --- Intents --- """
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
# logger.debug(
# 'dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot's intent handlers
if intent_name == 'KubernetesIntent':
return kubectl_get_api_call(intent_request)
raise Exception('Intent with name ' + intent_name + ' not supported')
""" --- Setup --- """
def setup_kubernetes():
# This file has to be bundled with the function.zip (created by kops after cluster ~/.kube/conf)
global v1
try:
config.load_kube_config("config")
except:
message = "Loading config from package failed"
logger.error(message)
return False
v1 = client.CoreV1Api()
# Try to get a api call done to check configuration, timeout at 2s because lambda timeout is 3s
try:
v1.list_node(limit=1, timeout_seconds=2)
except:
message = "No connection possible"
logger.error(message)
return False
return True
""" --- Main handler --- """
def lambda_handler(event, context):
# print("Received event: " + json.dumps(event, indent=2))
# logger.debug("Incoming event: " + json.dumps(event))
if not (setup_kubernetes()):
logger.error("Kubernetes API config fails.")
return close(event, 'Fulfilled', "Kubernetes is not properly configured. Please have a look in the logs.")
result = dispatch(event)
logger.debug(result)
return result
# Offline mock event
demo_connect_event = {'messageVersion': '1.0',
'invocationSource': 'FulfillmentCodeHook',
'userId': 'test',
'sessionAttributes': {},
'requestAttributes': {'x-amz-lex:accept-content-types': 'PlainText,SSML'},
'bot': {'name': 'DevOpsChatBot',
'alias': '$LATEST',
'version': '$LATEST'},
'outputDialogMode': 'Text',
'currentIntent': {'name': 'KubernetesIntent',
'slots': {'resource': 'node'},
'slotDetails': {
'resource': {'resolutions': [{'value': 'node'}],
'originalValue': 'node'}},
'confirmationStatus': 'None',
'sourceLexNLUIntentInterpretation': None},
'inputTranscript': 'node'}
demo_chat_event = {'messageVersion': '1.0',
'invocationSource': 'FulfillmentCodeHook',
'userId': 'test',
'sessionAttributes': {},
'requestAttributes': None,
'bot': {'name': 'DevOpsChatBot',
'alias': '$LATEST',
'version': '$LATEST'},
'outputDialogMode': 'Text',
'currentIntent': {'name': 'KubernetesIntent',
'slots': {'resource': 'node'},
'slotDetails': {'resource': {'resolutions': [{'value': 'node'}],
'originalValue': 'node'}},
'confirmationStatus': 'None',
'sourceLexNLUIntentInterpretation': None},
'inputTranscript': 'node'}
demo_slack_event = {'messageVersion': '1.0',
'invocationSource': 'FulfillmentCodeHook',
'userId': 'test',
'sessionAttributes': {},
'requestAttributes': {'x-amz-lex:channel-id': '7cd6cfc4-8356-4e6b-a879-81aae1b89097',
'x-amz-lex:webhook-endpoint-url': 'https://channels.lex.eu-west-1.amazonaws.com/slack/webhook/7cd6cfc4-8356-4e6b-a879-81aae1b89097',
'x-amz-lex:accept-content-types': 'PlainText',
'x-amz-lex:user-id': '465214619063.487654285126',
'x-amz-lex:slack-team-id': 'TDP6AJ71V',
'x-amz-lex:slack-bot-token': os.environ['token'],
'x-amz-lex:channel-name': 'Slack', 'x-amz-lex:channel-type': 'Slack'},
'bot': {'name': 'DevOpsChatBot', 'alias': 'DevOpsChatBotAlias', 'version': '10'},
'bot': {'name': 'DevOpsChatBot',
'alias': '$LATEST',
'version': '$LATEST'},
'outputDialogMode': 'Text',
'currentIntent': {'name': 'KubernetesIntent',
'slots': {'resource': 'node'},
'slotDetails': {'resource': {'resolutions': [{'value': 'node'}],
'originalValue': 'node'}},
'confirmationStatus': 'None',
'sourceLexNLUIntentInterpretation': None},
'inputTranscript': 'node'}
# Offline mock call comment when publish!
#print("init")
#print(lambda_handler(demo_connect_event, ''))
#print(lambda_handler(demo_chat_event, ''))
#print(lambda_handler(demo_slack_event, ''))
|
[] |
[] |
[
"token"
] |
[]
|
["token"]
|
python
| 1 | 0 | |
twisted/internet/interfaces.py
|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Interface documentation.
Maintainer: Itamar Shtull-Trauring
"""
from __future__ import division, absolute_import
from zope.interface import Interface, Attribute
from twisted.python import deprecate
from twisted.python.versions import Version
class IAddress(Interface):
"""
An address, e.g. a TCP C{(host, port)}.
Default implementations are in L{twisted.internet.address}.
"""
### Reactor Interfaces
class IConnector(Interface):
"""
Object used to interface between connections and protocols.
Each L{IConnector} manages one connection.
"""
def stopConnecting():
"""
Stop attempting to connect.
"""
def disconnect():
"""
Disconnect regardless of the connection state.
If we are connected, disconnect, if we are trying to connect,
stop trying.
"""
def connect():
"""
Try to connect to remote address.
"""
def getDestination():
"""
Return destination this will try to connect to.
@return: An object which provides L{IAddress}.
"""
class IResolverSimple(Interface):
def getHostByName(name, timeout = (1, 3, 11, 45)):
"""
Resolve the domain name C{name} into an IP address.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{twisted.internet.defer.Deferred}
@return: The callback of the Deferred that is returned will be
passed a string that represents the IP address of the
specified name, or the errback will be called if the
lookup times out. If multiple types of address records
are associated with the name, A6 records will be returned
in preference to AAAA records, which will be returned in
preference to A records. If there are multiple records of
the type to be returned, one will be selected at random.
@raise twisted.internet.defer.TimeoutError: Raised
(asynchronously) if the name cannot be resolved within the
specified timeout period.
"""
class IResolver(IResolverSimple):
def query(query, timeout=None):
"""
Dispatch C{query} to the method which can handle its type.
@type query: L{twisted.names.dns.Query}
@param query: The DNS query being issued, to which a response is to be
generated.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupAddress(name, timeout=None):
"""
Perform an A record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupAddress6(name, timeout=None):
"""
Perform an A6 record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupIPV6Address(name, timeout=None):
"""
Perform an AAAA record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailExchange(name, timeout=None):
"""
Perform an MX record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupNameservers(name, timeout=None):
"""
Perform an NS record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupCanonicalName(name, timeout=None):
"""
Perform a CNAME record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailBox(name, timeout=None):
"""
Perform an MB record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailGroup(name, timeout=None):
"""
Perform an MG record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailRename(name, timeout=None):
"""
Perform an MR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupPointer(name, timeout=None):
"""
Perform a PTR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupAuthority(name, timeout=None):
"""
Perform an SOA record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupNull(name, timeout=None):
"""
Perform a NULL record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupWellKnownServices(name, timeout=None):
"""
Perform a WKS record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupHostInfo(name, timeout=None):
"""
Perform a HINFO record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupMailboxInfo(name, timeout=None):
"""
Perform an MINFO record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupText(name, timeout=None):
"""
Perform a TXT record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupResponsibility(name, timeout=None):
"""
Perform an RP record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupAFSDatabase(name, timeout=None):
"""
Perform an AFSDB record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupService(name, timeout=None):
"""
Perform an SRV record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupAllRecords(name, timeout=None):
"""
Perform an ALL_RECORD lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupSenderPolicy(name, timeout= 10):
"""
Perform a SPF record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupNamingAuthorityPointer(name, timeout=None):
"""
Perform a NAPTR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
def lookupZone(name, timeout=None):
"""
Perform an AXFR record lookup.
NB This is quite different from other DNS requests. See
U{http://cr.yp.to/djbdns/axfr-notes.html} for more
information.
NB Unlike other C{lookup*} methods, the timeout here is not a
list of ints, it is a single int.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: C{int}
@param timeout: When this timeout expires, the query is
considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances.
The first element of the tuple gives answers.
The second and third elements are always empty.
The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
class IReactorTCP(Interface):
def listenTCP(port, factory, backlog=50, interface=''):
"""
Connects a given protocol factory to the given numeric TCP/IP port.
@param port: a port number on which to listen
@param factory: a L{twisted.internet.protocol.ServerFactory} instance
@param backlog: size of the listen queue
@param interface: The local IPv4 or IPv6 address to which to bind;
defaults to '', ie all IPv4 addresses. To bind to all IPv4 and IPv6
addresses, you must call this method twice.
@return: an object that provides L{IListeningPort}.
@raise CannotListenError: as defined here
L{twisted.internet.error.CannotListenError},
if it cannot listen on this port (e.g., it
cannot bind to the required port number)
"""
def connectTCP(host, port, factory, timeout=30, bindAddress=None):
"""
Connect a TCP client.
@param host: A hostname or an IPv4 or IPv6 address literal.
@type host: L{bytes}
@param port: a port number
@param factory: a L{twisted.internet.protocol.ClientFactory} instance
@param timeout: number of seconds to wait before assuming the
connection has failed.
@param bindAddress: a (host, port) tuple of local address to bind
to, or None.
@return: An object which provides L{IConnector}. This connector will
call various callbacks on the factory when a connection is
made, failed, or lost - see
L{ClientFactory<twisted.internet.protocol.ClientFactory>}
docs for details.
"""
class IReactorSSL(Interface):
def connectSSL(host, port, factory, contextFactory, timeout=30, bindAddress=None):
"""
Connect a client Protocol to a remote SSL socket.
@param host: a host name
@param port: a port number
@param factory: a L{twisted.internet.protocol.ClientFactory} instance
@param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
@param timeout: number of seconds to wait before assuming the
connection has failed.
@param bindAddress: a (host, port) tuple of local address to bind to,
or C{None}.
@return: An object which provides L{IConnector}.
"""
def listenSSL(port, factory, contextFactory, backlog=50, interface=''):
"""
Connects a given protocol factory to the given numeric TCP/IP port.
The connection is a SSL one, using contexts created by the context
factory.
@param port: a port number on which to listen
@param factory: a L{twisted.internet.protocol.ServerFactory} instance
@param contextFactory: a L{twisted.internet.ssl.ContextFactory} instance
@param backlog: size of the listen queue
@param interface: the hostname to bind to, defaults to '' (all)
"""
class IReactorUNIX(Interface):
"""
UNIX socket methods.
"""
def connectUNIX(address, factory, timeout=30, checkPID=0):
"""
Connect a client protocol to a UNIX socket.
@param address: a path to a unix socket on the filesystem.
@param factory: a L{twisted.internet.protocol.ClientFactory} instance
@param timeout: number of seconds to wait before assuming the connection
has failed.
@param checkPID: if True, check for a pid file to verify that a server
is listening. If C{address} is a Linux abstract namespace path,
this must be C{False}.
@return: An object which provides L{IConnector}.
"""
def listenUNIX(address, factory, backlog=50, mode=0o666, wantPID=0):
"""
Listen on a UNIX socket.
@param address: a path to a unix socket on the filesystem.
@param factory: a L{twisted.internet.protocol.Factory} instance.
@param backlog: number of connections to allow in backlog.
@param mode: The mode (B{not} umask) to set on the unix socket. See
platform specific documentation for information about how this
might affect connection attempts.
@type mode: C{int}
@param wantPID: if True, create a pidfile for the socket. If C{address}
is a Linux abstract namespace path, this must be C{False}.
@return: An object which provides L{IListeningPort}.
"""
class IReactorUNIXDatagram(Interface):
"""
Datagram UNIX socket methods.
"""
def connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0o666, bindAddress=None):
"""
Connect a client protocol to a datagram UNIX socket.
@param address: a path to a unix socket on the filesystem.
@param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance
@param maxPacketSize: maximum packet size to accept
@param mode: The mode (B{not} umask) to set on the unix socket. See
platform specific documentation for information about how this
might affect connection attempts.
@type mode: C{int}
@param bindAddress: address to bind to
@return: An object which provides L{IConnector}.
"""
def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0o666):
"""
Listen on a datagram UNIX socket.
@param address: a path to a unix socket on the filesystem.
@param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.
@param maxPacketSize: maximum packet size to accept
@param mode: The mode (B{not} umask) to set on the unix socket. See
platform specific documentation for information about how this
might affect connection attempts.
@type mode: C{int}
@return: An object which provides L{IListeningPort}.
"""
class IReactorWin32Events(Interface):
"""
Win32 Event API methods
@since: 10.2
"""
def addEvent(event, fd, action):
"""
Add a new win32 event to the event loop.
@param event: a Win32 event object created using win32event.CreateEvent()
@param fd: an instance of L{twisted.internet.abstract.FileDescriptor}
@param action: a string that is a method name of the fd instance.
This method is called in response to the event.
@return: None
"""
def removeEvent(event):
"""
Remove an event.
@param event: a Win32 event object added using L{IReactorWin32Events.addEvent}
@return: None
"""
class IReactorUDP(Interface):
"""
UDP socket methods.
"""
def listenUDP(port, protocol, interface='', maxPacketSize=8192):
"""
Connects a given L{DatagramProtocol} to the given numeric UDP port.
@param port: A port number on which to listen.
@type port: C{int}
@param protocol: A L{DatagramProtocol} instance which will be
connected to the given C{port}.
@type protocol: L{DatagramProtocol}
@param interface: The local IPv4 or IPv6 address to which to bind;
defaults to '', ie all IPv4 addresses.
@type interface: C{str}
@param maxPacketSize: The maximum packet size to accept.
@type maxPacketSize: C{int}
@return: object which provides L{IListeningPort}.
"""
class IReactorMulticast(Interface):
"""
UDP socket methods that support multicast.
IMPORTANT: This is an experimental new interface. It may change
without backwards compatability. Suggestions are welcome.
"""
def listenMulticast(port, protocol, interface='', maxPacketSize=8192,
listenMultiple=False):
"""
Connects a given
L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the
given numeric UDP port.
@param listenMultiple: If set to True, allows multiple sockets to
bind to the same address and port number at the same time.
@type listenMultiple: C{bool}
@returns: An object which provides L{IListeningPort}.
@see: L{twisted.internet.interfaces.IMulticastTransport}
@see: U{http://twistedmatrix.com/documents/current/core/howto/udp.html}
"""
class IReactorSocket(Interface):
"""
Methods which allow a reactor to use externally created sockets.
For example, to use C{adoptStreamPort} to implement behavior equivalent
to that of L{IReactorTCP.listenTCP}, you might write code like this::
from socket import SOMAXCONN, AF_INET, SOCK_STREAM, socket
portSocket = socket(AF_INET, SOCK_STREAM)
# Set FD_CLOEXEC on port, left as an exercise. Then make it into a
# non-blocking listening port:
portSocket.setblocking(False)
portSocket.bind(('192.168.1.2', 12345))
portSocket.listen(SOMAXCONN)
# Now have the reactor use it as a TCP port
port = reactor.adoptStreamPort(
portSocket.fileno(), AF_INET, YourFactory())
# portSocket itself is no longer necessary, and needs to be cleaned
# up by us.
portSocket.close()
# Whenever the server is no longer needed, stop it as usual.
stoppedDeferred = port.stopListening()
Another potential use is to inherit a listening descriptor from a parent
process (for example, systemd or launchd), or to receive one over a UNIX
domain socket.
Some plans for extending this interface exist. See:
- U{http://twistedmatrix.com/trac/ticket/5573}: AF_UNIX SOCK_STREAM ports
- U{http://twistedmatrix.com/trac/ticket/6594}: AF_UNIX SOCK_DGRAM ports
"""
def adoptStreamPort(fileDescriptor, addressFamily, factory):
"""
Add an existing listening I{SOCK_STREAM} socket to the reactor to
monitor for new connections to accept and handle.
@param fileDescriptor: A file descriptor associated with a socket which
is already bound to an address and marked as listening. The socket
must be set non-blocking. Any additional flags (for example,
close-on-exec) must also be set by application code. Application
code is responsible for closing the file descriptor, which may be
done as soon as C{adoptStreamPort} returns.
@type fileDescriptor: C{int}
@param addressFamily: The address family (or I{domain}) of the socket.
For example, L{socket.AF_INET6}.
@param factory: A L{ServerFactory} instance to use to create new
protocols to handle connections accepted via this socket.
@return: An object providing L{IListeningPort}.
@raise twisted.internet.error.UnsupportedAddressFamily: If the
given address family is not supported by this reactor, or
not supported with the given socket type.
@raise twisted.internet.error.UnsupportedSocketType: If the
given socket type is not supported by this reactor, or not
supported with the given socket type.
"""
def adoptStreamConnection(fileDescriptor, addressFamily, factory):
"""
Add an existing connected I{SOCK_STREAM} socket to the reactor to
monitor for data.
Note that the given factory won't have its C{startFactory} and
C{stopFactory} methods called, as there is no sensible time to call
them in this situation.
@param fileDescriptor: A file descriptor associated with a socket which
is already connected. The socket must be set non-blocking. Any
additional flags (for example, close-on-exec) must also be set by
application code. Application code is responsible for closing the
file descriptor, which may be done as soon as
C{adoptStreamConnection} returns.
@type fileDescriptor: C{int}
@param addressFamily: The address family (or I{domain}) of the socket.
For example, L{socket.AF_INET6}.
@param factory: A L{ServerFactory} instance to use to create a new
protocol to handle the connection via this socket.
@raise UnsupportedAddressFamily: If the given address family is not
supported by this reactor, or not supported with the given socket
type.
@raise UnsupportedSocketType: If the given socket type is not supported
by this reactor, or not supported with the given socket type.
"""
def adoptDatagramPort(fileDescriptor, addressFamily, protocol,
maxPacketSize=8192):
"""
Add an existing listening I{SOCK_DGRAM} socket to the reactor to
monitor for read and write readiness.
@param fileDescriptor: A file descriptor associated with a socket which
is already bound to an address and marked as listening. The socket
must be set non-blocking. Any additional flags (for example,
close-on-exec) must also be set by application code. Application
code is responsible for closing the file descriptor, which may be
done as soon as C{adoptDatagramPort} returns.
@type fileDescriptor: C{int}
@param addressFamily: The address family (or I{domain}) of the socket.
For example, L{socket.AF_INET6}.
@type addressFamily: C{int}
@param protocol: A L{DatagramProtocol} instance to connect to
a UDP transport.
@type protocol: L{DatagramProtocol}
@param maxPacketSize: The maximum packet size to accept.
@type maxPacketSize: C{int}
@return: An object providing L{IListeningPort}.
@raise L{UnsupportedAddressFamily}: If the given address family is not
supported by this reactor, or not supported with the given socket
type.
@raise UnsupportedSocketType: If the given socket type is not supported
by this reactor, or not supported with the given socket type.
"""
class IReactorProcess(Interface):
def spawnProcess(processProtocol, executable, args=(), env={}, path=None,
uid=None, gid=None, usePTY=0, childFDs=None):
"""
Spawn a process, with a process protocol.
@type processProtocol: L{IProcessProtocol} provider
@param processProtocol: An object which will be notified of all
events related to the created process.
@param executable: the file name to spawn - the full path should be
used.
@param args: the command line arguments to pass to the process; a
sequence of strings. The first string should be the
executable's name.
@type env: a C{dict} mapping C{str} to C{str}, or C{None}.
@param env: the environment variables to pass to the child process. The
resulting behavior varies between platforms. If
- C{env} is not set:
- On POSIX: pass an empty environment.
- On Windows: pass C{os.environ}.
- C{env} is C{None}:
- On POSIX: pass C{os.environ}.
- On Windows: pass C{os.environ}.
- C{env} is a C{dict}:
- On POSIX: pass the key/value pairs in C{env} as the
complete environment.
- On Windows: update C{os.environ} with the key/value
pairs in the C{dict} before passing it. As a
consequence of U{bug #1640
<http://twistedmatrix.com/trac/ticket/1640>}, passing
keys with empty values in an effort to unset
environment variables I{won't} unset them.
@param path: the path to run the subprocess in - defaults to the
current directory.
@param uid: user ID to run the subprocess as. (Only available on
POSIX systems.)
@param gid: group ID to run the subprocess as. (Only available on
POSIX systems.)
@param usePTY: if true, run this process in a pseudo-terminal.
optionally a tuple of C{(masterfd, slavefd, ttyname)},
in which case use those file descriptors.
(Not available on all systems.)
@param childFDs: A dictionary mapping file descriptors in the new child
process to an integer or to the string 'r' or 'w'.
If the value is an integer, it specifies a file
descriptor in the parent process which will be mapped
to a file descriptor (specified by the key) in the
child process. This is useful for things like inetd
and shell-like file redirection.
If it is the string 'r', a pipe will be created and
attached to the child at that file descriptor: the
child will be able to write to that file descriptor
and the parent will receive read notification via the
L{IProcessProtocol.childDataReceived} callback. This
is useful for the child's stdout and stderr.
If it is the string 'w', similar setup to the previous
case will occur, with the pipe being readable by the
child instead of writeable. The parent process can
write to that file descriptor using
L{IProcessTransport.writeToChild}. This is useful for
the child's stdin.
If childFDs is not passed, the default behaviour is to
use a mapping that opens the usual stdin/stdout/stderr
pipes.
@see: L{twisted.internet.protocol.ProcessProtocol}
@return: An object which provides L{IProcessTransport}.
@raise OSError: Raised with errno C{EAGAIN} or C{ENOMEM} if there are
insufficient system resources to create a new process.
"""
class IReactorTime(Interface):
"""
Time methods that a Reactor should implement.
"""
def seconds():
"""
Get the current time in seconds.
@return: A number-like object of some sort.
"""
def callLater(delay, callable, *args, **kw):
"""
Call a function later.
@type delay: C{float}
@param delay: the number of seconds to wait.
@param callable: the callable object to call later.
@param args: the arguments to call it with.
@param kw: the keyword arguments to call it with.
@return: An object which provides L{IDelayedCall} and can be used to
cancel the scheduled call, by calling its C{cancel()} method.
It also may be rescheduled by calling its C{delay()} or
C{reset()} methods.
"""
def getDelayedCalls():
"""
Retrieve all currently scheduled delayed calls.
@return: A tuple of all L{IDelayedCall} providers representing all
currently scheduled calls. This is everything that has been
returned by C{callLater} but not yet called or canceled.
"""
class IDelayedCall(Interface):
"""
A scheduled call.
There are probably other useful methods we can add to this interface;
suggestions are welcome.
"""
def getTime():
"""
Get time when delayed call will happen.
@return: time in seconds since epoch (a float).
"""
def cancel():
"""
Cancel the scheduled call.
@raises twisted.internet.error.AlreadyCalled: if the call has already
happened.
@raises twisted.internet.error.AlreadyCancelled: if the call has already
been cancelled.
"""
def delay(secondsLater):
"""
Delay the scheduled call.
@param secondsLater: how many seconds from its current firing time to delay
@raises twisted.internet.error.AlreadyCalled: if the call has already
happened.
@raises twisted.internet.error.AlreadyCancelled: if the call has already
been cancelled.
"""
def reset(secondsFromNow):
"""
Reset the scheduled call's timer.
@param secondsFromNow: how many seconds from now it should fire,
equivalent to C{.cancel()} and then doing another
C{reactor.callLater(secondsLater, ...)}
@raises twisted.internet.error.AlreadyCalled: if the call has already
happened.
@raises twisted.internet.error.AlreadyCancelled: if the call has already
been cancelled.
"""
def active():
"""
@return: True if this call is still active, False if it has been
called or cancelled.
"""
class IReactorThreads(Interface):
"""
Dispatch methods to be run in threads.
Internally, this should use a thread pool and dispatch methods to them.
"""
def getThreadPool():
"""
Return the threadpool used by L{callInThread}. Create it first if
necessary.
@rtype: L{twisted.python.threadpool.ThreadPool}
"""
def callInThread(callable, *args, **kwargs):
"""
Run the callable object in a separate thread.
"""
def callFromThread(callable, *args, **kw):
"""
Cause a function to be executed by the reactor thread.
Use this method when you want to run a function in the reactor's thread
from another thread. Calling L{callFromThread} should wake up the main
thread (where L{reactor.run()<reactor.run>} is executing) and run the
given callable in that thread.
If you're writing a multi-threaded application the C{callable} may need
to be thread safe, but this method doesn't require it as such. If you
want to call a function in the next mainloop iteration, but you're in
the same thread, use L{callLater} with a delay of 0.
"""
def suggestThreadPoolSize(size):
"""
Suggest the size of the internal threadpool used to dispatch functions
passed to L{callInThread}.
"""
class IReactorCore(Interface):
"""
Core methods that a Reactor must implement.
"""
running = Attribute(
"A C{bool} which is C{True} from I{during startup} to "
"I{during shutdown} and C{False} the rest of the time.")
def resolve(name, timeout=10):
"""
Return a L{twisted.internet.defer.Deferred} that will resolve a hostname.
"""
def run():
"""
Fire 'startup' System Events, move the reactor to the 'running'
state, then run the main loop until it is stopped with C{stop()} or
C{crash()}.
"""
def stop():
"""
Fire 'shutdown' System Events, which will move the reactor to the
'stopped' state and cause C{reactor.run()} to exit.
"""
def crash():
"""
Stop the main loop *immediately*, without firing any system events.
This is named as it is because this is an extremely "rude" thing to do;
it is possible to lose data and put your system in an inconsistent
state by calling this. However, it is necessary, as sometimes a system
can become wedged in a pre-shutdown call.
"""
def iterate(delay=0):
"""
Run the main loop's I/O polling function for a period of time.
This is most useful in applications where the UI is being drawn "as
fast as possible", such as games. All pending L{IDelayedCall}s will
be called.
The reactor must have been started (via the C{run()} method) prior to
any invocations of this method. It must also be stopped manually
after the last call to this method (via the C{stop()} method). This
method is not re-entrant: you must not call it recursively; in
particular, you must not call it while the reactor is running.
"""
def fireSystemEvent(eventType):
"""
Fire a system-wide event.
System-wide events are things like 'startup', 'shutdown', and
'persist'.
"""
def addSystemEventTrigger(phase, eventType, callable, *args, **kw):
"""
Add a function to be called when a system event occurs.
Each "system event" in Twisted, such as 'startup', 'shutdown', and
'persist', has 3 phases: 'before', 'during', and 'after' (in that
order, of course). These events will be fired internally by the
Reactor.
An implementor of this interface must only implement those events
described here.
Callbacks registered for the "before" phase may return either None or a
Deferred. The "during" phase will not execute until all of the
Deferreds from the "before" phase have fired.
Once the "during" phase is running, all of the remaining triggers must
execute; their return values must be ignored.
@param phase: a time to call the event -- either the string 'before',
'after', or 'during', describing when to call it
relative to the event's execution.
@param eventType: this is a string describing the type of event.
@param callable: the object to call before shutdown.
@param args: the arguments to call it with.
@param kw: the keyword arguments to call it with.
@return: an ID that can be used to remove this call with
removeSystemEventTrigger.
"""
def removeSystemEventTrigger(triggerID):
"""
Removes a trigger added with addSystemEventTrigger.
@param triggerID: a value returned from addSystemEventTrigger.
@raise KeyError: If there is no system event trigger for the given
C{triggerID}.
@raise ValueError: If there is no system event trigger for the given
C{triggerID}.
@raise TypeError: If there is no system event trigger for the given
C{triggerID}.
"""
def callWhenRunning(callable, *args, **kw):
"""
Call a function when the reactor is running.
If the reactor has not started, the callable will be scheduled
to run when it does start. Otherwise, the callable will be invoked
immediately.
@param callable: the callable object to call later.
@param args: the arguments to call it with.
@param kw: the keyword arguments to call it with.
@return: None if the callable was invoked, otherwise a system
event id for the scheduled call.
"""
class IReactorPluggableResolver(Interface):
"""
A reactor with a pluggable name resolver interface.
"""
def installResolver(resolver):
"""
Set the internal resolver to use to for name lookups.
@type resolver: An object implementing the L{IResolverSimple} interface
@param resolver: The new resolver to use.
@return: The previously installed resolver.
"""
class IReactorDaemonize(Interface):
"""
A reactor which provides hooks that need to be called before and after
daemonization.
Notes:
- This interface SHOULD NOT be called by applications.
- This interface should only be implemented by reactors as a workaround
(in particular, it's implemented currently only by kqueue()).
For details please see the comments on ticket #1918.
"""
def beforeDaemonize():
"""
Hook to be called immediately before daemonization. No reactor methods
may be called until L{afterDaemonize} is called.
@return: C{None}.
"""
def afterDaemonize():
"""
Hook to be called immediately after daemonization. This may only be
called after L{beforeDaemonize} had been called previously.
@return: C{None}.
"""
class IReactorFDSet(Interface):
"""
Implement me to be able to use L{IFileDescriptor} type resources.
This assumes that your main-loop uses UNIX-style numeric file descriptors
(or at least similarly opaque IDs returned from a .fileno() method)
"""
def addReader(reader):
"""
I add reader to the set of file descriptors to get read events for.
@param reader: An L{IReadDescriptor} provider that will be checked for
read events until it is removed from the reactor with
L{removeReader}.
@return: C{None}.
"""
def addWriter(writer):
"""
I add writer to the set of file descriptors to get write events for.
@param writer: An L{IWriteDescriptor} provider that will be checked for
write events until it is removed from the reactor with
L{removeWriter}.
@return: C{None}.
"""
def removeReader(reader):
"""
Removes an object previously added with L{addReader}.
@return: C{None}.
"""
def removeWriter(writer):
"""
Removes an object previously added with L{addWriter}.
@return: C{None}.
"""
def removeAll():
"""
Remove all readers and writers.
Should not remove reactor internal reactor connections (like a waker).
@return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
which were removed.
"""
def getReaders():
"""
Return the list of file descriptors currently monitored for input
events by the reactor.
@return: the list of file descriptors monitored for input events.
@rtype: C{list} of C{IReadDescriptor}
"""
def getWriters():
"""
Return the list file descriptors currently monitored for output events
by the reactor.
@return: the list of file descriptors monitored for output events.
@rtype: C{list} of C{IWriteDescriptor}
"""
class IListeningPort(Interface):
"""
A listening port.
"""
def startListening():
"""
Start listening on this port.
@raise CannotListenError: If it cannot listen on this port (e.g., it is
a TCP port and it cannot bind to the required
port number).
"""
def stopListening():
"""
Stop listening on this port.
If it does not complete immediately, will return Deferred that fires
upon completion.
"""
def getHost():
"""
Get the host that this port is listening for.
@return: An L{IAddress} provider.
"""
class ILoggingContext(Interface):
"""
Give context information that will be used to log events generated by
this item.
"""
def logPrefix():
"""
@return: Prefix used during log formatting to indicate context.
@rtype: C{str}
"""
class IFileDescriptor(ILoggingContext):
"""
An interface representing a UNIX-style numeric file descriptor.
"""
def fileno():
"""
@raise: If the descriptor no longer has a valid file descriptor
number associated with it.
@return: The platform-specified representation of a file descriptor
number. Or C{-1} if the descriptor no longer has a valid file
descriptor number associated with it. As long as the descriptor
is valid, calls to this method on a particular instance must
return the same value.
"""
def connectionLost(reason):
"""
Called when the connection was lost.
This is called when the connection on a selectable object has been
lost. It will be called whether the connection was closed explicitly,
an exception occurred in an event handler, or the other end of the
connection closed it first.
See also L{IHalfCloseableDescriptor} if your descriptor wants to be
notified separately of the two halves of the connection being closed.
@param reason: A failure instance indicating the reason why the
connection was lost. L{error.ConnectionLost} and
L{error.ConnectionDone} are of special note, but the
failure may be of other classes as well.
"""
class IReadDescriptor(IFileDescriptor):
"""
An L{IFileDescriptor} that can read.
This interface is generally used in conjunction with L{IReactorFDSet}.
"""
def doRead():
"""
Some data is available for reading on your descriptor.
@return: If an error is encountered which causes the descriptor to
no longer be valid, a L{Failure} should be returned. Otherwise,
C{None}.
"""
class IWriteDescriptor(IFileDescriptor):
"""
An L{IFileDescriptor} that can write.
This interface is generally used in conjunction with L{IReactorFDSet}.
"""
def doWrite():
"""
Some data can be written to your descriptor.
@return: If an error is encountered which causes the descriptor to
no longer be valid, a L{Failure} should be returned. Otherwise,
C{None}.
"""
class IReadWriteDescriptor(IReadDescriptor, IWriteDescriptor):
"""
An L{IFileDescriptor} that can both read and write.
"""
class IHalfCloseableDescriptor(Interface):
"""
A descriptor that can be half-closed.
"""
def writeConnectionLost(reason):
"""
Indicates write connection was lost.
"""
def readConnectionLost(reason):
"""
Indicates read connection was lost.
"""
class ISystemHandle(Interface):
"""
An object that wraps a networking OS-specific handle.
"""
def getHandle():
"""
Return a system- and reactor-specific handle.
This might be a socket.socket() object, or some other type of
object, depending on which reactor is being used. Use and
manipulate at your own risk.
This might be used in cases where you want to set specific
options not exposed by the Twisted APIs.
"""
class IConsumer(Interface):
"""
A consumer consumes data from a producer.
"""
def registerProducer(producer, streaming):
"""
Register to receive data from a producer.
This sets self to be a consumer for a producer. When this object runs
out of data (as when a send(2) call on a socket succeeds in moving the
last data from a userspace buffer into a kernelspace buffer), it will
ask the producer to resumeProducing().
For L{IPullProducer} providers, C{resumeProducing} will be called once
each time data is required.
For L{IPushProducer} providers, C{pauseProducing} will be called
whenever the write buffer fills up and C{resumeProducing} will only be
called when it empties.
@type producer: L{IProducer} provider
@type streaming: C{bool}
@param streaming: C{True} if C{producer} provides L{IPushProducer},
C{False} if C{producer} provides L{IPullProducer}.
@raise RuntimeError: If a producer is already registered.
@return: C{None}
"""
def unregisterProducer():
"""
Stop consuming data from a producer, without disconnecting.
"""
def write(data):
"""
The producer will write data by calling this method.
The implementation must be non-blocking and perform whatever
buffering is necessary. If the producer has provided enough data
for now and it is a L{IPushProducer}, the consumer may call its
C{pauseProducing} method.
"""
class IProducer(Interface):
"""
A producer produces data for a consumer.
Typically producing is done by calling the write method of an class
implementing L{IConsumer}.
"""
def stopProducing():
"""
Stop producing data.
This tells a producer that its consumer has died, so it must stop
producing data for good.
"""
class IPushProducer(IProducer):
"""
A push producer, also known as a streaming producer is expected to
produce (write to this consumer) data on a continuous basis, unless
it has been paused. A paused push producer will resume producing
after its resumeProducing() method is called. For a push producer
which is not pauseable, these functions may be noops.
"""
def pauseProducing():
"""
Pause producing data.
Tells a producer that it has produced too much data to process for
the time being, and to stop until resumeProducing() is called.
"""
def resumeProducing():
"""
Resume producing data.
This tells a producer to re-add itself to the main loop and produce
more data for its consumer.
"""
class IPullProducer(IProducer):
"""
A pull producer, also known as a non-streaming producer, is
expected to produce data each time resumeProducing() is called.
"""
def resumeProducing():
"""
Produce data for the consumer a single time.
This tells a producer to produce data for the consumer once
(not repeatedly, once only). Typically this will be done
by calling the consumer's write() method a single time with
produced data.
"""
class IProtocol(Interface):
def dataReceived(data):
"""
Called whenever data is received.
Use this method to translate to a higher-level message. Usually, some
callback will be made upon the receipt of each complete protocol
message.
@param data: a string of indeterminate length. Please keep in mind
that you will probably need to buffer some data, as partial
(or multiple) protocol messages may be received! I recommend
that unit tests for protocols call through to this method with
differing chunk sizes, down to one byte at a time.
"""
def connectionLost(reason):
"""
Called when the connection is shut down.
Clear any circular references here, and any external references
to this Protocol. The connection has been closed. The C{reason}
Failure wraps a L{twisted.internet.error.ConnectionDone} or
L{twisted.internet.error.ConnectionLost} instance (or a subclass
of one of those).
@type reason: L{twisted.python.failure.Failure}
"""
def makeConnection(transport):
"""
Make a connection to a transport and a server.
"""
def connectionMade():
"""
Called when a connection is made.
This may be considered the initializer of the protocol, because
it is called when the connection is completed. For clients,
this is called once the connection to the server has been
established; for servers, this is called after an accept() call
stops blocking and a socket has been received. If you need to
send any greeting or initial message, do it here.
"""
class IProcessProtocol(Interface):
"""
Interface for process-related event handlers.
"""
def makeConnection(process):
"""
Called when the process has been created.
@type process: L{IProcessTransport} provider
@param process: An object representing the process which has been
created and associated with this protocol.
"""
def childDataReceived(childFD, data):
"""
Called when data arrives from the child process.
@type childFD: C{int}
@param childFD: The file descriptor from which the data was
received.
@type data: C{str}
@param data: The data read from the child's file descriptor.
"""
def childConnectionLost(childFD):
"""
Called when a file descriptor associated with the child process is
closed.
@type childFD: C{int}
@param childFD: The file descriptor which was closed.
"""
def processExited(reason):
"""
Called when the child process exits.
@type reason: L{twisted.python.failure.Failure}
@param reason: A failure giving the reason the child process
terminated. The type of exception for this failure is either
L{twisted.internet.error.ProcessDone} or
L{twisted.internet.error.ProcessTerminated}.
@since: 8.2
"""
def processEnded(reason):
"""
Called when the child process exits and all file descriptors associated
with it have been closed.
@type reason: L{twisted.python.failure.Failure}
@param reason: A failure giving the reason the child process
terminated. The type of exception for this failure is either
L{twisted.internet.error.ProcessDone} or
L{twisted.internet.error.ProcessTerminated}.
"""
class IHalfCloseableProtocol(Interface):
"""
Implemented to indicate they want notification of half-closes.
TCP supports the notion of half-closing the connection, e.g.
closing the write side but still not stopping reading. A protocol
that implements this interface will be notified of such events,
instead of having connectionLost called.
"""
def readConnectionLost():
"""
Notification of the read connection being closed.
This indicates peer did half-close of write side. It is now
the responsibility of the this protocol to call
loseConnection(). In addition, the protocol MUST make sure a
reference to it still exists (i.e. by doing a callLater with
one of its methods, etc.) as the reactor will only have a
reference to it if it is writing.
If the protocol does not do so, it might get garbage collected
without the connectionLost method ever being called.
"""
def writeConnectionLost():
"""
Notification of the write connection being closed.
This will never be called for TCP connections as TCP does not
support notification of this type of half-close.
"""
class IFileDescriptorReceiver(Interface):
"""
Protocols may implement L{IFileDescriptorReceiver} to receive file
descriptors sent to them. This is useful in conjunction with
L{IUNIXTransport}, which allows file descriptors to be sent between
processes on a single host.
"""
def fileDescriptorReceived(descriptor):
"""
Called when a file descriptor is received over the connection.
@param descriptor: The descriptor which was received.
@type descriptor: C{int}
@return: C{None}
"""
class IProtocolFactory(Interface):
"""
Interface for protocol factories.
"""
def buildProtocol(addr):
"""
Called when a connection has been established to addr.
If None is returned, the connection is assumed to have been refused,
and the Port will close the connection.
@type addr: (host, port)
@param addr: The address of the newly-established connection
@return: None if the connection was refused, otherwise an object
providing L{IProtocol}.
"""
def doStart():
"""
Called every time this is connected to a Port or Connector.
"""
def doStop():
"""
Called every time this is unconnected from a Port or Connector.
"""
class ITransport(Interface):
"""
I am a transport for bytes.
I represent (and wrap) the physical connection and synchronicity
of the framework which is talking to the network. I make no
representations about whether calls to me will happen immediately
or require returning to a control loop, or whether they will happen
in the same or another thread. Consider methods of this class
(aside from getPeer) to be 'thrown over the wall', to happen at some
indeterminate time.
"""
def write(data):
"""
Write some data to the physical connection, in sequence, in a
non-blocking fashion.
If possible, make sure that it is all written. No data will
ever be lost, although (obviously) the connection may be closed
before it all gets through.
"""
def writeSequence(data):
"""
Write a list of strings to the physical connection.
If possible, make sure that all of the data is written to
the socket at once, without first copying it all into a
single string.
"""
def loseConnection():
"""
Close my connection, after writing all pending data.
Note that if there is a registered producer on a transport it
will not be closed until the producer has been unregistered.
"""
def getPeer():
"""
Get the remote address of this connection.
Treat this method with caution. It is the unfortunate result of the
CGI and Jabber standards, but should not be considered reliable for
the usual host of reasons; port forwarding, proxying, firewalls, IP
masquerading, etc.
@return: An L{IAddress} provider.
"""
def getHost():
"""
Similar to getPeer, but returns an address describing this side of the
connection.
@return: An L{IAddress} provider.
"""
class ITCPTransport(ITransport):
"""
A TCP based transport.
"""
def loseWriteConnection():
"""
Half-close the write side of a TCP connection.
If the protocol instance this is attached to provides
IHalfCloseableProtocol, it will get notified when the operation is
done. When closing write connection, as with loseConnection this will
only happen when buffer has emptied and there is no registered
producer.
"""
def abortConnection():
"""
Close the connection abruptly.
Discards any buffered data, stops any registered producer,
and, if possible, notifies the other end of the unclean
closure.
@since: 11.1
"""
def getTcpNoDelay():
"""
Return if C{TCP_NODELAY} is enabled.
"""
def setTcpNoDelay(enabled):
"""
Enable/disable C{TCP_NODELAY}.
Enabling C{TCP_NODELAY} turns off Nagle's algorithm. Small packets are
sent sooner, possibly at the expense of overall throughput.
"""
def getTcpKeepAlive():
"""
Return if C{SO_KEEPALIVE} is enabled.
"""
def setTcpKeepAlive(enabled):
"""
Enable/disable C{SO_KEEPALIVE}.
Enabling C{SO_KEEPALIVE} sends packets periodically when the connection
is otherwise idle, usually once every two hours. They are intended
to allow detection of lost peers in a non-infinite amount of time.
"""
def getHost():
"""
Returns L{IPv4Address} or L{IPv6Address}.
"""
def getPeer():
"""
Returns L{IPv4Address} or L{IPv6Address}.
"""
class IUNIXTransport(ITransport):
"""
Transport for stream-oriented unix domain connections.
"""
def sendFileDescriptor(descriptor):
"""
Send a duplicate of this (file, socket, pipe, etc) descriptor to the
other end of this connection.
The send is non-blocking and will be queued if it cannot be performed
immediately. The send will be processed in order with respect to other
C{sendFileDescriptor} calls on this transport, but not necessarily with
respect to C{write} calls on this transport. The send can only be
processed if there are also bytes in the normal connection-oriented send
buffer (ie, you must call C{write} at least as many times as you call
C{sendFileDescriptor}).
@param descriptor: An C{int} giving a valid file descriptor in this
process. Note that a I{file descriptor} may actually refer to a
socket, a pipe, or anything else POSIX tries to treat in the same
way as a file.
@return: C{None}
"""
class IOpenSSLServerConnectionCreator(Interface):
"""
A provider of L{IOpenSSLServerConnectionCreator} can create
L{OpenSSL.SSL.Connection} objects for TLS servers.
@see: L{twisted.internet.ssl}
@note: Creating OpenSSL connection objects is subtle, error-prone, and
security-critical. Before implementing this interface yourself,
consider using L{twisted.internet.ssl.CertificateOptions} as your
C{contextFactory}. (For historical reasons, that class does not
actually I{implement} this interface; nevertheless it is usable in all
Twisted APIs which require a provider of this interface.)
"""
def serverConnectionForTLS(tlsProtocol):
"""
Create a connection for the given server protocol.
@param tlsProtocol: the protocol server making the request.
@type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}.
@return: an OpenSSL connection object configured appropriately for the
given Twisted protocol.
@rtype: L{OpenSSL.SSL.Connection}
"""
class IOpenSSLClientConnectionCreator(Interface):
"""
A provider of L{IOpenSSLClientConnectionCreator} can create
L{OpenSSL.SSL.Connection} objects for TLS clients.
@see: L{twisted.internet.ssl}
@note: Creating OpenSSL connection objects is subtle, error-prone, and
security-critical. Before implementing this interface yourself,
consider using L{twisted.internet.ssl.optionsForClientTLS} as your
C{contextFactory}.
"""
def clientConnectionForTLS(tlsProtocol):
"""
Create a connection for the given client protocol.
@param tlsProtocol: the client protocol making the request.
@type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}.
@return: an OpenSSL connection object configured appropriately for the
given Twisted protocol.
@rtype: L{OpenSSL.SSL.Connection}
"""
class ITLSTransport(ITCPTransport):
"""
A TCP transport that supports switching to TLS midstream.
Once TLS mode is started the transport will implement L{ISSLTransport}.
"""
def startTLS(contextFactory):
"""
Initiate TLS negotiation.
@param contextFactory: An object which creates appropriately configured
TLS connections.
For clients, use L{twisted.internet.ssl.optionsForClientTLS}; for
servers, use L{twisted.internet.ssl.CertificateOptions}.
@type contextFactory: L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}, depending on whether this
L{ITLSTransport} is a server or not. If the appropriate interface
is not provided by the value given for C{contextFactory}, it must
be an old-style L{twisted.internet.ssl.ContextFactory} or similar.
"""
class ISSLTransport(ITCPTransport):
"""
A SSL/TLS based transport.
"""
def getPeerCertificate():
"""
Return an object with the peer's certificate info.
"""
class ICipher(Interface):
"""
A TLS cipher.
"""
fullName = Attribute(
"The fully qualified name of the cipher in L{unicode}."
)
class IAcceptableCiphers(Interface):
"""
A list of acceptable ciphers for a TLS context.
"""
def selectCiphers(availableCiphers):
"""
Choose which ciphers to allow to be negotiated on a TLS connection.
@param availableCiphers: A L{list} of L{ICipher} which gives the names
of all ciphers supported by the TLS implementation in use.
@return: A L{list} of L{ICipher} which represents the ciphers
which may be negotiated on the TLS connection. The result is
ordered by preference with more preferred ciphers appearing
earlier.
"""
class IProcessTransport(ITransport):
"""
A process transport.
"""
pid = Attribute(
"From before L{IProcessProtocol.makeConnection} is called to before "
"L{IProcessProtocol.processEnded} is called, C{pid} is an L{int} "
"giving the platform process ID of this process. C{pid} is L{None} "
"at all other times.")
def closeStdin():
"""
Close stdin after all data has been written out.
"""
def closeStdout():
"""
Close stdout.
"""
def closeStderr():
"""
Close stderr.
"""
def closeChildFD(descriptor):
"""
Close a file descriptor which is connected to the child process, identified
by its FD in the child process.
"""
def writeToChild(childFD, data):
"""
Similar to L{ITransport.write} but also allows the file descriptor in
the child process which will receive the bytes to be specified.
@type childFD: C{int}
@param childFD: The file descriptor to which to write.
@type data: C{str}
@param data: The bytes to write.
@return: C{None}
@raise KeyError: If C{childFD} is not a file descriptor that was mapped
in the child when L{IReactorProcess.spawnProcess} was used to create
it.
"""
def loseConnection():
"""
Close stdin, stderr and stdout.
"""
def signalProcess(signalID):
"""
Send a signal to the process.
@param signalID: can be
- one of C{"KILL"}, C{"TERM"}, or C{"INT"}.
These will be implemented in a
cross-platform manner, and so should be used
if possible.
- an integer, where it represents a POSIX
signal ID.
@raise twisted.internet.error.ProcessExitedAlready: If the process has
already exited.
@raise OSError: If the C{os.kill} call fails with an errno different
from C{ESRCH}.
"""
class IServiceCollection(Interface):
"""
An object which provides access to a collection of services.
"""
def getServiceNamed(serviceName):
"""
Retrieve the named service from this application.
Raise a C{KeyError} if there is no such service name.
"""
def addService(service):
"""
Add a service to this collection.
"""
def removeService(service):
"""
Remove a service from this collection.
"""
class IUDPTransport(Interface):
"""
Transport for UDP DatagramProtocols.
"""
def write(packet, addr=None):
"""
Write packet to given address.
@param addr: a tuple of (ip, port). For connected transports must
be the address the transport is connected to, or None.
In non-connected mode this is mandatory.
@raise twisted.internet.error.MessageLengthError: C{packet} was too
long.
"""
def connect(host, port):
"""
Connect the transport to an address.
This changes it to connected mode. Datagrams can only be sent to
this address, and will only be received from this address. In addition
the protocol's connectionRefused method might get called if destination
is not receiving datagrams.
@param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
@param port: port to connect to.
"""
def getHost():
"""
Get this port's host address.
@return: an address describing the listening port.
@rtype: L{IPv4Address} or L{IPv6Address}.
"""
def stopListening():
"""
Stop listening on this port.
If it does not complete immediately, will return L{Deferred} that fires
upon completion.
"""
def setBroadcastAllowed(enabled):
"""
Set whether this port may broadcast.
@param enabled: Whether the port may broadcast.
@type enabled: L{bool}
"""
def getBroadcastAllowed():
"""
Checks if broadcast is currently allowed on this port.
@return: Whether this port may broadcast.
@rtype: L{bool}
"""
class IUNIXDatagramTransport(Interface):
"""
Transport for UDP PacketProtocols.
"""
def write(packet, address):
"""
Write packet to given address.
"""
def getHost():
"""
Returns L{UNIXAddress}.
"""
class IUNIXDatagramConnectedTransport(Interface):
"""
Transport for UDP ConnectedPacketProtocols.
"""
def write(packet):
"""
Write packet to address we are connected to.
"""
def getHost():
"""
Returns L{UNIXAddress}.
"""
def getPeer():
"""
Returns L{UNIXAddress}.
"""
class IMulticastTransport(Interface):
"""
Additional functionality for multicast UDP.
"""
def getOutgoingInterface():
"""
Return interface of outgoing multicast packets.
"""
def setOutgoingInterface(addr):
"""
Set interface for outgoing multicast packets.
Returns Deferred of success.
"""
def getLoopbackMode():
"""
Return if loopback mode is enabled.
"""
def setLoopbackMode(mode):
"""
Set if loopback mode is enabled.
"""
def getTTL():
"""
Get time to live for multicast packets.
"""
def setTTL(ttl):
"""
Set time to live on multicast packets.
"""
def joinGroup(addr, interface=""):
"""
Join a multicast group. Returns L{Deferred} of success or failure.
If an error occurs, the returned L{Deferred} will fail with
L{error.MulticastJoinError}.
"""
def leaveGroup(addr, interface=""):
"""
Leave multicast group, return L{Deferred} of success.
"""
class IStreamClientEndpoint(Interface):
"""
A stream client endpoint is a place that L{ClientFactory} can connect to.
For example, a remote TCP host/port pair would be a TCP client endpoint.
@since: 10.1
"""
def connect(protocolFactory):
"""
Connect the C{protocolFactory} to the location specified by this
L{IStreamClientEndpoint} provider.
@param protocolFactory: A provider of L{IProtocolFactory}
@return: A L{Deferred} that results in an L{IProtocol} upon successful
connection otherwise a L{Failure} wrapping L{ConnectError} or
L{NoProtocol <twisted.internet.error.NoProtocol>}.
"""
class IStreamServerEndpoint(Interface):
"""
A stream server endpoint is a place that a L{Factory} can listen for
incoming connections.
@since: 10.1
"""
def listen(protocolFactory):
"""
Listen with C{protocolFactory} at the location specified by this
L{IStreamServerEndpoint} provider.
@param protocolFactory: A provider of L{IProtocolFactory}
@return: A L{Deferred} that results in an L{IListeningPort} or an
L{CannotListenError}
"""
class IStreamServerEndpointStringParser(Interface):
"""
An L{IStreamServerEndpointStringParser} is like an
L{IStreamClientEndpointStringParser}, except for L{IStreamServerEndpoint}s
instead of clients. It integrates with L{endpoints.serverFromString} in
much the same way.
"""
prefix = Attribute(
"""
@see: L{IStreamClientEndpointStringParser.prefix}
"""
)
def parseStreamServer(reactor, *args, **kwargs):
"""
Parse a stream server endpoint from a reactor and string-only arguments
and keyword arguments.
@see: L{IStreamClientEndpointStringParser.parseStreamClient}
@return: a stream server endpoint
@rtype: L{IStreamServerEndpoint}
"""
class IStreamClientEndpointStringParser(Interface):
"""
This interface is deprecated since Twisted 14.0; please use the
L{IStreamClientEndpointStringParserWithReactor} interface instead.
An L{IStreamClientEndpointStringParser} is a parser which can convert
a set of string C{*args} and C{**kwargs} into an L{IStreamClientEndpoint}
provider.
This interface is really only useful in the context of the plugin system
for L{endpoints.clientFromString}. See the document entitled "I{The
Twisted Plugin System}" for more details on how to write a plugin.
If you place an L{IStreamClientEndpointStringParser} plugin in the
C{twisted.plugins} package, that plugin's C{parseStreamClient} method will
be used to produce endpoints for any description string that begins with
the result of that L{IStreamClientEndpointStringParser}'s prefix attribute.
If a L{IStreamClientEndpointStringParserWithReactor} plugin and
L{IStreamClientEndpointStringParser} plugin share the same prefix, the
L{IStreamClientEndpointStringParserWithReactor} plugin will be preferred.
"""
prefix = Attribute(
"""
A C{str}, the description prefix to respond to. For example, an
L{IStreamClientEndpointStringParser} plugin which had C{"foo"} for its
C{prefix} attribute would be called for endpoint descriptions like
C{"foo:bar:baz"} or C{"foo:"}.
"""
)
def parseStreamClient(*args, **kwargs):
"""
This method is invoked by L{endpoints.clientFromString}, if the type of
endpoint matches the return value from this
L{IStreamClientEndpointStringParser}'s C{prefix} method.
@param args: The string arguments, minus the endpoint type, in the
endpoint description string, parsed according to the rules
described in L{endpoints.quoteStringArgument}. For example, if the
description were C{"my-type:foo:bar:baz=qux"}, C{args} would be
C{('foo','bar')}
@param kwargs: The string arguments from the endpoint description
passed as keyword arguments. For example, if the description were
C{"my-type:foo:bar:baz=qux"}, C{kwargs} would be
C{dict(baz='qux')}.
@return: a client endpoint
@rtype: L{IStreamClientEndpoint}
"""
deprecate.deprecatedModuleAttribute(
Version("Twisted", 14, 0, 0),
"This interface has been superseded by "
"IStreamClientEndpointStringParserWithReactor.",
__name__,
"IStreamClientEndpointStringParser")
class IStreamClientEndpointStringParserWithReactor(Interface):
"""
An L{IStreamClientEndpointStringParserWithReactor} is a parser which can
convert a set of string C{*args} and C{**kwargs} into an
L{IStreamClientEndpoint} provider. It's much like
L{IStreamClientEndpointStringParser}, except that the reactor is passed
along to L{parseStreamClient} too.
This interface is really only useful in the context of the plugin system
for L{endpoints.clientFromString}. See the document entitled "I{The
Twisted Plugin System}" for more details on how to write a plugin.
If you place an L{IStreamClientEndpointStringParserWithReactor} plugin in
the C{twisted.plugins} package, that plugin's C{parseStreamClient} method
will be used to produce endpoints for any description string that begins
with the result of that L{IStreamClientEndpointStringParserWithReactor}'s
prefix attribute.
If a L{IStreamClientEndpointStringParserWithReactor} plugin and
L{IStreamClientEndpointStringParser} plugin share the same prefix, the
L{IStreamClientEndpointStringParserWithReactor} plugin will be preferred.
"""
prefix = Attribute(
"""
L{bytes}, the description prefix to respond to. For example, an
L{IStreamClientEndpointStringParserWithReactor} plugin which had
C{b"foo"} for its C{prefix} attribute would be called for endpoint
descriptions like C{b"foo:bar:baz"} or C{b"foo:"}.
"""
)
def parseStreamClient(reactor, *args, **kwargs):
"""
This method is invoked by L{endpoints.clientFromString}, if the type of
endpoint matches the return value from this
L{IStreamClientEndpointStringParserWithReactor}'s C{prefix} method.
@param reactor: The reactor passed to L{endpoints.clientFromString}.
@param args: The byte string arguments, minus the endpoint type, in the
endpoint description string, parsed according to the rules
described in L{endpoints.quoteStringArgument}. For example, if the
description were C{b"my-type:foo:bar:baz=qux"}, C{args} would be
C{(b'foo', b'bar')}
@param kwargs: The byte string arguments from the endpoint description
passed as keyword arguments. For example, if the description were
C{b"my-type:foo:bar:baz=qux"}, C{kwargs} would be
C{dict(baz=b'qux')}.
@return: a client endpoint
@rtype: a provider of L{IStreamClientEndpoint}
"""
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
internal/pkg/build/sources/conveyorPacker_yum.go
|
// Copyright (c) 2018, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package sources
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/sylabs/singularity/internal/pkg/sylog"
"github.com/sylabs/singularity/pkg/build/types"
)
const (
yumConf = "/etc/bootstrap-yum.conf"
)
// YumConveyor holds stuff that needs to be packed into the bundle
type YumConveyor struct {
b *types.Bundle
rpmPath string
mirrorurl string
updateurl string
osversion string
include string
gpg string
httpProxy string
}
// YumConveyorPacker only needs to hold the conveyor to have the needed data to pack
type YumConveyorPacker struct {
YumConveyor
}
// Get downloads container information from the specified source
func (c *YumConveyor) Get(b *types.Bundle) (err error) {
c.b = b
// check for dnf or yum on system
var installCommandPath string
if installCommandPath, err = exec.LookPath("dnf"); err == nil {
sylog.Debugf("Found dnf at: %v", installCommandPath)
} else if installCommandPath, err = exec.LookPath("yum"); err == nil {
sylog.Debugf("Found yum at: %v", installCommandPath)
} else {
return fmt.Errorf("Neither yum nor dnf in PATH")
}
// check for rpm on system
err = c.getRPMPath()
if err != nil {
return fmt.Errorf("While checking rpm path: %v", err)
}
err = c.getBootstrapOptions()
if err != nil {
return fmt.Errorf("While getting bootstrap options: %v", err)
}
err = c.genYumConfig()
if err != nil {
return fmt.Errorf("While generating Yum config: %v", err)
}
err = c.copyPseudoDevices()
if err != nil {
return fmt.Errorf("While copying pseudo devices: %v", err)
}
args := []string{`--noplugins`, `-c`, filepath.Join(c.b.Rootfs(), yumConf), `--installroot`, c.b.Rootfs(), `--releasever=` + c.osversion, `-y`, `install`}
args = append(args, strings.Fields(c.include)...)
// Do the install
sylog.Debugf("\n\tInstall Command Path: %s\n\tDetected Arch: %s\n\tOSVersion: %s\n\tMirrorURL: %s\n\tUpdateURL: %s\n\tIncludes: %s\n", installCommandPath, runtime.GOARCH, c.osversion, c.mirrorurl, c.updateurl, c.include)
cmd := exec.Command(installCommandPath, args...)
// cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return fmt.Errorf("While bootstrapping: %v", err)
}
// clean up bootstrap packages
os.RemoveAll(filepath.Join(c.b.Rootfs(), "/var/cache/yum-bootstrap"))
return nil
}
// Pack puts relevant objects in a Bundle!
func (cp *YumConveyorPacker) Pack() (b *types.Bundle, err error) {
err = cp.insertBaseEnv()
if err != nil {
return nil, fmt.Errorf("While inserting base environment: %v", err)
}
err = cp.insertRunScript()
if err != nil {
return nil, fmt.Errorf("While inserting runscript: %v", err)
}
return cp.b, nil
}
func (c *YumConveyor) getRPMPath() (err error) {
c.rpmPath, err = exec.LookPath("rpm")
if err != nil {
return fmt.Errorf("RPM is not in PATH: %v", err)
}
output := &bytes.Buffer{}
cmd := exec.Command("rpm", "--showrc")
cmd.Stdout = output
if err = cmd.Run(); err != nil {
return
}
rpmDBPath := ""
scanner := bufio.NewScanner(output)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
// search for dbpath from showrc output
if strings.Contains(scanner.Text(), "_dbpath\t") {
// second field in the string is the path
rpmDBPath = strings.Fields(scanner.Text())[2]
}
}
if rpmDBPath == "" {
return fmt.Errorf("Could find dbpath")
} else if rpmDBPath != `%{_var}/lib/rpm` {
return fmt.Errorf("RPM database is using a weird path: %s\n"+
"You are probably running this bootstrap on Debian or Ubuntu.\n"+
"There is a way to work around this problem:\n"+
"Create a file at path %s/.rpmmacros.\n"+
"Place the following lines into the '.rpmmacros' file:\n"+
"%s\n"+
"%s\n"+
"After creating the file, re-run the bootstrap.\n"+
"More info: https://github.com/sylabs/singularity/issues/241\n",
rpmDBPath, os.Getenv("HOME"), `%_var /var`, `%_dbpath %{_var}/lib/rpm`)
}
return nil
}
func (c *YumConveyor) getBootstrapOptions() (err error) {
var ok bool
// look for http_proxy and gpg environment vars
c.gpg = os.Getenv("GPG")
c.httpProxy = os.Getenv("http_proxy")
// get mirrorURL, updateURL, OSVerison, and Includes components to definition
c.mirrorurl, ok = c.b.Recipe.Header["mirrorurl"]
if !ok {
return fmt.Errorf("Invalid yum header, no MirrorURL specified")
}
c.updateurl, _ = c.b.Recipe.Header["updateurl"]
// look for an OS version if a mirror specifies it
regex := regexp.MustCompile(`(?i)%{OSVERSION}`)
if regex.MatchString(c.mirrorurl) || regex.MatchString(c.updateurl) {
c.osversion, ok = c.b.Recipe.Header["osversion"]
if !ok {
return fmt.Errorf("Invalid yum header, OSVersion referenced in mirror but no OSVersion specified")
}
c.mirrorurl = regex.ReplaceAllString(c.mirrorurl, c.osversion)
c.updateurl = regex.ReplaceAllString(c.updateurl, c.osversion)
}
include, _ := c.b.Recipe.Header["include"]
// check for include environment variable and add it to requires string
include += ` ` + os.Getenv("INCLUDE")
// trim leading and trailing whitespace
include = strings.TrimSpace(include)
// add aa_base to start of include list by default
include = `/etc/redhat-release coreutils ` + include
c.include = include
return nil
}
func (c *YumConveyor) genYumConfig() (err error) {
fileContent := "[main]\n"
// http proxy
if c.httpProxy != "" {
fileContent += "proxy=" + c.httpProxy + "\n"
}
fileContent += "cachedir=/var/cache/yum-bootstrap\n"
fileContent += "keepcache=0\n"
fileContent += "debuglevel=2\n"
fileContent += "logfile=/var/log/yum.log\n"
fileContent += "syslog_device=/dev/null\n"
fileContent += "exactarch=1\n"
fileContent += "obsoletes=1\n"
// gpg
if c.gpg != "" {
fileContent += "gpgcheck=1\n"
} else {
fileContent += "gpgcheck=0\n"
}
fileContent += "plugins=1\n"
fileContent += "reposdir=0\n"
fileContent += "deltarpm=0\n"
fileContent += "\n"
fileContent += "[base]\n"
fileContent += "name=Linux $releasever - $basearch\n"
// mirror
if c.mirrorurl != "" {
fileContent += "baseurl=" + c.mirrorurl + "\n"
}
fileContent += "enabled=1\n"
// gpg
if c.gpg != "" {
fileContent += "gpgcheck=1\n"
} else {
fileContent += "gpgcheck=0\n"
}
// add update section if updateurl is specified
if c.updateurl != "" {
fileContent += "[updates]\n"
fileContent += "name=Linux $releasever - $basearch updates\n"
fileContent += "baseurl=" + c.updateurl + "\n"
fileContent += "enabled=1\n"
// gpg
if c.gpg != "" {
fileContent += "gpgcheck=1\n"
} else {
fileContent += "gpgcheck=0\n"
}
fileContent += "\n"
}
err = os.Mkdir(filepath.Join(c.b.Rootfs(), "/etc"), 0775)
if err != nil {
return fmt.Errorf("While creating %v: %v", filepath.Join(c.b.Rootfs(), "/etc"), err)
}
err = ioutil.WriteFile(filepath.Join(c.b.Rootfs(), yumConf), []byte(fileContent), 0664)
if err != nil {
return fmt.Errorf("While creating %v: %v", filepath.Join(c.b.Rootfs(), yumConf), err)
}
// if gpg key is specified, import it
if c.gpg != "" {
err = c.importGPGKey()
if err != nil {
return fmt.Errorf("While importing GPG key: %v", err)
}
} else {
sylog.Infof("Skipping GPG Key Import")
}
return nil
}
func (c *YumConveyor) importGPGKey() (err error) {
sylog.Infof("We have a GPG key! Preparing RPM database.")
// make sure gpg is being imported over https
if strings.HasPrefix(c.gpg, "https://") == false {
return fmt.Errorf("GPG key must be fetched with https")
}
// make sure curl is installed so rpm can import gpg key
if _, err = exec.LookPath("curl"); err != nil {
return fmt.Errorf("Neither yum nor dnf in PATH")
}
cmd := exec.Command(c.rpmPath, "--root", c.b.Rootfs(), "--initdb")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return fmt.Errorf("While initializing new rpm db: %v", err)
}
cmd = exec.Command(c.rpmPath, "--root", c.b.Rootfs(), "--import", c.gpg)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return fmt.Errorf("While importing GPG key with rpm: %v", err)
}
sylog.Infof("GPG key import complete!")
return nil
}
func (c *YumConveyor) copyPseudoDevices() (err error) {
err = os.Mkdir(filepath.Join(c.b.Rootfs(), "/dev"), 0775)
if err != nil {
return fmt.Errorf("While creating %v: %v", filepath.Join(c.b.Rootfs(), "/dev"), err)
}
devs := []string{"/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"}
for _, dev := range devs {
cmd := exec.Command("cp", "-a", dev, filepath.Join(c.b.Rootfs(), "/dev"))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
f, err := os.Create(c.b.Rootfs() + "/.singularity.d/runscript")
if err != nil {
return fmt.Errorf("While creating %v: %v", filepath.Join(c.b.Rootfs(), dev), err)
}
defer f.Close()
}
}
return nil
}
func (cp *YumConveyorPacker) insertBaseEnv() (err error) {
if err = makeBaseEnv(cp.b.Rootfs()); err != nil {
return
}
return nil
}
func (cp *YumConveyorPacker) insertRunScript() (err error) {
ioutil.WriteFile(filepath.Join(cp.b.Rootfs(), "/.singularity.d/runscript"), []byte("#!/bin/sh\n"), 0755)
if err != nil {
return
}
return nil
}
|
[
"\"HOME\"",
"\"GPG\"",
"\"http_proxy\"",
"\"INCLUDE\""
] |
[] |
[
"INCLUDE",
"GPG",
"HOME",
"http_proxy"
] |
[]
|
["INCLUDE", "GPG", "HOME", "http_proxy"]
|
go
| 4 | 0 | |
cmd/deploy.go
|
package cmd
import (
"fmt"
"kool-dev/kool/api"
"kool-dev/kool/tgz"
"os"
"os/exec"
"strings"
"time"
"github.com/spf13/cobra"
)
// DeployFlags holds the flags for the start command
type DeployFlags struct {
}
var deployCmd = &cobra.Command{
Use: "deploy",
Short: "Deploys your application usin Kool Dev",
Run: runDeploy,
}
var deployFlags = &DeployFlags{}
func init() {
rootCmd.AddCommand(deployCmd)
}
func runDeploy(cmd *cobra.Command, args []string) {
var (
filename string
deploy *api.Deploy
err error
)
if url := os.Getenv("KOOL_API_URL"); url != "" {
api.SetBaseURL(url)
}
fmt.Println("Create release file...")
filename, err = createReleaseFile()
if err != nil {
execError("", err)
os.Exit(1)
}
defer func(file string) {
var err error
if err = os.Remove(file); err != nil {
fmt.Println("error trying to remove temporary tarball:", err)
}
}(filename)
deploy = api.NewDeploy(filename)
fmt.Println("Upload release file...")
err = deploy.SendFile()
if err != nil {
execError("", err)
os.Exit(1)
}
fmt.Println("Going to deploy...")
var finishes chan bool = make(chan bool)
go func(deploy *api.Deploy, finishes chan bool) {
var lastStatus string
for {
err = deploy.GetStatus()
if lastStatus != deploy.Status {
lastStatus = deploy.Status
fmt.Println(" > deploy:", lastStatus)
}
if err != nil {
finishes <- false
execError("", err)
break
}
if deploy.IsSuccessful() {
finishes <- true
break
}
time.Sleep(time.Second * 3)
}
}(deploy, finishes)
var success bool
select {
case success = <-finishes:
{
if success {
fmt.Println("Deploy finished:", deploy.GetURL())
} else {
fmt.Println("Deploy failed.")
os.Exit(1)
}
break
}
case <-time.After(time.Minute * 10):
{
fmt.Println("timeout waiting deploy to finish")
break
}
}
}
func createReleaseFile() (filename string, err error) {
var (
tarball *tgz.TarGz
cwd string
)
tarball, err = tgz.NewTemp()
if err != nil {
return
}
var hasGit bool = true
if _, err = exec.LookPath("git"); err != nil {
hasGit = false
}
if _, err = os.Stat(".git"); hasGit && !os.IsNotExist(err) {
// we are in a Git environment
var (
output []byte
files []string
)
// Exclude list
// git ls-files -d // delete files
output, err = exec.Command("git", "ls-files", "-d").CombinedOutput()
if err != nil {
panic(fmt.Errorf("Failed listing deleted "))
}
tarball.SetIgnoreList(strings.Split(string(output), "\n"))
// Include list
// git ls-files -c
output, err = exec.Command("git", "ls-files", "-c").CombinedOutput()
if err != nil {
panic(fmt.Errorf("Failed list Git cached files"))
}
files = append(files, strings.Split(string(output), "\n")...)
// git ls-files -o --exclude-standard
output, err = exec.Command("git", "ls-files", "-o", "--exclude-standard").CombinedOutput()
if err != nil {
panic(fmt.Errorf("Failed list Git untracked non-ignored files"))
}
files = append(files, strings.Split(string(output), "\n")...)
filename, err = tarball.CompressFiles(files)
} else {
fmt.Println("Fallback to tarball full current working directory...")
cwd, _ = os.Getwd()
filename, err = tarball.CompressFolder(cwd)
}
return
}
|
[
"\"KOOL_API_URL\""
] |
[] |
[
"KOOL_API_URL"
] |
[]
|
["KOOL_API_URL"]
|
go
| 1 | 0 | |
internal/cli/server/server.go
|
// Package server provides the Epinio http server
package server
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/epinio/epinio/helpers/authtoken"
apiv1 "github.com/epinio/epinio/internal/api/v1"
"github.com/epinio/epinio/internal/api/v1/response"
"github.com/epinio/epinio/internal/auth"
"github.com/epinio/epinio/internal/cli/server/requestctx"
apierrors "github.com/epinio/epinio/pkg/api/core/v1/errors"
"github.com/alron/ginlogr"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/go-logr/logr"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/mattn/go-colorable"
"github.com/spf13/viper"
)
// NewHandler creates and setup the gin router
func NewHandler(logger logr.Logger) (*gin.Engine, error) {
// Support colors on Windows also
gin.DefaultWriter = colorable.NewColorableStdout()
gin.SetMode(gin.ReleaseMode)
// Endpoint structure ...
// | Path | Notes | Logging
// | --- | --- | ----
// | <Root>/... | API | Via "<Root>" Group
// | /ready | L/R Probes |
// | /namespaces/target/:namespace | ditto | ditto
router := gin.New()
router.HandleMethodNotAllowed = true
router.NoMethod(func(ctx *gin.Context) {
response.Error(ctx, apierrors.NewAPIError("Method not allowed", "", http.StatusMethodNotAllowed))
})
router.NoRoute(func(ctx *gin.Context) {
response.Error(ctx, apierrors.NewNotFoundError("Route not found"))
})
router.Use(gin.Recovery())
// Do not set header if nothing is specified.
accessControlAllowOrigin := strings.TrimSuffix(viper.GetString("access-control-allow-origin"), "/")
if accessControlAllowOrigin != "" {
router.Use(func(ctx *gin.Context) {
ctx.Header("Access-Control-Allow-Origin", accessControlAllowOrigin)
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Methods", "POST, PUT, PATCH, GET, OPTIONS, DELETE") // This cannot be a wildcard when `Access-Control-Allow-Credentials` is true
ctx.Header("Access-Control-Allow-Headers", "Authorization,x-api-csrf,content-type,file-size") // This cannot be a wildcard when `Access-Control-Allow-Credentials` is true
ctx.Header("Vary", "Origin") // Required when `Access-Control-Allow-Origin` is not a wildcard value
if ctx.Request.Method == "OPTIONS" {
// OPTIONS requests don't support `Authorization` headers, so return before we hit any checks
ctx.AbortWithStatus(http.StatusNoContent)
return
}
})
}
if os.Getenv("SESSION_KEY") == "" {
return nil, errors.New("SESSION_KEY environment variable not defined")
}
store := cookie.NewStore([]byte(os.Getenv("SESSION_KEY")))
store.Options(sessions.Options{MaxAge: 60 * 60 * 24}) // expire in a day
ginLogger := ginlogr.Ginlogr(logger, time.RFC3339, true)
ginRecoveryLogger := ginlogr.RecoveryWithLogr(logger, time.RFC3339, true, true)
// Register routes
// No authentication, no logging, no session. This is the healthcheck.
router.GET("/ready", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
})
// add common middlewares to all the routes
router.Use(
sessions.Sessions("epinio-session", store),
ginLogger,
ginRecoveryLogger,
initContextMiddleware(logger),
)
// Register api routes
{
apiRoutesGroup := router.Group(apiv1.Root, authMiddleware, sessionMiddleware)
apiv1.Lemon(apiRoutesGroup)
}
// Register web socket routes
{
wapiRoutesGroup := router.Group(apiv1.WsRoot, tokenAuthMiddleware)
apiv1.Spice(wapiRoutesGroup)
}
// print all registered routes
if logger.V(3).Enabled() {
for _, h := range router.Routes() {
logger.V(3).Info(fmt.Sprintf("%-6s %s", h.Method, h.Path))
}
}
return router, nil
}
// initContextMiddleware initialize the Request Context injecting the logger and the requestID
func initContextMiddleware(logger logr.Logger) gin.HandlerFunc {
return func(ctx *gin.Context) {
reqCtx := ctx.Request.Context()
requestID := uuid.NewString()
baseLogger := logger.WithValues("requestId", requestID)
reqCtx = requestctx.WithID(reqCtx, requestID)
reqCtx = requestctx.WithLogger(reqCtx, baseLogger)
ctx.Request = ctx.Request.WithContext(reqCtx)
}
}
// authMiddleware authenticates the user either using the session or if one
// doesn't exist, it authenticates with basic auth.
func authMiddleware(ctx *gin.Context) {
reqCtx := ctx.Request.Context()
logger := requestctx.Logger(reqCtx).WithName("AuthMiddleware")
// First get the available users
accounts, err := auth.GetUserAccounts(ctx)
if err != nil {
response.Error(ctx, apierrors.InternalError(err))
}
if len(*accounts) == 0 {
response.Error(ctx, apierrors.NewAPIError("no user found", "", http.StatusUnauthorized))
}
// We set this to the current user after successful authentication.
// This is also added to the context for controllers to use.
var user string
session := sessions.Default(ctx)
sessionUser := session.Get("user")
if sessionUser == nil { // no session exists, try basic auth
logger.V(1).Info("Basic auth authentication")
authHeader := string(ctx.GetHeader("Authorization"))
// If basic auth header is there, extract the user out of it
if authHeader != "" {
// A Basic auth header looks something like this:
// Basic base64_encoded_username:password_string
headerParts := strings.Split(authHeader, " ")
if len(headerParts) < 2 {
response.Error(ctx, apierrors.NewInternalError("Authorization header format was not expected"))
ctx.Abort()
return
}
creds, err := base64.StdEncoding.DecodeString(headerParts[1])
if err != nil {
response.Error(ctx, apierrors.NewInternalError("Couldn't decode auth header"))
ctx.Abort()
return
}
// creds is in username:password format
user = strings.Split(string(creds), ":")[0]
if user == "" {
response.Error(ctx, apierrors.NewInternalError("Couldn't extract user from the auth header"))
ctx.Abort()
return
}
}
// Perform basic auth authentication
gin.BasicAuth(*accounts)(ctx)
} else {
logger.V(1).Info("Session authentication")
var ok bool
user, ok = sessionUser.(string)
if !ok {
response.Error(ctx, apierrors.NewInternalError("Couldn't parse user from session"))
ctx.Abort()
return
}
// Check if that user still exists. If not delete the session and block the request!
// This allows us to kick out users even if they keep their browser open.
userStillExists := false
for checkUser := range *accounts {
if checkUser == user {
userStillExists = true
break
}
}
if !userStillExists {
session.Clear()
session.Options(sessions.Options{MaxAge: -1})
err := session.Save()
if err != nil {
response.Error(ctx, apierrors.NewInternalError("Couldn't save the session"))
ctx.Abort()
return
}
response.Error(ctx, apierrors.NewAPIError("User no longer exists. Session expired.", "", http.StatusUnauthorized))
ctx.Abort()
return
}
}
// Write the user info in the context. It's needed by the next middleware
// to write it into the session.
newCtx := ctx.Request.Context()
newCtx = requestctx.WithUser(newCtx, user)
ctx.Request = ctx.Request.WithContext(newCtx)
}
// sessionMiddleware creates a new session for a logged in user.
// This middleware is not called when authentication fails. That's because
// the authMiddleware calls "ctx.Abort()" in that case.
// We only set the user in session upon successful authentication
// (either basic auth or cookie based).
func sessionMiddleware(ctx *gin.Context) {
session := sessions.Default(ctx)
requestContext := ctx.Request.Context()
user := requestctx.User(requestContext)
if user == "" { // This can't be, authentication has succeeded.
response.Error(ctx, apierrors.NewInternalError("Couldn't set user in session after successful authentication. This can't happen."))
ctx.Abort()
return
}
if session.Get("user") == nil { // Only the first time after authentication success
session.Set("user", user)
session.Options(sessions.Options{
MaxAge: 172800, // Expire session every 2 days
Secure: true,
HttpOnly: true,
})
err := session.Save()
if err != nil {
response.Error(ctx, apierrors.NewInternalError("Couldn't save the session"))
ctx.Abort()
return
}
}
}
// tokenAuthMiddleware is only used to establish websocket connections for authenticated users
func tokenAuthMiddleware(ctx *gin.Context) {
logger := requestctx.Logger(ctx.Request.Context()).WithName("TokenAuthMiddleware")
logger.V(1).Info("Authtoken authentication")
token := ctx.Query("authtoken")
claims, err := authtoken.Validate(token)
if err != nil {
apiErr := apierrors.NewAPIError("unknown token validation error", "", http.StatusUnauthorized)
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
apiErr.Title = "malformed token format"
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
apiErr.Title = "token expired"
} else {
apiErr.Title = "cannot handle token"
}
}
// detailed log message
logger.V(2).Info(apiErr.Title, "error", err.Error())
// not too specific log message for unauthorized client
response.Error(ctx, apiErr)
ctx.Abort()
return
}
// we don't check if the user exists, token lifetime is small enough
newCtx := ctx.Request.Context()
newCtx = requestctx.WithUser(newCtx, claims.Username)
ctx.Request = ctx.Request.WithContext(newCtx)
}
|
[
"\"SESSION_KEY\"",
"\"SESSION_KEY\""
] |
[] |
[
"SESSION_KEY"
] |
[]
|
["SESSION_KEY"]
|
go
| 1 | 0 | |
tago/account/plan.py
|
import requests # Used to make HTTP requests
import json # Used to parse JSON
import os # Used to infer environment variables
API_TAGO = os.environ.get('TAGOIO_API') or 'https://api.tago.io'
REALTIME = os.environ.get('TAGOIO_REALTIME') or 'https://realtime.tago.io'
class Plan:
def __init__(self, acc_token):
self.token = acc_token
self.default_headers = {
'content-type': 'application/json', 'Account-Token': acc_token}
return
def setPlanParameters(self, data):
data = data if data else {}
return requests.post('{api_endpoint}/account/plan'.format(api_endpoint=API_TAGO), headers=self.default_headers, json=data).json()
def getPriceToUpdate(self, data):
return requests.get('{api_endpoint}/account/plan_value'.format(api_endpoint=API_TAGO), headers=self.default_headers, params=json.dumps(data)).json()
def getActivePlan(self):
return requests.get('{api_endpoint}/account/plan'.format(api_endpoint=API_TAGO), headers=self.default_headers).json()
def getCurrentPrices(self):
return requests.get('{api_endpoint}/pricing'.format(api_endpoint=API_TAGO), headers=self.default_headers).json()
def summary(self):
return requests.get('{api_endpoint}/billing'.format(api_endpoint=API_TAGO), headers=self.default_headers).json()
|
[] |
[] |
[
"TAGOIO_API",
"TAGOIO_REALTIME"
] |
[]
|
["TAGOIO_API", "TAGOIO_REALTIME"]
|
python
| 2 | 0 | |
biobb_adapters/pycompss/biobb_ml/classification/k_neighbors.py
|
# Python
import os
import sys
import traceback
# Pycompss
from pycompss.api.task import task
from pycompss.api.parameter import FILE_IN, FILE_OUT
# Adapters commons pycompss
from biobb_adapters.pycompss.biobb_commons import task_config
# Wrapped Biobb
from biobb_ml.classification.k_neighbors import KNeighborsTrain # Importing class instead of module to avoid name collision
task_time_out = int(os.environ.get('TASK_TIME_OUT', 0))
@task(input_dataset_path=FILE_IN, output_model_path=FILE_OUT, output_test_table_path=FILE_OUT, output_plot_path=FILE_OUT,
on_failure="IGNORE", time_out=task_time_out)
def _kneighborstrain(input_dataset_path, output_model_path, output_test_table_path, output_plot_path, properties, **kwargs):
task_config.pop_pmi(os.environ)
try:
KNeighborsTrain(input_dataset_path=input_dataset_path, output_model_path=output_model_path, output_test_table_path=output_test_table_path, output_plot_path=output_plot_path, properties=properties, **kwargs).launch()
except Exception as e:
traceback.print_exc()
raise e
finally:
sys.stdout.flush()
sys.stderr.flush()
def k_neighbors(input_dataset_path, output_model_path, output_test_table_path=None, output_plot_path=None, properties=None, **kwargs):
if (output_model_path is None or os.path.exists(output_model_path)) and \
(output_test_table_path is None or os.path.exists(output_test_table_path)) and \
(output_plot_path is None or os.path.exists(output_plot_path)) and \
True:
print("WARN: Task KNeighborsTrain already executed.")
else:
_kneighborstrain( input_dataset_path, output_model_path, output_test_table_path, output_plot_path, properties, **kwargs)
|
[] |
[] |
[
"TASK_TIME_OUT"
] |
[]
|
["TASK_TIME_OUT"]
|
python
| 1 | 0 | |
sample_config.py
|
import os
import time
class Config(object):
# Get a bot token from botfather
TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
# Get from my.telegram.org (or @UseTGXBot)
API_ID = int(os.environ.get("API_ID", 12345))
# Get from my.telegram.org (or @UseTGXBot)
API_HASH = os.environ.get("API_HASH", "9415a61fedcc0f00f33667ca46e577a3")
# Database URL from https://cloud.mongodb.com/
DATABASE_URI = os.environ.get("DATABASE_URI", "")
# Your database name from mongoDB
DATABASE_NAME = str(os.environ.get("DATABASE_NAME", "Cluster0"))
# ID of users that can use the bot commands
AUTH_USERS = set(str(x) for x in os.environ.get("AUTH_USERS", "").split())
# To save user details (Usefull for getting userinfo and total user counts)
# May reduce filter capacity :(
# Give yes or no
SAVE_USER = os.environ.get("SAVE_USER", "no").lower()
# Go to https://dashboard.heroku.com/account, scroll down and press Reveal API
# To check dyno status
HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", "")
# To record start time of bot
BOT_START_TIME = time.time()
|
[] |
[] |
[
"SAVE_USER",
"AUTH_USERS",
"DATABASE_NAME",
"DATABASE_URI",
"TG_BOT_TOKEN",
"HEROKU_API_KEY",
"API_ID",
"API_HASH"
] |
[]
|
["SAVE_USER", "AUTH_USERS", "DATABASE_NAME", "DATABASE_URI", "TG_BOT_TOKEN", "HEROKU_API_KEY", "API_ID", "API_HASH"]
|
python
| 8 | 0 | |
vagrant/__init__.py
|
'''
Python bindings for working with Vagrant and Vagrantfiles. Do useful things
with the `vagrant` CLI without the boilerplate (and errors) of calling
`vagrant` and parsing the results.
The API attempts to conform closely to the API of the `vagrant` command line,
including method names and parameter names.
Documentation of usage, testing, installation, etc., can be found at
https://github.com/todddeluca/python-vagrant.
'''
import collections
import os
import re
import subprocess
import sys
import logging
# python package version
# should match r"^__version__ = '(?P<version>[^']+)'$" for setup.py
__version__ = '0.5.0'
log = logging.getLogger(__name__)
VAGRANT_NOT_FOUND_WARNING = 'The Vagrant executable cannot be found. ' \
'Please check if it is in the system path.'
def which(program):
'''
Emulate unix 'which' command. If program is a path to an executable file
(i.e. it contains any directory components, like './myscript'), return
program. Otherwise, if an executable file matching program is found in one
of the directories in the PATH environment variable, return the first match
found.
On Windows, if PATHEXT is defined and program does not include an
extension, include the extensions in PATHEXT when searching for a matching
executable file.
Return None if no executable file is found.
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
https://github.com/webcoyote/vagrant/blob/f70507062e3b30c00db1f0d8b90f9245c4c997d4/lib/vagrant/util/file_util.rb
'''
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# If program contains any dir components, do not search the path
# e.g. './backup', '/bin/ls'
if os.path.dirname(program):
if is_exe(program):
return program
else:
return None
# Only search PATH if there is one to search.
if 'PATH' not in os.environ:
return None
# Are we on windows?
# http://stackoverflow.com/questions/1325581/how-do-i-check-if-im-running-on-windows-in-python
windows = (os.name == 'nt')
# Does program have an extension?
has_ext = os.path.splitext(program)[1]
if windows and not has_ext:
# If windows and no extension, search for program + ext for each
# extension in PATHEXT. http://environmentvariables.org/PathExt
# e.g. ['.EXE', '.CMD', '.BAT']
exts = os.environ.get('PATHEXT', '').split(';')
else:
# Otherwise, just search for program
exts = ['']
programs = [program + ext for ext in exts]
for path in os.environ['PATH'].split(os.pathsep):
for p in programs:
fpath = os.path.join(path, p)
if is_exe(fpath):
return fpath
return None
# The full path to the vagrant executable, e.g. '/usr/bin/vagrant'
def get_vagrant_executable():
return which('vagrant')
if get_vagrant_executable() is None:
log.warn(VAGRANT_NOT_FOUND_WARNING)
# Classes for listings of Statuses, Boxes, and Plugins
Status = collections.namedtuple('Status', ['name', 'state', 'provider'])
Box = collections.namedtuple('Box', ['name', 'provider', 'version'])
Plugin = collections.namedtuple('Plugin', ['name', 'version', 'system'])
class Vagrant(object):
'''
Object to up (launch) and destroy (terminate) vagrant virtual machines,
to check the status of the machine and to report on the configuration
of the machine.
Works by using the `vagrant` executable and a `Vagrantfile`.
'''
# statuses
RUNNING = 'running' # vagrant up
NOT_CREATED = 'not created' # vagrant destroy
POWEROFF = 'poweroff' # vagrant halt
ABORTED = 'aborted' # The VM is in an aborted state
SAVED = 'saved' # vagrant suspend
# LXC statuses
STOPPED = 'stopped'
FROZEN = 'frozen'
STATUSES = (RUNNING, NOT_CREATED, POWEROFF, ABORTED, SAVED, STOPPED, FROZEN)
BASE_BOXES = {
'ubuntu-Lucid32': 'http://files.vagrantup.com/lucid32.box',
'ubuntu-lucid32': 'http://files.vagrantup.com/lucid32.box',
'ubuntu-lucid64': 'http://files.vagrantup.com/lucid64.box',
'ubuntu-precise32': 'http://files.vagrantup.com/precise32.box',
'ubuntu-precise64': 'http://files.vagrantup.com/precise64.box',
}
def __init__(self, root=None, quiet_stdout=True, quiet_stderr=True):
'''
root: a directory containing a file named Vagrantfile. Defaults to
os.getcwd(). This is the directory and Vagrantfile that the Vagrant
instance will operate on.
quiet_stdout: If True, the stdout of vagrant commands whose output is
not captured for further processing will be sent to devnull.
quiet_stderr: If True, the stderr of vagrant commands whose output is
not captured for further processing will be sent to devnull.
'''
self.root = os.path.abspath(root) if root is not None else os.getcwd()
self._cached_conf = {}
self._vagrant_exe = None # cache vagrant executable path
self.quiet_stdout = quiet_stdout
self.quiet_stderr = quiet_stderr
def version(self):
'''
Return the installed vagrant version, as a string, e.g. '1.5.0'
'''
output = self._run_vagrant_command(['--version'])
m = re.search(r'^Vagrant (?P<version>.+)$', output)
if m is None:
raise Exception('Failed to parse vagrant --version output. output={!r}'.format(output))
return m.group('version')
def init(self, box_name=None, box_url=None):
'''
From the Vagrant docs:
This initializes the current directory to be a Vagrant environment by
creating an initial Vagrantfile if one doesn't already exist.
If box_name is given, it will prepopulate the config.vm.box setting in
the created Vagrantfile.
If box_url is given, it will prepopulate the config.vm.box_url setting
in the created Vagrantfile.
Note: if box_url is given, box_name should also be given.
'''
self._call_vagrant_command(['init', box_name, box_url])
def up(self, no_provision=False, provider=None, vm_name=None,
provision=None, provision_with=None):
'''
Launch the Vagrant box.
provision_with: optional list of provisioners to enable.
provider: Back the machine with a specific provider
no_provision: if True, disable provisioning. Same as 'provision=False'.
provision: optional boolean. Enable or disable provisioning. Default
behavior is to use the underlying vagrant default.
Note: If provision and no_provision are not None, no_provision will be
ignored.
'''
provider_arg = '--provider=%s' % provider if provider else None
prov_with_arg = None if provision_with is None else '--provision-with'
providers_arg = None if provision_with is None else ','.join(provision_with)
# For the sake of backward compatibility, no_provision is allowed.
# However it is ignored if provision is set.
if provision is not None:
no_provision = None
no_provision_arg = '--no-provision' if no_provision else None
provision_arg = None if provision is None else '--provision' if provision else '--no-provision'
self._call_vagrant_command(['up', vm_name, no_provision_arg,
provision_arg, provider_arg,
prov_with_arg, providers_arg])
try:
self.conf(vm_name=vm_name) # cache configuration
except subprocess.CalledProcessError:
# in multi-VM environments, up() can be used to start all VMs,
# however vm_name is required for conf() or ssh_config().
pass
def provision(self, vm_name=None, provision_with=None):
'''
Runs the provisioners defined in the Vagrantfile.
vm_name: optional VM name string.
provision_with: optional list of provisioners to enable.
e.g. ['shell', 'chef_solo']
'''
prov_with_arg = None if provision_with is None else '--provision-with'
providers_arg = None if provision_with is None else ','.join(provision_with)
self._call_vagrant_command(['provision', vm_name, prov_with_arg,
providers_arg])
def reload(self, vm_name=None, provision=None, provision_with=None):
'''
Quoting from Vagrant docs:
> The equivalent of running a halt followed by an up.
> This command is usually required for changes made in the Vagrantfile to take effect. After making any modifications to the Vagrantfile, a reload should be called.
> The configured provisioners will not run again, by default. You can force the provisioners to re-run by specifying the --provision flag.
provision: optional boolean. Enable or disable provisioning. Default
behavior is to use the underlying vagrant default.
provision_with: optional list of provisioners to enable.
e.g. ['shell', 'chef_solo']
'''
prov_with_arg = None if provision_with is None else '--provision-with'
providers_arg = None if provision_with is None else ','.join(provision_with)
provision_arg = None if provision is None else '--provision' if provision else '--no-provision'
self._call_vagrant_command(['reload', vm_name, provision_arg,
prov_with_arg, providers_arg])
def suspend(self, vm_name=None):
'''
Suspend/save the machine.
'''
self._call_vagrant_command(['suspend', vm_name])
self._cached_conf[vm_name] = None # remove cached configuration
def halt(self, vm_name=None, force=False):
'''
Halt the Vagrant box.
force: If True, force shut down.
'''
force_opt = '--force' if force else None
self._call_vagrant_command(['halt', vm_name, force_opt])
self._cached_conf[vm_name] = None # remove cached configuration
def destroy(self, vm_name=None):
'''
Terminate the running Vagrant box.
'''
self._call_vagrant_command(['destroy', vm_name, '--force'])
self._cached_conf[vm_name] = None # remove cached configuration
def status(self, vm_name=None):
'''
Return the results of a `vagrant status` call as a list of one or more
Status objects. A Status contains the following attributes:
- name: The VM name in a multi-vm environment. 'default' otherwise.
- state: The state of the underlying guest machine (i.e. VM).
- provider: the name of the VM provider, e.g. 'virtualbox'. None
if no provider is output by vagrant.
This information corresponds with the current return values from running
`vagrant status`, as of Vagrant 1.5.
Example return values for a multi-VM environment:
[Status(name='web', state='not created', provider='virtualbox'),
Status(name='db', state='not created', provider='virtualbox')]
And for a single-VM environment:
[Status(name='default', state='not created', provider='virtualbox')]
Possible states include, but are not limited to (since new states are
being added as Vagrant evolves):
- 'not created' if the vm is destroyed
- 'running' if the vm is up
- 'poweroff' if the vm is halted
- 'saved' if the vm is suspended
- 'aborted' if the vm is aborted
- None if no status is found
As of Vagrant 1.1.0, vagrant has started supporting providers (like
virtualbox and vmware_fusion) and has started adding the provider in
the status string, like 'not created (virtualbox)'.
Implementation notes:
- The human-readable output of vagrant lists the vm name as 'default'
in a single vm environment. This is in contrast to the
Machine-readable output from vagrant, which lists the vm name
(a.k.a. target) as '' in a single VM environment.
- The human readable states differ from machine readable states. For
example, 'not created' versus 'not_created'. In order to future-proof
code using python-vagrant, use the status constants defined in the
Vagrant class instead of hardcoding the string. At some point
parsing will switch from using the human-readable output to the
machine readable output and the state values might change as well.
'''
# example output (without provdier):
# Current VM states:
#
# default poweroff
#
# The VM is powered off. To restart the VM, simply run `vagrant up`
# example multi-VM environment output (with provider):
# Current machine states:
#
# web not created (virtualbox)
# db not created (virtualbox)
#
# This environment represents multiple VMs. The VMs are all listed
# above with their current state. For more information about a specific
# VM, run `vagrant status NAME`.
output = self._run_vagrant_command(['status', vm_name])
# The format of output is expected to be a
# - "Current VM states:" line (vagrant 1)
# - "Current machine states" line (vagrant 1.1)
# followed by a blank line, followed by one or more status lines,
# followed by a blank line.
# Parsing the output of `vagrant status`
# Currently parsing is constrained to known states. Otherwise how
# could we know where the VM name ends and the state begins.
# Once --machine-readable output is stable (a work in progress as of
# Vagrant 1.5), this constraint can be lifted.
START_LINE, FIRST_BLANK, VM_STATUS = 1, 2, 3
statuses = []
parse_state = START_LINE # looking for for the 'Current ... states' line
for line in output.splitlines():
line = line.strip()
if parse_state == START_LINE and re.search('^Current (VM|machine) states:', line):
parse_state = FIRST_BLANK # looking for the first blank line
elif parse_state == FIRST_BLANK and not line:
parse_state = VM_STATUS # looking for machine status lines
elif parse_state == VM_STATUS and line:
vm_name_and_state, provider = self._parse_provider_line(line)
# Split vm_name from status. Only works for recognized states.
m = re.search(r'^(?P<vm_name>.*?)\s+(?P<state>' +
'|'.join(self.STATUSES) + ')$',
vm_name_and_state)
if not m:
raise Exception('ParseError: Failed to properly parse vm name and status from line.',
line, output)
else:
status = Status(m.group('vm_name'), m.group('state'), provider)
statuses.append(status)
elif parse_state == VM_STATUS and not line:
# Found the second blank line. All done.
break
return statuses
def conf(self, ssh_config=None, vm_name=None):
'''
Parse ssh_config into a dict containing the keys defined in ssh_config,
which should include these keys (listed with example values): 'User'
(e.g. 'vagrant'), 'HostName' (e.g. 'localhost'), 'Port' (e.g. '2222'),
'IdentityFile' (e.g. '/home/todd/.ssh/id_dsa'). Cache the parsed
configuration dict. Return the dict.
If ssh_config is not given, return the cached dict. If there is no
cached configuration, call ssh_config() to get the configuration, then
parse, cache, and return the config dict. Calling ssh_config() raises
an Exception if the Vagrant box has not yet been created or has been
destroyed.
vm_name: required in a Multi-VM Vagrant environment. This name will be
used to get the configuration for the named vm and associate the config
with the vm name in the cache.
ssh_config: a valid ssh confige file host section. Defaults to
the value returned from ssh_config(). For speed, the configuration
parsed from ssh_config is cached for subsequent calls.
'''
if self._cached_conf.get(vm_name) is None or ssh_config is not None:
if ssh_config is None:
ssh_config = self.ssh_config(vm_name=vm_name)
conf = self._parse_config(ssh_config)
self._cached_conf[vm_name] = conf
return self._cached_conf[vm_name]
def ssh_config(self, vm_name=None):
'''
Return the output of 'vagrant ssh-config' which appears to be a valid
Host section suitable for use in an ssh config file.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
vm_name: required in a multi-VM environment.
Example output:
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/todd/.vagrant.d/insecure_private_key
IdentitiesOnly yes
'''
# capture ssh configuration from vagrant
return self._run_vagrant_command(['ssh-config', vm_name])
def user(self, vm_name=None):
'''
Return the ssh user of the vagrant box, e.g. 'vagrant'
or None if there is no user in the ssh_config.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
'''
return self.conf(vm_name=vm_name).get('User')
def hostname(self, vm_name=None):
'''
Return the vagrant box hostname, e.g. '127.0.0.1'
or None if there is no hostname in the ssh_config.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
'''
return self.conf(vm_name=vm_name).get('HostName')
def port(self, vm_name=None):
'''
Return the vagrant box ssh port, e.g. '2222'
or None if there is no port in the ssh_config.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
'''
return self.conf(vm_name=vm_name).get('Port')
def keyfile(self, vm_name=None):
'''
Return the path to the private key used to log in to the vagrant box
or None if there is no keyfile (IdentityFile) in the ssh_config.
E.g. '/Users/todd/.vagrant.d/insecure_private_key'
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
KeyFile is a synonym for IdentityFile.
'''
return self.conf(vm_name=vm_name).get('IdentityFile')
def user_hostname(self, vm_name=None):
'''
Return a string combining user and hostname, e.g. '[email protected]'.
This string is suitable for use in an ssh commmand. If user is None
or empty, it will be left out of the string, e.g. 'localhost'. If
hostname is None, have bigger problems.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
'''
user = self.user(vm_name=vm_name)
user_prefix = user + '@' if user else ''
return user_prefix + self.hostname(vm_name=vm_name)
def user_hostname_port(self, vm_name=None):
'''
Return a string combining user, hostname and port, e.g.
'[email protected]:2222'. This string is suitable for use with Fabric,
in env.hosts. If user or port is None or empty, they will be left
out of the string. E.g. 'vagrant@localhost', or 'localhost:2222' or
'localhost'. If hostname is None, you have bigger problems.
Raises an Exception if the Vagrant box has not yet been created or
has been destroyed.
'''
user = self.user(vm_name=vm_name)
port = self.port(vm_name=vm_name)
user_prefix = user + '@' if user else ''
port_suffix = ':' + port if port else ''
return user_prefix + self.hostname(vm_name=vm_name) + port_suffix
def box_add(self, name, url, provider=None, force=False):
'''
Adds a box with given name, from given url.
force: If True, overwrite an existing box if it exists.
'''
force_opt = '--force' if force else None
cmd = ['box', 'add', name, url, force_opt]
if provider is not None:
cmd += ['--provider', provider]
self._call_vagrant_command(cmd)
def box_list(self):
'''
Run `vagrant box list` and return a list of Box objects containing the
results. A Box object has the following attributes:
- name: the box-name.
- provider: the box-provider.
- version: the box-version.
Example output:
[Box(name='precise32', provider='virtualbox', version=None),
Box(name='precise64', provider='virtualbox', version=None),
Box(name='trusty64', provider='virtualbox', version=None)]
Implementation Notes:
- The box-version is not currently returned, since we parse the
human-readable vagrant output, where it is not listed. As of Vagrant
1.5 (or 1.4?) is is available in the --machine-readable output.
Once parsing is switched to use that output, it will be available.
- As of Vagrant >= 1.1, boxes are listed with names and providers.
'''
output = self._run_vagrant_command(['box', 'list'])
boxes = []
for line in output.splitlines():
name, provider = self._parse_provider_line(line)
box = Box(name, provider, version=None) # not currently parsing the box version
boxes.append(box)
return boxes
def box_remove(self, name, provider):
'''
Removes the box matching name and provider. It is an error if no box
matches name and provider.
'''
self._call_vagrant_command(['box', 'remove', name, provider])
def plugin_list(self):
'''
Return a list of Plugin objects containing the following information
about installed plugins:
- name: The plugin name, as a string.
- version: The plugin version, as a string.
- system: A boolean, presumably indicating whether this plugin is a
"core" part of vagrant, though the feature is not yet documented
in the Vagrant 1.5 docs.
Example output:
[Plugin(name='sahara', version='0.0.16', system=False),
Plugin(name='vagrant-login', version='1.0.1', system=True),
Plugin(name='vagrant-share', version='1.0.1', system=True)]
'''
output = self._run_vagrant_command(['plugin', 'list'])
return [self._parse_plugin_list_line(l) for l in output.splitlines()]
def _parse_plugin_list_line(self, line):
# As of Vagrant 1.5, the format of the `vagrant plugin list` command can
# be inferred here:
# https://github.com/mitchellh/vagrant/blob/master/plugins/commands/plugin/action/list_plugins.rb#L35
# Example plugin listing lines:
# sahara (0.0.16)
# vagrant-login (1.0.1, system)
regex = re.compile(r'^(?P<name>.+?)\s+\((?P<version>.+?)(?P<system>, system)?\)$')
m = regex.search(line)
if m is None:
raise Exception('Error parsing plugin listing line.', line)
else:
return Plugin(m.group('name'), m.group('version'), bool(m.group('system')))
def _parse_provider_line(self, line):
'''
In vagrant 1.1+, `vagrant box list` produces lines like:
precise32 (virtualbox)
And `vagrant status` produces lines like:
default not created (virtualbox)
Pre-1.1 version of vagrant produce lines without a provider
in parentheses. This helper function separates the beginning of the
line from the provider at the end of the line. It assumes that the
provider is surrounded by parentheses (and contains no parentheses.
It returns the beginning of the line (trimmed of whitespace) and
the provider (or None if the line has no provider).
Example outputs:
('precise32', 'virtualbox')
('default not created', 'virtualbox')
'''
m = re.search(r'^\s*(?P<value>.+?)\s+\((?P<provider>[^)]+)\)\s*$',
line)
if m:
return m.group('value'), m.group('provider')
else:
return line.strip(), None
def _parse_config(self, ssh_config):
'''
This lame parser does not parse the full grammar of an ssh config
file. It makes assumptions that are (hopefully) correct for the output
of `vagrant ssh-config [vm-name]`. Specifically it assumes that there
is only one Host section, the default vagrant host. It assumes that
the parameters of the ssh config are not changing.
every line is of the form 'key value', where key is a single token
without any whitespace and value is the remaining part of the line.
Value may optionally be surrounded in double quotes. All leading and
trailing whitespace is removed from key and value. Example lines:
' User vagrant\n'
' IdentityFile "/home/robert/.vagrant.d/insecure_private_key"\n'
Lines with '#' as the first non-whitespace character are considered
comments and ignored. Whitespace-only lines are ignored. This parser
does NOT handle using an '=' in options. Values surrounded in double
quotes will have the double quotes removed.
See https://github.com/bitprophet/ssh/blob/master/ssh/config.py for a
more compliant ssh config file parser.
'''
conf = dict()
started_parsing = False
for line in ssh_config.splitlines():
if line.strip().startswith('Host ') and not started_parsing:
started_parsing = True
if not started_parsing or not line.strip() or line.strip().startswith('#'):
continue
key, value = line.strip().split(None, 1)
# Remove leading and trailing " from the values
conf[key] = value.strip('"')
return conf
def _make_vagrant_command(self, args):
if self._vagrant_exe is None:
self._vagrant_exe = get_vagrant_executable()
if not self._vagrant_exe:
raise RuntimeError(VAGRANT_NOT_FOUND_WARNING)
# filter out None args. Since vm_name is None in non-Multi-VM
# environments, this quitely removes it from the arguments list
# when it is not specified.
return [self._vagrant_exe] + [arg for arg in args if arg is not None]
def _call_vagrant_command(self, args):
'''
Run a vagrant command. Return None.
args: A sequence of arguments to a vagrant command line.
'''
# Make subprocess command
command = self._make_vagrant_command(args)
if self.quiet_stdout or self.quiet_stderr:
# Redirect stdout and/or stderr to devnull
# Use with stmt to close filehandle in case of exception
with open(os.devnull, 'wb') as fh:
outfh = fh if self.quiet_stdout else sys.stdout
errfh = fh if self.quiet_stderr else sys.stderr
subprocess.check_call(command, cwd=self.root,
stdout=outfh, stderr=errfh)
else:
subprocess.check_call(command, cwd=self.root)
def _run_vagrant_command(self, args):
'''
Run a vagrant command and return its stdout.
args: A sequence of arguments to a vagrant command line.
e.g. ['up', 'my_vm_name', '--no-provision'] or
['up', None, '--no-provision'] for a non-Multi-VM environment.
'''
# Make subprocess command
command = self._make_vagrant_command(args)
return subprocess.check_output(command, cwd=self.root)
class SandboxVagrant(Vagrant):
'''
Support for sandbox mode using the Sahara gem (https://github.com/jedi4ever/sahara).
'''
def _run_sandbox_command(self, args):
return self._run_vagrant_command(['sandbox'] + list(args))
def sandbox_commit(self, vm_name=None):
'''
Permanently writes all the changes made to the VM.
'''
self._run_sandbox_command(['commit', vm_name])
def sandbox_off(self, vm_name=None):
'''
Disables the sandbox mode.
'''
self._run_sandbox_command(['off', vm_name])
def sandbox_on(self, vm_name=None):
'''
Enables the sandbox mode.
This requires the Sahara gem to be installed
(https://github.com/jedi4ever/sahara).
'''
self._run_sandbox_command(['on', vm_name])
def sandbox_rollback(self, vm_name=None):
'''
Reverts all the changes made to the VM since the last commit.
'''
self._run_sandbox_command(['rollback', vm_name])
def sandbox_status(self, vm_name=None):
'''
Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed
'''
vagrant_sandbox_output = self._run_sandbox_command(['status', vm_name])
return self._parse_vagrant_sandbox_status(vagrant_sandbox_output)
def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
'''
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the box VM is down
tokens = [token.strip() for token in vagrant_output.split(' ')]
if tokens[0] == 'Usage:':
sahara_status = 'not installed'
elif "{} {}".format(tokens[-2], tokens[-1]) == 'not created':
sahara_status = 'unknown'
else:
sahara_status = tokens[-1]
return sahara_status
|
[] |
[] |
[
"PATH",
"PATHEXT"
] |
[]
|
["PATH", "PATHEXT"]
|
python
| 2 | 0 | |
geminidr/doc/tutorials/GMOSImg-DRTutorial/conf.py
|
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
on_rtd = os.environ.get('READTHEDOCS') == 'True'
relative_path = './../../../../'
dragons_path = os.path.normpath(os.path.join(os.getcwd(), relative_path))
sys.path.append(dragons_path)
import astrodata
print('\n Printing current working directory for debugging:')
print((' Current working directory: {}'.format(os.getcwd())))
print((' Dragons path: {}\n'.format(dragons_path)))
# -- Project information -----------------------------------------------------
project = 'DRAGONS Tutorial<br> GMOS Imaging Data Reduction'
copyright = '2020, Association of Universities for Research in Astronomy'
author = 'Bruno C. Quint, Kathleen Labrie'
# The short X.Y version
version = astrodata.version(short=True)
# The full version, including alpha/beta/rc tags
release = astrodata.version()
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.8'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
today = 'April 2020'
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# hello world
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'DRAGONSTutorial-GMOStut'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'DRAGONSTutorial-GMOStut.tex', 'DRAGONS Tutorial - GMOS Data Reduction',
'Bruno Quint, Kathleen Labrie', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'dragonstutorial-gmos', 'DRAGONS Tutorial - GMOS Data Reduction',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [(
master_doc,
'DRAGONSTutorial-GMOSDataReduction',
'DRAGONS Tutorial - GMOS Data Reduction',
author,
'DRAGONSTutorial-GMOS',
'A quick tutorial on how to reduce GMOS images with the DRAGONS command line tools',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'astrodata': ('https://astrodata-user-manual.readthedocs.io/en/latest/', None),
'astropy': ('http://docs.astropy.org/en/stable/', None),
'gemini_instruments': ('https://dragons-recipe-system-programmers-manual.readthedocs.io/en/latest/', None),
'geminidr': ('https://dragons-recipe-system-programmers-manual.readthedocs.io/en/latest/', None),
'matplotlib': ('https://matplotlib.org/', None),
'numpy': ('https://docs.scipy.org/doc/numpy/', None),
'python': ('https://docs.python.org/3', None),
}
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Finishing with a setup that will run always -----------------------------
def setup(app):
# -- Adding custom styles ---
app.add_css_file('css/code.xref-styles.css')
app.add_css_file('css/todo-styles.css')
app.add_css_file('css/copy_code_block.css')
# -- Adding custom behavior ---
# -- Will leave this out for now until I manage to get the behavior I want
# app.add_js_file('js/copy_code_block.js')
# app.add_js_file('https://cdn.jsdelivr.net/npm/clipboard@1/dist/clipboard.min.js')
|
[] |
[] |
[
"READTHEDOCS"
] |
[]
|
["READTHEDOCS"]
|
python
| 1 | 0 | |
tests/unit/gapic/bigtable_v2/test_bigtable.py
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import mock
import grpc
from grpc.experimental import aio
import math
import pytest
from proto.marshal.rules.dates import DurationRule, TimestampRule
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.bigtable_v2.services.bigtable import BigtableAsyncClient
from google.cloud.bigtable_v2.services.bigtable import BigtableClient
from google.cloud.bigtable_v2.services.bigtable import transports
from google.cloud.bigtable_v2.types import bigtable
from google.cloud.bigtable_v2.types import data
from google.oauth2 import service_account
import google.auth
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
# If default endpoint is localhost, then default mtls endpoint will be the same.
# This method modifies the default endpoint so the client can produce a different
# mtls endpoint for endpoint testing purposes.
def modify_default_endpoint(client):
return (
"foo.googleapis.com"
if ("localhost" in client.DEFAULT_ENDPOINT)
else client.DEFAULT_ENDPOINT
)
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
sandbox_endpoint = "example.sandbox.googleapis.com"
sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
non_googleapi = "api.example.com"
assert BigtableClient._get_default_mtls_endpoint(None) is None
assert BigtableClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
assert (
BigtableClient._get_default_mtls_endpoint(api_mtls_endpoint)
== api_mtls_endpoint
)
assert (
BigtableClient._get_default_mtls_endpoint(sandbox_endpoint)
== sandbox_mtls_endpoint
)
assert (
BigtableClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
== sandbox_mtls_endpoint
)
assert BigtableClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
@pytest.mark.parametrize("client_class", [BigtableClient, BigtableAsyncClient,])
def test_bigtable_client_from_service_account_info(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_info"
) as factory:
factory.return_value = creds
info = {"valid": True}
client = client_class.from_service_account_info(info)
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == "bigtable.googleapis.com:443"
@pytest.mark.parametrize(
"transport_class,transport_name",
[
(transports.BigtableGrpcTransport, "grpc"),
(transports.BigtableGrpcAsyncIOTransport, "grpc_asyncio"),
],
)
def test_bigtable_client_service_account_always_use_jwt(
transport_class, transport_name
):
with mock.patch.object(
service_account.Credentials, "with_always_use_jwt_access", create=True
) as use_jwt:
creds = service_account.Credentials(None, None, None)
transport = transport_class(credentials=creds, always_use_jwt_access=True)
use_jwt.assert_called_once_with(True)
with mock.patch.object(
service_account.Credentials, "with_always_use_jwt_access", create=True
) as use_jwt:
creds = service_account.Credentials(None, None, None)
transport = transport_class(credentials=creds, always_use_jwt_access=False)
use_jwt.assert_not_called()
@pytest.mark.parametrize("client_class", [BigtableClient, BigtableAsyncClient,])
def test_bigtable_client_from_service_account_file(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == "bigtable.googleapis.com:443"
def test_bigtable_client_get_transport_class():
transport = BigtableClient.get_transport_class()
available_transports = [
transports.BigtableGrpcTransport,
]
assert transport in available_transports
transport = BigtableClient.get_transport_class("grpc")
assert transport == transports.BigtableGrpcTransport
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(BigtableClient, transports.BigtableGrpcTransport, "grpc"),
(BigtableAsyncClient, transports.BigtableGrpcAsyncIOTransport, "grpc_asyncio"),
],
)
@mock.patch.object(
BigtableClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BigtableClient)
)
@mock.patch.object(
BigtableAsyncClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(BigtableAsyncClient),
)
def test_bigtable_client_client_options(client_class, transport_class, transport_name):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(BigtableClient, "get_transport_class") as gtc:
transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
# Check that if channel is provided via str we will create a new one.
with mock.patch.object(BigtableClient, "get_transport_class") as gtc:
client = client_class(transport=transport_name)
gtc.assert_called()
# Check the case api_endpoint is provided.
options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name, client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "never".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "always".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
# unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
with pytest.raises(MutualTLSChannelError):
client = client_class()
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
):
with pytest.raises(ValueError):
client = client_class()
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name, client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name,use_client_cert_env",
[
(BigtableClient, transports.BigtableGrpcTransport, "grpc", "true"),
(
BigtableAsyncClient,
transports.BigtableGrpcAsyncIOTransport,
"grpc_asyncio",
"true",
),
(BigtableClient, transports.BigtableGrpcTransport, "grpc", "false"),
(
BigtableAsyncClient,
transports.BigtableGrpcAsyncIOTransport,
"grpc_asyncio",
"false",
),
],
)
@mock.patch.object(
BigtableClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BigtableClient)
)
@mock.patch.object(
BigtableAsyncClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(BigtableAsyncClient),
)
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_bigtable_client_mtls_env_auto(
client_class, transport_class, transport_name, use_client_cert_env
):
# This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
# mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
# Check the case client_cert_source is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
options = client_options.ClientOptions(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name, client_options=options)
if use_client_cert_env == "false":
expected_client_cert_source = None
expected_host = client.DEFAULT_ENDPOINT
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=True,
):
with mock.patch(
"google.auth.transport.mtls.default_client_cert_source",
return_value=client_cert_source_callback,
):
if use_client_cert_env == "false":
expected_host = client.DEFAULT_ENDPOINT
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
expected_client_cert_source = client_cert_source_callback
patched.return_value = None
client = client_class(transport=transport_name)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
# Check the case client_cert_source and ADC client cert are not provided.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=False,
):
patched.return_value = None
client = client_class(transport=transport_name)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(BigtableClient, transports.BigtableGrpcTransport, "grpc"),
(BigtableAsyncClient, transports.BigtableGrpcAsyncIOTransport, "grpc_asyncio"),
],
)
def test_bigtable_client_client_options_scopes(
client_class, transport_class, transport_name
):
# Check the case scopes are provided.
options = client_options.ClientOptions(scopes=["1", "2"],)
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name, client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(BigtableClient, transports.BigtableGrpcTransport, "grpc"),
(BigtableAsyncClient, transports.BigtableGrpcAsyncIOTransport, "grpc_asyncio"),
],
)
def test_bigtable_client_client_options_credentials_file(
client_class, transport_class, transport_name
):
# Check the case credentials file is provided.
options = client_options.ClientOptions(credentials_file="credentials.json")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(transport=transport_name, client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
def test_bigtable_client_client_options_from_dict():
with mock.patch(
"google.cloud.bigtable_v2.services.bigtable.transports.BigtableGrpcTransport.__init__"
) as grpc_transport:
grpc_transport.return_value = None
client = BigtableClient(client_options={"api_endpoint": "squid.clam.whelk"})
grpc_transport.assert_called_once_with(
credentials=None,
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
always_use_jwt_access=True,
)
def test_read_rows(transport: str = "grpc", request_type=bigtable.ReadRowsRequest):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.ReadRowsResponse()])
response = client.read_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadRowsRequest()
# Establish that the response is the type that we expect.
for message in response:
assert isinstance(message, bigtable.ReadRowsResponse)
def test_read_rows_from_dict():
test_read_rows(request_type=dict)
def test_read_rows_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
client.read_rows()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadRowsRequest()
@pytest.mark.asyncio
async def test_read_rows_async(
transport: str = "grpc_asyncio", request_type=bigtable.ReadRowsRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.ReadRowsResponse()]
)
response = await client.read_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadRowsRequest()
# Establish that the response is the type that we expect.
message = await response.read()
assert isinstance(message, bigtable.ReadRowsResponse)
@pytest.mark.asyncio
async def test_read_rows_async_from_dict():
await test_read_rows_async(request_type=dict)
def test_read_rows_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.ReadRowsRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
call.return_value = iter([bigtable.ReadRowsResponse()])
client.read_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_read_rows_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.ReadRowsRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.ReadRowsResponse()]
)
await client.read_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_read_rows_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.ReadRowsResponse()])
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.read_rows(
table_name="table_name_value", app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_read_rows_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.read_rows(
bigtable.ReadRowsRequest(),
table_name="table_name_value",
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_read_rows_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.read_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.ReadRowsResponse()])
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.read_rows(
table_name="table_name_value", app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_read_rows_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.read_rows(
bigtable.ReadRowsRequest(),
table_name="table_name_value",
app_profile_id="app_profile_id_value",
)
def test_sample_row_keys(
transport: str = "grpc", request_type=bigtable.SampleRowKeysRequest
):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.SampleRowKeysResponse()])
response = client.sample_row_keys(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.SampleRowKeysRequest()
# Establish that the response is the type that we expect.
for message in response:
assert isinstance(message, bigtable.SampleRowKeysResponse)
def test_sample_row_keys_from_dict():
test_sample_row_keys(request_type=dict)
def test_sample_row_keys_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
client.sample_row_keys()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.SampleRowKeysRequest()
@pytest.mark.asyncio
async def test_sample_row_keys_async(
transport: str = "grpc_asyncio", request_type=bigtable.SampleRowKeysRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.SampleRowKeysResponse()]
)
response = await client.sample_row_keys(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.SampleRowKeysRequest()
# Establish that the response is the type that we expect.
message = await response.read()
assert isinstance(message, bigtable.SampleRowKeysResponse)
@pytest.mark.asyncio
async def test_sample_row_keys_async_from_dict():
await test_sample_row_keys_async(request_type=dict)
def test_sample_row_keys_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.SampleRowKeysRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
call.return_value = iter([bigtable.SampleRowKeysResponse()])
client.sample_row_keys(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_sample_row_keys_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.SampleRowKeysRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.SampleRowKeysResponse()]
)
await client.sample_row_keys(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_sample_row_keys_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.SampleRowKeysResponse()])
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.sample_row_keys(
table_name="table_name_value", app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_sample_row_keys_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.sample_row_keys(
bigtable.SampleRowKeysRequest(),
table_name="table_name_value",
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_sample_row_keys_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.sample_row_keys), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.SampleRowKeysResponse()])
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.sample_row_keys(
table_name="table_name_value", app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_sample_row_keys_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.sample_row_keys(
bigtable.SampleRowKeysRequest(),
table_name="table_name_value",
app_profile_id="app_profile_id_value",
)
def test_mutate_row(transport: str = "grpc", request_type=bigtable.MutateRowRequest):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.MutateRowResponse()
response = client.mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.MutateRowResponse)
def test_mutate_row_from_dict():
test_mutate_row(request_type=dict)
def test_mutate_row_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
client.mutate_row()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowRequest()
@pytest.mark.asyncio
async def test_mutate_row_async(
transport: str = "grpc_asyncio", request_type=bigtable.MutateRowRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.MutateRowResponse()
)
response = await client.mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.MutateRowResponse)
@pytest.mark.asyncio
async def test_mutate_row_async_from_dict():
await test_mutate_row_async(request_type=dict)
def test_mutate_row_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.MutateRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
call.return_value = bigtable.MutateRowResponse()
client.mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_mutate_row_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.MutateRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.MutateRowResponse()
)
await client.mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_mutate_row_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.MutateRowResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.mutate_row(
table_name="table_name_value",
row_key=b"row_key_blob",
mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_mutate_row_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.mutate_row(
bigtable.MutateRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_mutate_row_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_row), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.MutateRowResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.MutateRowResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.mutate_row(
table_name="table_name_value",
row_key=b"row_key_blob",
mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_mutate_row_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.mutate_row(
bigtable.MutateRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
def test_mutate_rows(transport: str = "grpc", request_type=bigtable.MutateRowsRequest):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.MutateRowsResponse()])
response = client.mutate_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowsRequest()
# Establish that the response is the type that we expect.
for message in response:
assert isinstance(message, bigtable.MutateRowsResponse)
def test_mutate_rows_from_dict():
test_mutate_rows(request_type=dict)
def test_mutate_rows_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
client.mutate_rows()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowsRequest()
@pytest.mark.asyncio
async def test_mutate_rows_async(
transport: str = "grpc_asyncio", request_type=bigtable.MutateRowsRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.MutateRowsResponse()]
)
response = await client.mutate_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.MutateRowsRequest()
# Establish that the response is the type that we expect.
message = await response.read()
assert isinstance(message, bigtable.MutateRowsResponse)
@pytest.mark.asyncio
async def test_mutate_rows_async_from_dict():
await test_mutate_rows_async(request_type=dict)
def test_mutate_rows_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.MutateRowsRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
call.return_value = iter([bigtable.MutateRowsResponse()])
client.mutate_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_mutate_rows_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.MutateRowsRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
call.return_value.read = mock.AsyncMock(
side_effect=[bigtable.MutateRowsResponse()]
)
await client.mutate_rows(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_mutate_rows_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.MutateRowsResponse()])
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.mutate_rows(
table_name="table_name_value",
entries=[bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].entries
mock_val = [bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_mutate_rows_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.mutate_rows(
bigtable.MutateRowsRequest(),
table_name="table_name_value",
entries=[bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")],
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_mutate_rows_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.mutate_rows), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = iter([bigtable.MutateRowsResponse()])
call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.mutate_rows(
table_name="table_name_value",
entries=[bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].entries
mock_val = [bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_mutate_rows_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.mutate_rows(
bigtable.MutateRowsRequest(),
table_name="table_name_value",
entries=[bigtable.MutateRowsRequest.Entry(row_key=b"row_key_blob")],
app_profile_id="app_profile_id_value",
)
def test_check_and_mutate_row(
transport: str = "grpc", request_type=bigtable.CheckAndMutateRowRequest
):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.CheckAndMutateRowResponse(predicate_matched=True,)
response = client.check_and_mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.CheckAndMutateRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.CheckAndMutateRowResponse)
assert response.predicate_matched is True
def test_check_and_mutate_row_from_dict():
test_check_and_mutate_row(request_type=dict)
def test_check_and_mutate_row_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
client.check_and_mutate_row()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.CheckAndMutateRowRequest()
@pytest.mark.asyncio
async def test_check_and_mutate_row_async(
transport: str = "grpc_asyncio", request_type=bigtable.CheckAndMutateRowRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.CheckAndMutateRowResponse(predicate_matched=True,)
)
response = await client.check_and_mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.CheckAndMutateRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.CheckAndMutateRowResponse)
assert response.predicate_matched is True
@pytest.mark.asyncio
async def test_check_and_mutate_row_async_from_dict():
await test_check_and_mutate_row_async(request_type=dict)
def test_check_and_mutate_row_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.CheckAndMutateRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
call.return_value = bigtable.CheckAndMutateRowResponse()
client.check_and_mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_check_and_mutate_row_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.CheckAndMutateRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.CheckAndMutateRowResponse()
)
await client.check_and_mutate_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_check_and_mutate_row_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.CheckAndMutateRowResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.check_and_mutate_row(
table_name="table_name_value",
row_key=b"row_key_blob",
predicate_filter=data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(
filters=[data.RowFilter(chain=None)]
)
)
]
)
),
true_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
false_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].predicate_filter
mock_val = data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(filters=[data.RowFilter(chain=None)])
)
]
)
)
assert arg == mock_val
arg = args[0].true_mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].false_mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_check_and_mutate_row_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.check_and_mutate_row(
bigtable.CheckAndMutateRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
predicate_filter=data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(
filters=[data.RowFilter(chain=None)]
)
)
]
)
),
true_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
false_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_check_and_mutate_row_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.check_and_mutate_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.CheckAndMutateRowResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.CheckAndMutateRowResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.check_and_mutate_row(
table_name="table_name_value",
row_key=b"row_key_blob",
predicate_filter=data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(
filters=[data.RowFilter(chain=None)]
)
)
]
)
),
true_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
false_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].predicate_filter
mock_val = data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(filters=[data.RowFilter(chain=None)])
)
]
)
)
assert arg == mock_val
arg = args[0].true_mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].false_mutations
mock_val = [
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_check_and_mutate_row_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.check_and_mutate_row(
bigtable.CheckAndMutateRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
predicate_filter=data.RowFilter(
chain=data.RowFilter.Chain(
filters=[
data.RowFilter(
chain=data.RowFilter.Chain(
filters=[data.RowFilter(chain=None)]
)
)
]
)
),
true_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
false_mutations=[
data.Mutation(
set_cell=data.Mutation.SetCell(family_name="family_name_value")
)
],
app_profile_id="app_profile_id_value",
)
def test_read_modify_write_row(
transport: str = "grpc", request_type=bigtable.ReadModifyWriteRowRequest
):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.ReadModifyWriteRowResponse()
response = client.read_modify_write_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadModifyWriteRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.ReadModifyWriteRowResponse)
def test_read_modify_write_row_from_dict():
test_read_modify_write_row(request_type=dict)
def test_read_modify_write_row_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
client.read_modify_write_row()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadModifyWriteRowRequest()
@pytest.mark.asyncio
async def test_read_modify_write_row_async(
transport: str = "grpc_asyncio", request_type=bigtable.ReadModifyWriteRowRequest
):
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.ReadModifyWriteRowResponse()
)
response = await client.read_modify_write_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == bigtable.ReadModifyWriteRowRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, bigtable.ReadModifyWriteRowResponse)
@pytest.mark.asyncio
async def test_read_modify_write_row_async_from_dict():
await test_read_modify_write_row_async(request_type=dict)
def test_read_modify_write_row_field_headers():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.ReadModifyWriteRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
call.return_value = bigtable.ReadModifyWriteRowResponse()
client.read_modify_write_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
@pytest.mark.asyncio
async def test_read_modify_write_row_field_headers_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = bigtable.ReadModifyWriteRowRequest()
request.table_name = "table_name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.ReadModifyWriteRowResponse()
)
await client.read_modify_write_row(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "table_name=table_name/value",) in kw["metadata"]
def test_read_modify_write_row_flattened():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.ReadModifyWriteRowResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.read_modify_write_row(
table_name="table_name_value",
row_key=b"row_key_blob",
rules=[data.ReadModifyWriteRule(family_name="family_name_value")],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].rules
mock_val = [data.ReadModifyWriteRule(family_name="family_name_value")]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
def test_read_modify_write_row_flattened_error():
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.read_modify_write_row(
bigtable.ReadModifyWriteRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
rules=[data.ReadModifyWriteRule(family_name="family_name_value")],
app_profile_id="app_profile_id_value",
)
@pytest.mark.asyncio
async def test_read_modify_write_row_flattened_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.read_modify_write_row), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = bigtable.ReadModifyWriteRowResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
bigtable.ReadModifyWriteRowResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.read_modify_write_row(
table_name="table_name_value",
row_key=b"row_key_blob",
rules=[data.ReadModifyWriteRule(family_name="family_name_value")],
app_profile_id="app_profile_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
arg = args[0].table_name
mock_val = "table_name_value"
assert arg == mock_val
arg = args[0].row_key
mock_val = b"row_key_blob"
assert arg == mock_val
arg = args[0].rules
mock_val = [data.ReadModifyWriteRule(family_name="family_name_value")]
assert arg == mock_val
arg = args[0].app_profile_id
mock_val = "app_profile_id_value"
assert arg == mock_val
@pytest.mark.asyncio
async def test_read_modify_write_row_flattened_error_async():
client = BigtableAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.read_modify_write_row(
bigtable.ReadModifyWriteRowRequest(),
table_name="table_name_value",
row_key=b"row_key_blob",
rules=[data.ReadModifyWriteRule(family_name="family_name_value")],
app_profile_id="app_profile_id_value",
)
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.BigtableGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.BigtableGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = BigtableClient(
client_options={"credentials_file": "credentials.json"},
transport=transport,
)
# It is an error to provide scopes and a transport instance.
transport = transports.BigtableGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = BigtableClient(
client_options={"scopes": ["1", "2"]}, transport=transport,
)
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.BigtableGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
client = BigtableClient(transport=transport)
assert client.transport is transport
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.BigtableGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.BigtableGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@pytest.mark.parametrize(
"transport_class",
[transports.BigtableGrpcTransport, transports.BigtableGrpcAsyncIOTransport,],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = BigtableClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.BigtableGrpcTransport,)
def test_bigtable_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.BigtableTransport(
credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
def test_bigtable_base_transport():
# Instantiate the base transport.
with mock.patch(
"google.cloud.bigtable_v2.services.bigtable.transports.BigtableTransport.__init__"
) as Transport:
Transport.return_value = None
transport = transports.BigtableTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
"read_rows",
"sample_row_keys",
"mutate_row",
"mutate_rows",
"check_and_mutate_row",
"read_modify_write_row",
)
for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
with pytest.raises(NotImplementedError):
transport.close()
def test_bigtable_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.bigtable_v2.services.bigtable.transports.BigtableTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.BigtableTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
default_scopes=(
"https://www.googleapis.com/auth/bigtable.data",
"https://www.googleapis.com/auth/bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-bigtable.data",
"https://www.googleapis.com/auth/cloud-bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
),
quota_project_id="octopus",
)
def test_bigtable_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.bigtable_v2.services.bigtable.transports.BigtableTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.BigtableTransport()
adc.assert_called_once()
def test_bigtable_auth_adc():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
BigtableClient()
adc.assert_called_once_with(
scopes=None,
default_scopes=(
"https://www.googleapis.com/auth/bigtable.data",
"https://www.googleapis.com/auth/bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-bigtable.data",
"https://www.googleapis.com/auth/cloud-bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
),
quota_project_id=None,
)
@pytest.mark.parametrize(
"transport_class",
[transports.BigtableGrpcTransport, transports.BigtableGrpcAsyncIOTransport,],
)
def test_bigtable_transport_auth_adc(transport_class):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
default_scopes=(
"https://www.googleapis.com/auth/bigtable.data",
"https://www.googleapis.com/auth/bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-bigtable.data",
"https://www.googleapis.com/auth/cloud-bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
),
quota_project_id="octopus",
)
@pytest.mark.parametrize(
"transport_class,grpc_helpers",
[
(transports.BigtableGrpcTransport, grpc_helpers),
(transports.BigtableGrpcAsyncIOTransport, grpc_helpers_async),
],
)
def test_bigtable_transport_create_channel(transport_class, grpc_helpers):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(
google.auth, "default", autospec=True
) as adc, mock.patch.object(
grpc_helpers, "create_channel", autospec=True
) as create_channel:
creds = ga_credentials.AnonymousCredentials()
adc.return_value = (creds, None)
transport_class(quota_project_id="octopus", scopes=["1", "2"])
create_channel.assert_called_with(
"bigtable.googleapis.com:443",
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
default_scopes=(
"https://www.googleapis.com/auth/bigtable.data",
"https://www.googleapis.com/auth/bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-bigtable.data",
"https://www.googleapis.com/auth/cloud-bigtable.data.readonly",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
),
scopes=["1", "2"],
default_host="bigtable.googleapis.com",
ssl_credentials=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
@pytest.mark.parametrize(
"transport_class",
[transports.BigtableGrpcTransport, transports.BigtableGrpcAsyncIOTransport],
)
def test_bigtable_grpc_transport_client_cert_source_for_mtls(transport_class):
cred = ga_credentials.AnonymousCredentials()
# Check ssl_channel_credentials is used if provided.
with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
mock_ssl_channel_creds = mock.Mock()
transport_class(
host="squid.clam.whelk",
credentials=cred,
ssl_channel_credentials=mock_ssl_channel_creds,
)
mock_create_channel.assert_called_once_with(
"squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
scopes=None,
ssl_credentials=mock_ssl_channel_creds,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
# is used.
with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
transport_class(
credentials=cred,
client_cert_source_for_mtls=client_cert_source_callback,
)
expected_cert, expected_key = client_cert_source_callback()
mock_ssl_cred.assert_called_once_with(
certificate_chain=expected_cert, private_key=expected_key
)
def test_bigtable_host_no_port():
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="bigtable.googleapis.com"
),
)
assert client.transport._host == "bigtable.googleapis.com:443"
def test_bigtable_host_with_port():
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="bigtable.googleapis.com:8000"
),
)
assert client.transport._host == "bigtable.googleapis.com:8000"
def test_bigtable_grpc_transport_channel():
channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.BigtableGrpcTransport(
host="squid.clam.whelk", channel=channel,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert transport._ssl_channel_credentials == None
def test_bigtable_grpc_asyncio_transport_channel():
channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.BigtableGrpcAsyncIOTransport(
host="squid.clam.whelk", channel=channel,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert transport._ssl_channel_credentials == None
# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.BigtableGrpcTransport, transports.BigtableGrpcAsyncIOTransport],
)
def test_bigtable_transport_channel_mtls_with_client_cert_source(transport_class):
with mock.patch(
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=client_cert_source_callback,
)
adc.assert_called_once()
grpc_ssl_channel_cred.assert_called_once_with(
certificate_chain=b"cert bytes", private_key=b"key bytes"
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
assert transport._ssl_channel_credentials == mock_ssl_cred
# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.BigtableGrpcTransport, transports.BigtableGrpcAsyncIOTransport],
)
def test_bigtable_transport_channel_mtls_with_adc(transport_class):
mock_ssl_cred = mock.Mock()
with mock.patch.multiple(
"google.auth.transport.grpc.SslCredentials",
__init__=mock.Mock(return_value=None),
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
mock_cred = mock.Mock()
with pytest.warns(DeprecationWarning):
transport = transport_class(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=None,
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
def test_table_path():
project = "squid"
instance = "clam"
table = "whelk"
expected = "projects/{project}/instances/{instance}/tables/{table}".format(
project=project, instance=instance, table=table,
)
actual = BigtableClient.table_path(project, instance, table)
assert expected == actual
def test_parse_table_path():
expected = {
"project": "octopus",
"instance": "oyster",
"table": "nudibranch",
}
path = BigtableClient.table_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_table_path(path)
assert expected == actual
def test_common_billing_account_path():
billing_account = "cuttlefish"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
actual = BigtableClient.common_billing_account_path(billing_account)
assert expected == actual
def test_parse_common_billing_account_path():
expected = {
"billing_account": "mussel",
}
path = BigtableClient.common_billing_account_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_common_billing_account_path(path)
assert expected == actual
def test_common_folder_path():
folder = "winkle"
expected = "folders/{folder}".format(folder=folder,)
actual = BigtableClient.common_folder_path(folder)
assert expected == actual
def test_parse_common_folder_path():
expected = {
"folder": "nautilus",
}
path = BigtableClient.common_folder_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_common_folder_path(path)
assert expected == actual
def test_common_organization_path():
organization = "scallop"
expected = "organizations/{organization}".format(organization=organization,)
actual = BigtableClient.common_organization_path(organization)
assert expected == actual
def test_parse_common_organization_path():
expected = {
"organization": "abalone",
}
path = BigtableClient.common_organization_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_common_organization_path(path)
assert expected == actual
def test_common_project_path():
project = "squid"
expected = "projects/{project}".format(project=project,)
actual = BigtableClient.common_project_path(project)
assert expected == actual
def test_parse_common_project_path():
expected = {
"project": "clam",
}
path = BigtableClient.common_project_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_common_project_path(path)
assert expected == actual
def test_common_location_path():
project = "whelk"
location = "octopus"
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
actual = BigtableClient.common_location_path(project, location)
assert expected == actual
def test_parse_common_location_path():
expected = {
"project": "oyster",
"location": "nudibranch",
}
path = BigtableClient.common_location_path(**expected)
# Check that the path construction is reversible.
actual = BigtableClient.parse_common_location_path(path)
assert expected == actual
def test_client_withDEFAULT_CLIENT_INFO():
client_info = gapic_v1.client_info.ClientInfo()
with mock.patch.object(
transports.BigtableTransport, "_prep_wrapped_messages"
) as prep:
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
with mock.patch.object(
transports.BigtableTransport, "_prep_wrapped_messages"
) as prep:
transport_class = BigtableClient.get_transport_class()
transport = transport_class(
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@pytest.mark.asyncio
async def test_transport_close_async():
client = BigtableAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
)
with mock.patch.object(
type(getattr(client.transport, "grpc_channel")), "close"
) as close:
async with client:
close.assert_not_called()
close.assert_called_once()
def test_transport_close():
transports = {
"grpc": "_grpc_channel",
}
for transport, close_name in transports.items():
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport
)
with mock.patch.object(
type(getattr(client.transport, close_name)), "close"
) as close:
with client:
close.assert_not_called()
close.assert_called_once()
def test_client_ctx():
transports = [
"grpc",
]
for transport in transports:
client = BigtableClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport
)
# Test client calls underlying transport.
with mock.patch.object(type(client.transport), "close") as close:
close.assert_not_called()
with client:
pass
close.assert_called()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
internal/testing/e2e/cluster_test.go
|
// +build e2ecluster
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package e2e
import (
"context"
"fmt"
"os"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"ns-open-match/internal/app/evaluator"
"ns-open-match/internal/appmain/apptest"
"ns-open-match/internal/config"
mmfService "ns-open-match/internal/testing/mmf"
"ns-open-match/pkg/pb"
"strings"
)
func TestServiceHealth(t *testing.T) {
kubeconfig, err := rest.InClusterConfig()
if err != nil {
t.Fatal(err)
}
kubeClient, err := kubernetes.NewForConfig(kubeconfig)
if err != nil {
t.Fatalf("%s: creating Kubernetes client from config failed\nconfig= %+v", err, kubeconfig)
}
namespace := os.Getenv("NAMESPACE")
podList, err := kubeClient.CoreV1().Pods(namespace).List(metav1.ListOptions{})
if err != nil {
t.Fatal(err)
}
for _, pod := range podList.Items {
if app, ok := pod.ObjectMeta.Labels["app"]; ok && app == "open-match" && pod.Status.Phase != corev1.PodRunning {
t.Errorf("pod %+v is not running.", pod)
}
}
}
func TestMain(m *testing.M) {
clusterStarted = true
mmf := func(ctx context.Context, profile *pb.MatchProfile, out chan<- *pb.Match) error {
return clusterMMF(ctx, profile, out)
}
eval := func(ctx context.Context, in <-chan *pb.Match, out chan<- string) error {
return clusterEval(ctx, in, out)
}
cleanup, err := apptest.RunInCluster(mmfService.BindServiceFor(mmf), evaluator.BindServiceFor(eval))
if err != nil {
fmt.Println("Error starting mmf and evaluator:", err)
os.Exit(1)
}
exitCode := m.Run()
err = cleanup()
if err != nil {
fmt.Println("Error stopping mmf and evaluator:", err)
os.Exit(1)
}
os.Exit(exitCode)
}
// TestConfigMatch covers that the config file used for local in memory e2e
// tests matches the configs used for the in cluster tests, to avoid drift.
func TestConfigMatch(t *testing.T) {
cfg, err := config.Read()
if err != nil {
t.Fatal(err)
}
cfgMemory := viper.New()
cfgMemory.SetConfigType("yaml")
err = cfgMemory.ReadConfig(strings.NewReader(configFile))
if err != nil {
t.Fatal(err)
}
require.Equal(t, cfgMemory.AllSettings(), cfg.AllSettings())
}
|
[
"\"NAMESPACE\""
] |
[] |
[
"NAMESPACE"
] |
[]
|
["NAMESPACE"]
|
go
| 1 | 0 | |
examples/service/api/sip_ip_access_control_list/update/ip_access_control_list_update_example.go
|
package main
import (
"log"
"os"
"github.com/RJPearson94/twilio-sdk-go"
v2010 "github.com/RJPearson94/twilio-sdk-go/service/api/v2010"
"github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/ip_access_control_list"
"github.com/RJPearson94/twilio-sdk-go/session/credentials"
)
var apiClient *v2010.V2010
func init() {
creds, err := credentials.New(credentials.Account{
Sid: os.Getenv("TWILIO_ACCOUNT_SID"),
AuthToken: os.Getenv("TWILIO_AUTH_TOKEN"),
})
if err != nil {
log.Panicf("%s", err.Error())
}
apiClient = twilio.NewWithCredentials(creds).API.V2010
}
func main() {
resp, err := apiClient.
Account("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").
Sip.
IpAccessControlList("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").
Update(&ip_access_control_list.UpdateIpAccessControlListInput{
FriendlyName: "Test 2",
})
if err != nil {
log.Panicf("%s", err.Error())
}
log.Printf("SID: %s", resp.Sid)
}
|
[
"\"TWILIO_ACCOUNT_SID\"",
"\"TWILIO_AUTH_TOKEN\""
] |
[] |
[
"TWILIO_AUTH_TOKEN",
"TWILIO_ACCOUNT_SID"
] |
[]
|
["TWILIO_AUTH_TOKEN", "TWILIO_ACCOUNT_SID"]
|
go
| 2 | 0 | |
docs/conf.py
|
# -*- coding: utf-8 -*-
#
# Falcon documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 12 14:14:02 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from datetime import datetime
from collections import OrderedDict
import sys
import os
try:
import configparser
except ImportError:
import ConfigParser as configparser
import falcon
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))
# Path to custom themes
sys.path.append(os.path.abspath('_themes'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
# Falcon-specific extensions
'ext.rfc',
'ext.doorway',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Falcon'
copyright = u"{year} Falcon Contributors".format(
year=datetime.utcnow().year
)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
cfg = configparser.SafeConfigParser()
cfg.read('../setup.cfg')
tag = cfg.get('egg_info', 'tag_build')
html_context = {
'prerelease': bool(tag), # True if tag is not the empty string
}
# The short X.Y version.
version = '.'.join(falcon.__version__.split('.')[0:2]) + tag
# The full version, including alpha/beta/rc tags.
release = falcon.__version__ + tag
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'github'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ['_themes']
# html_theme = ''
html_theme = 'alabaster'
# if not on_rtd:
# # Use the RTD theme explicitly if it is available
# try:
# import sphinx_rtd_theme
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# html_theme = "sphinx_rtd_theme"
# except ImportError:
# pass
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'github_user': 'falconry',
'github_repo': 'falcon',
'github_button': False,
'github_banner': True,
'fixed_sidebar': False,
'show_powered_by': False,
'extra_nav_links': OrderedDict([
('Falcon Home', 'https://falconframework.org/'),
('Falcon Wiki', 'https://github.com/falconry/falcon/wiki'),
('Get Help', '/community/help.html'),
('Support Falcon', 'https://falconframework.org/#sectionSupportFalconDevelopment'),
]),
}
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = '../falcon.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '_static/img/favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {
# 'index': ['side-primary.html', 'searchbox.html'],
# '**': ['side-secondary.html', 'localtoc.html',
# 'relations.html', 'searchbox.html']
# }
html_sidebars = {
'**': [
'sidebar-top.html',
'sidebar-sponsors.html',
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Falcondoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'Falcon.tex', u'Falcon Documentation',
u'Kurt Griffiths et al.', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'falcon', u'Falcon Documentation',
[u'Kurt Griffiths et al.'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Falcon', u'Falcon Documentation',
u'Kurt Griffiths et al.', 'Falcon', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/2': None}
|
[] |
[] |
[
"READTHEDOCS"
] |
[]
|
["READTHEDOCS"]
|
python
| 1 | 0 | |
api/auth/auth.go
|
package auth
import(
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/go-redis/redis"
"github.com/gorilla/securecookie"
uuid "github.com/satori/go.uuid"
"golang.org/x/crypto/bcrypt"
)
var authenticatedUserID struct {
id string
}
var deleteSessionAndCookie struct {
flag bool
}
var validCookies []securecookie.Codec
var hashKeyData struct {
hash [][]byte
key [][]byte
}
var userIDCtxKey = &contextKey{"userID"}
type contextKey struct {
name string
}
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
// Return a slice of byte containing the
// cryptologically random string.
return b, nil
}
func GenerateRandomString(s int) (string, error) {
b, err := GenerateRandomBytes(s)
return base64.URLEncoding.EncodeToString(b), err
}
func Roll() error {
err := rollFile(".hash")
if err != nil {
return err
}
err = rollFile(".key")
if err != nil {
return err
}
err = generateValidCookies()
if err != nil {
return err
}
return nil
}
func rollFile(fName string) error {
var f *os.File
_, err := os.Stat(fName)
if os.IsNotExist(err) {
f, err = os.OpenFile(fName, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
err = f.Chown(os.Getuid(), os.Getgid())
if err != nil {
return err
}
err = os.Chtimes(fName, time.Now(), time.Now())
if err != nil {
return err
}
} else {
f, err = os.OpenFile(fName, os.O_RDWR, 0600)
if err != nil {
return err
}
}
defer f.Close()
fInfo, err := f.Stat()
if err != nil {
return err
}
n := fInfo.Size()
var fData []byte
if n >= 24*32 {
fData = make([]byte, n-32)
lenBytes, err := f.ReadAt(fData, 32)
if lenBytes != int(n-32 || err != nil {
return errors.New("Corruption of data in rolling encryption file:\nUnexpected number of bytes.")
}
} else {
fData = make([]byte], n)
lenBytes, err := f.Read(fData)
if lenBytes != int(n) || err != nil {
return err
}
}
s, err := GenerateRandomString(24)
if err != nil {
return err
}
fData = append(fData, []byte(s)...)
_, err = f.WriteAt(fData, 0)
if err != nil {
return err
}
err = f.Sync()
if err != nil {
return err
}
switch fName {
case ".hash":
err = parseHashDataToMemory(fData)
if err != nil {
return err
}
case ".key":
err = parseKeyDataToMemory(fData)
if err != nil {
return err
}
}
return nil
}
func parseHashDataToMemory(data []byte) error {
n := len(data) / 32
if n <= 0 {
return errors.New("Illegal length for data in hash file.")
}
hashKeyData.hash = make([][]byte, 0, 24)
for k := 0; k < n; k++ {
h := data[k*32 : ((k*32)*32)-1]
hashKeyData.hash = append(hashKeyData.hash, h)
}
return nil
}
func parseKeyDataToMemory(data []byte) error {
n := len(data) / 32
if n <= 0 {
return errors.New("Illegal length for data in key file.")
}
hashKeyData.key = make([][]byte, 0, 24)
for m := 0; m < n; m++ {
l := data[m*32 : ((m*32)*32)-1]
hashKeyData.key = append(hashKeyData.key, l)
}
return nil
}
func generateValidCookies() error {
validCookies = make([]securecookie.Codec, 0, 24)
hLen := len(hashKeyData.hash)
kLen := len(hashKeyData.key)
if hLen != kLen {
return errors.New("Invalid cookie data.")
}
for hk := 0; hk < hLen; hk++ {
c := securecookie.New(
hashKeyData.hash[hk],
hashKeyData.key[hk],
)
validCookies = append(validCookies, c)
}
return nil
}
func HashAndSalt(pw string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
func CheckPassword(hashedPassword []byte, rawPassword []byte) (bool, error) {
err := bcrypt.CompareHashAndPassword(hashedPassword, rawPassword)
if err != nil {
return false, err
}
return true, nil
}
func ReadSessionIDFromCookie(w http.ResponseWriter, r *http.Request) (string, error) {
cookie, err := r.Cookie("sid")
if err != nil {
return "", err
}
value := make(map[string]string)
err = securecookie.DecodeMulti("sid", cookie.Value, &value, validCookies...)
if err != nil {
return "", err
}
validSessionID, err := uuid.FromString(value["sessionID"])
if err != nil {
return "", err
}
return validSessionID.String(), nil
}
func ReadFromRedis(sessionID map[string]string) (string, error) {
// TODO: Update this to use Docker URI.
client := redis.NewClient(&redis.Options{
Network: "backend"
Addr: fmt.Sprintf(
"%s:%d",
os.Getenv("REDIS_IP").(String),
os.Getenv("REDIS_PORT").(Int)
),
Username: os.Getenv("REDIS_ADMIN_USERNAME"),
Password: os.Getenv("REDIS_ADMIN_PASSWORD"),
})
defer client.Close()
userID, err := client.Do("HGET", sessionID["sessionID"], "userID").String()
if err != nil {
return "", err
}
return userID, nil
}
func WriteToRedis(sessionID map[string]string, userID string, ttl time.Time) error {
client := redis.NewClient(&redis.Options{
Network: "backend"
Addr: fmt.Sprintf(
"%s:%d",
os.Getenv("REDIS_IP").(String),
os.Getenv("REDIS_PORT").(Int)
),
Username: os.Getenv("REDIS_ADMIN_USERNAME"),
Password: os.Getenv("REDIS_ADMIN_PASSWORD"),
})
defer client.Close()
_, err := client.Do("HMSET", sessionID["sessionID"], "userID", userID).Result()
if err != nil {
return err
}
_, err = client.ExpireAt(sessionID["sessionID"], ttl).Result()
if err != nil {
return err
}
return nil
}
// Middleware is the authentication middleware function of our API.
func Middleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TODO:
//
// Gqlgen no longer uses these handler types, so must migrate
// this code to use the new standard.
// Also, this code needs to get cleaned up by refactoring.
var maxAge int
var expiration time.Time
del := deleteSessionAndCookie.flag
if del == true {
maxAge = 0
expiration = time.Now().addDate(0,0,-1)
} else {
maxAge = 24 * 60 * 60
expiration = time.Now().Add(24 * time.Hour)
}
if len(authenticatedUserID.id) == 0 {
c, err := r.Cookie("sid")
if c == nil || err != nil {
sessionID := map[string]string{
"sessionID": uuid.NewV4().String(),
}
err = WriteToRedis(sessionID, authenticatedUserID.id, expiration)
if err != nil {
log.Fatalln("Unable to write sessionID to Redis:", err)
}
persistedID, err = ReadFromRedis(sessionID)
if err != nil {
log.Fatalln("Unable to read sessionID from Redis:", err)
}
if persistedID == authenticatedUserID.id {
encoded, err := securecookie.EncodeMulti(
"sid",
sessionID,
validCookies[len(validCookies)-1],
)
if err != nil {
log.Fatalln("Failed to encode sessionID.")
}
cookie := &http.Cookie{
Name: "sid",
Value: encoded,
HttpOnly: true,
Path: "/",
MaxAge: maxAge,
Expires: expiration,
}
http.SetCookie(w, cookie)
ctx := context.WithValue(r.Context(), userIDCtxKey, authenticatedUserID.id)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
return
}
}
cookie, err := r.Cookie("sid")
if cookie == nil || err != nil {
log.Fatalln("Unable to find cookie for logged in User:", err)
}
sessionID := make(map[string]string)
err = securecookie.DecodeMulti("sid", cookie.Value, &sessionID, validCookies...)
if err != nil {
log.Fatalln("The session cookie has been tampered with:", err)
}
userID, err := ReadFromRedis(sessionID)
if err != nil {
log.Fatalln("Unable to read from Redis:", err)
}
err = WriteToRedis(sessionID, userID, expiration)
if err != nil {
log.Fatalln("Unable to write sessionID to Redis:", err)
}
persistedID, err := ReadFromRedis(sessionID)
if err != nil && del != true {
log.Fatalln("Unable to read userID from Redis:", err)
}
cookie.HttpOnly = true
if del == true {
cookie.Value = ""
}
cookie.Path = "/"
cookie.MaxAge = maxAge
cookie.Expires = expiration
http.SetCookie(w, cookie)
if del == true {
authenticatedUserID.id = ""
deleteSessionAndCookie.flag = false
} else {
authenticatedUserID.id = persistedID
}
ctx := context.WithValue(r.Context(), userIDCtxKey, authenticatedUserID.id)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
}
})
}
}
func InsertUserID(userID string) {
authenticatedUserID.id = userID
}
func SetLogOutFlag(value bool) {
deleteSessionAndCookie.flag = value
}
func ForContext(ctx context.Context) string {
// TODO: There should be error handling here.
raw, _ := ctx.Value(userIDCtxKey).(string)
return raw
}
|
[
"\"REDIS_IP\"",
"\"REDIS_PORT\"",
"\"REDIS_ADMIN_USERNAME\"",
"\"REDIS_ADMIN_PASSWORD\"",
"\"REDIS_IP\"",
"\"REDIS_PORT\"",
"\"REDIS_ADMIN_USERNAME\"",
"\"REDIS_ADMIN_PASSWORD\""
] |
[] |
[
"REDIS_ADMIN_PASSWORD",
"REDIS_ADMIN_USERNAME",
"REDIS_PORT",
"REDIS_IP"
] |
[]
|
["REDIS_ADMIN_PASSWORD", "REDIS_ADMIN_USERNAME", "REDIS_PORT", "REDIS_IP"]
|
go
| 4 | 0 | |
src/sentry/runner/commands/cleanup.py
|
from __future__ import absolute_import, print_function
import os
from datetime import timedelta
from uuid import uuid4
import click
from django.utils import timezone
from sentry.runner.decorators import log_options
from six.moves import xrange
# allows services like tagstore to add their own (abstracted) models
# to cleanup
EXTRA_BULK_QUERY_DELETES = []
def get_project(value):
from sentry.models import Project
try:
if value.isdigit():
return int(value)
if '/' not in value:
return None
org, proj = value.split('/', 1)
return Project.objects.get_from_cache(
organization__slug=org,
slug=proj,
).id
except Project.DoesNotExist:
return None
# We need a unique value to indicate when to stop multiprocessing queue
# an identity on an object() isn't guaranteed to work between parent
# and child proc
_STOP_WORKER = '91650ec271ae4b3e8a67cdc909d80f8c'
API_TOKEN_TTL_IN_DAYS = 30
def multiprocess_worker(task_queue):
# Configure within each Process
import logging
from sentry.utils.imports import import_string
logger = logging.getLogger('sentry.cleanup')
configured = False
while True:
j = task_queue.get()
if j == _STOP_WORKER:
task_queue.task_done()
return
# On first task, configure Sentry environment
if not configured:
from sentry.runner import configure
configure()
from sentry import models
from sentry import deletions
from sentry import similarity
skip_models = [
# Handled by other parts of cleanup
models.Event,
models.EventMapping,
models.EventAttachment,
models.UserReport,
models.Group,
models.GroupEmailThread,
models.GroupRuleStatus,
# Handled by TTL
similarity.features,
] + [b[0] for b in EXTRA_BULK_QUERY_DELETES]
configured = True
model, chunk = j
model = import_string(model)
try:
task = deletions.get(
model=model,
query={'id__in': chunk},
skip_models=skip_models,
transaction_id=uuid4().hex,
)
while True:
if not task.chunk():
break
except Exception as e:
logger.exception(e)
finally:
task_queue.task_done()
@click.command()
@click.option('--days', default=30, show_default=True, help='Numbers of days to truncate on.')
@click.option('--project', help='Limit truncation to only entries from project.')
@click.option(
'--concurrency',
type=int,
default=1,
show_default=True,
help='The total number of concurrent worker processes to run.'
)
@click.option(
'--silent', '-q', default=False, is_flag=True, help='Run quietly. No output on success.'
)
@click.option('--model', '-m', multiple=True)
@click.option('--router', '-r', default=None, help='Database router')
@click.option(
'--timed',
'-t',
default=False,
is_flag=True,
help='Send the duration of this command to internal metrics.'
)
@log_options()
def cleanup(days, project, concurrency, silent, model, router, timed):
"""Delete a portion of trailing data based on creation date.
All data that is older than `--days` will be deleted. The default for
this is 30 days. In the default setting all projects will be truncated
but if you have a specific project you want to limit this to this can be
done with the `--project` flag which accepts a project ID or a string
with the form `org/project` where both are slugs.
"""
if concurrency < 1:
click.echo('Error: Minimum concurrency is 1', err=True)
raise click.Abort()
os.environ['_SENTRY_CLEANUP'] = '1'
# Make sure we fork off multiprocessing pool
# before we import or configure the app
from multiprocessing import Process, JoinableQueue as Queue
pool = []
task_queue = Queue(1000)
for _ in xrange(concurrency):
p = Process(target=multiprocess_worker, args=(task_queue,))
p.daemon = True
p.start()
pool.append(p)
from sentry.runner import configure
configure()
from django.db import router as db_router
from sentry.app import nodestore
from sentry.db.deletion import BulkDeleteQuery
from sentry import models
if timed:
import time
from sentry.utils import metrics
start_time = time.time()
# list of models which this query is restricted to
model_list = {m.lower() for m in model}
def is_filtered(model):
if router is not None and db_router.db_for_write(model) != router:
return True
if not model_list:
return False
return model.__name__.lower() not in model_list
# Deletions that use `BulkDeleteQuery` (and don't need to worry about child relations)
# (model, datetime_field, order_by)
BULK_QUERY_DELETES = [
(models.EventMapping, 'date_added', '-date_added'),
(models.EventAttachment, 'date_added', None),
(models.UserReport, 'date_added', None),
(models.GroupEmailThread, 'date', None),
(models.GroupRuleStatus, 'date_added', None),
] + EXTRA_BULK_QUERY_DELETES
# Deletions that use the `deletions` code path (which handles their child relations)
# (model, datetime_field, order_by)
DELETES = (
(models.Event, 'datetime', 'datetime'),
(models.Group, 'last_seen', 'last_seen'),
)
if not silent:
click.echo('Removing expired values for LostPasswordHash')
if is_filtered(models.LostPasswordHash):
if not silent:
click.echo('>> Skipping LostPasswordHash')
else:
models.LostPasswordHash.objects.filter(
date_added__lte=timezone.now() - timedelta(hours=48)
).delete()
if not silent:
click.echo('Removing expired values for OrganizationMember')
if is_filtered(models.OrganizationMember):
if not silent:
click.echo('>> Skipping OrganizationMember')
else:
expired_threshold = timezone.now() - timedelta(days=days)
models.OrganizationMember.delete_expired(expired_threshold)
for model in [models.ApiGrant, models.ApiToken]:
if not silent:
click.echo(u'Removing expired values for {}'.format(model.__name__))
if is_filtered(model):
if not silent:
click.echo(u'>> Skipping {}'.format(model.__name__))
else:
queryset = model.objects.filter(
expires_at__lt=(timezone.now() - timedelta(days=API_TOKEN_TTL_IN_DAYS)),
)
# SentryAppInstallations are associated to ApiTokens. We're okay
# with these tokens sticking around so that the Integration can
# refresh them, but all other non-associated tokens should be
# deleted.
if model is models.ApiToken:
queryset = queryset.filter(sentry_app_installation__isnull=True)
queryset.delete()
project_id = None
if project:
click.echo(
"Bulk NodeStore deletion not available for project selection", err=True)
project_id = get_project(project)
if project_id is None:
click.echo('Error: Project not found', err=True)
raise click.Abort()
else:
if not silent:
click.echo("Removing old NodeStore values")
cutoff = timezone.now() - timedelta(days=days)
try:
nodestore.cleanup(cutoff)
except NotImplementedError:
click.echo(
"NodeStore backend does not support cleanup operation", err=True)
for bqd in BULK_QUERY_DELETES:
if len(bqd) == 4:
model, dtfield, order_by, chunk_size = bqd
else:
chunk_size = 10000
model, dtfield, order_by = bqd
if not silent:
click.echo(
u"Removing {model} for days={days} project={project}".format(
model=model.__name__,
days=days,
project=project or '*',
)
)
if is_filtered(model):
if not silent:
click.echo('>> Skipping %s' % model.__name__)
else:
BulkDeleteQuery(
model=model,
dtfield=dtfield,
days=days,
project_id=project_id,
order_by=order_by,
).execute(chunk_size=chunk_size)
for model, dtfield, order_by in DELETES:
if not silent:
click.echo(
u"Removing {model} for days={days} project={project}".format(
model=model.__name__,
days=days,
project=project or '*',
)
)
if is_filtered(model):
if not silent:
click.echo('>> Skipping %s' % model.__name__)
else:
imp = '.'.join((model.__module__, model.__name__))
q = BulkDeleteQuery(
model=model,
dtfield=dtfield,
days=days,
project_id=project_id,
order_by=order_by,
)
for chunk in q.iterator(chunk_size=100):
task_queue.put((imp, chunk))
task_queue.join()
# Clean up FileBlob instances which are no longer used and aren't super
# recent (as there could be a race between blob creation and reference)
if not silent:
click.echo("Cleaning up unused FileBlob references")
if is_filtered(models.FileBlob):
if not silent:
click.echo('>> Skipping FileBlob')
else:
cleanup_unused_files(silent)
# Shut down our pool
for _ in pool:
task_queue.put(_STOP_WORKER)
# And wait for it to drain
for p in pool:
p.join()
if timed:
duration = int(time.time() - start_time)
metrics.timing('cleanup.duration', duration, instance=router, sample_rate=1.0)
click.echo("Clean up took %s second(s)." % duration)
def cleanup_unused_files(quiet=False):
"""
Remove FileBlob's (and thus the actual files) if they are no longer
referenced by any File.
We set a minimum-age on the query to ensure that we don't try to remove
any blobs which are brand new and potentially in the process of being
referenced.
"""
from sentry.models import File, FileBlob, FileBlobIndex
if quiet:
from sentry.utils.query import RangeQuerySetWrapper
else:
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar as RangeQuerySetWrapper
cutoff = timezone.now() - timedelta(days=1)
queryset = FileBlob.objects.filter(
timestamp__lte=cutoff,
)
for blob in RangeQuerySetWrapper(queryset):
if FileBlobIndex.objects.filter(blob=blob).exists():
continue
if File.objects.filter(blob=blob).exists():
continue
blob.delete()
|
[] |
[] |
[
"_SENTRY_CLEANUP"
] |
[]
|
["_SENTRY_CLEANUP"]
|
python
| 1 | 0 | |
Text-Classification-using-NB-and-LR/Text-Classification-using-NB-and-LR-master/evaluation_metrics_discrete_naive_bayes.py
|
import bernoulli_model
import discrete_naive_bayes
import evaluation_metrics
def evaluate_discrete_NB(dataset_name):
"""
This is the method used for evaluation of multi-nomial NB on a particular dataset
:param dataset_name: This is the given dataset name
:return: We return the accuracy, precision, recall and f1_score for the given dataset
"""
# We first import training data for the training
try:
spam_email_bag_of_words, ham_email_bag_of_words, spam_mail_in_all_documents, ham_mail_in_all_documents, size_of_total_dataset, size_of_spam_dataset, size_of_ham_dataset, total_file_dictionary = bernoulli_model.convert_to_bernoulli_model(
dataset_name, True)
except:
print "You have given wrong file name, please check and run again"
exit(-1)
prior, conditional_probability, conditional_probability_of_non_occurring_word = discrete_naive_bayes.discrete_naive_bayes_train(
spam_email_bag_of_words, ham_email_bag_of_words, spam_mail_in_all_documents,
ham_mail_in_all_documents, size_of_total_dataset, size_of_spam_dataset, size_of_ham_dataset,
total_file_dictionary)
# We now import the data for testing
spam_email_bag_of_words, ham_email_bag_of_words, spam_mail_in_all_documents, ham_mail_in_all_documents, size_of_total_dataset, size_of_spam_dataset, size_of_ham_dataset, total_file_dictionary = bernoulli_model.convert_to_bernoulli_model(
dataset_name, False)
# We calculate the evaluation metric
# Here we first predict for the spam class and then the ham class
spam_predict = []
for each_document in spam_email_bag_of_words:
spam_predict.append(discrete_naive_bayes.discrete_naive_bayes_test(prior, conditional_probability,
conditional_probability_of_non_occurring_word,
each_document))
# We are taking spam as 1
spam_actual = [1] * len(spam_predict)
ham_predict = []
for each_document in ham_email_bag_of_words:
ham_predict.append(discrete_naive_bayes.discrete_naive_bayes_test(prior, conditional_probability,
conditional_probability_of_non_occurring_word,
each_document))
ham_actual = [0] * len(ham_predict)
total_actual = spam_actual + ham_actual
total_predict = spam_predict + ham_predict
# Now we predict the values for all the evaluation metrics
accuracy = evaluation_metrics.accuracy(total_actual, total_predict)
precision = evaluation_metrics.precision(total_actual, total_predict)
recall = evaluation_metrics.recall(total_actual, total_predict)
f1_score = evaluation_metrics.f1_score(recall, precision)
return accuracy, precision, recall, f1_score
# evaluate_discrete_NB(dataset_name)
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
common/service.go
|
package common
// default setting:
// Transport: tcp
// Server: rpc
// Client: rpc
// RegisterTTL: 30s
// RegisterInterval: 20s
// Registry: consul
// Broker: kafka
// Selector: cache
// Codec: protobuf
// Tracing: jaeger
// Metrics: jaeger
// breaker: hystrix 注:客户端熔断
// ratelimit: uber/ratelimit
import (
"github.com/yun-mu/MicroServicePractice/config"
"log"
"os"
"time"
gh "github.com/afex/hystrix-go/hystrix"
"github.com/micro/go-micro"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/consul"
"github.com/micro/go-micro/web"
"github.com/micro/go-plugins/broker/kafka"
"github.com/micro/go-plugins/transport/tcp"
"github.com/micro/go-plugins/wrapper/breaker/hystrix"
ratelimit "github.com/micro/go-plugins/wrapper/ratelimiter/uber"
"github.com/micro/go-plugins/wrapper/trace/opentracing"
)
var (
defaultOpts []micro.Option
defaultWebOpts []web.Option
defaultServer micro.Option
defaultClient micro.Option
)
func init() {
defaultOpts = []micro.Option{
micro.RegisterTTL(time.Second * 30),
micro.RegisterInterval(time.Second * 20),
micro.Transport(tcp.NewTransport()),
}
defaultWebOpts = []web.Option{
web.RegisterTTL(time.Second * 30),
web.RegisterInterval(time.Second * 20),
}
gh.DefaultMaxConcurrent = 100
gh.DefaultVolumeThreshold = 50
}
func GetMicroClient(service string, exOpts ...micro.Option) micro.Service {
opts := getOpts(service)
if defaultClient != nil {
opts = append(opts, defaultClient)
}
t, _, err := NewJaegerTracer(config.GetServiceName(service), config.GetTracingAddr(service))
if err != nil {
log.Fatalf("opentracing tracer create error:%v", err)
}
opts = append(opts, micro.WrapClient(hystrix.NewClientWrapper(), opentracing.NewClientWrapper(t), ratelimit.NewClientWrapper(1024)))
srv := micro.NewService(opts...)
opts = append(opts, exOpts...)
// 解析命令行参数
srv.Init()
return srv
}
func GetMicroServer(service string, exOpts ...micro.Option) micro.Service {
opts := getOpts(service)
if defaultServer != nil {
opts = append(opts, defaultServer)
}
brokerKafka := kafka.NewBroker(func(options *broker.Options) {
options.Addrs = config.GetBrokerAddrs(service)
})
if err := brokerKafka.Connect(); err != nil {
log.Fatalf("Broker Connect error: %v", err)
}
t, _, err := NewJaegerTracer(config.GetServiceName(service), config.GetTracingAddr(service))
if err != nil {
log.Fatalf("opentracing tracer create error:%v", err)
}
opts = append(opts, micro.Broker(brokerKafka), micro.WrapHandler(opentracing.NewHandlerWrapper(t), ratelimit.NewHandlerWrapper(1024)))
// 注意顺序,同样的配置后面的会将前面的覆盖
opts = append(opts, exOpts...)
srv := micro.NewService(opts...)
// 初始化,解析命令行参数
srv.Init()
return srv
}
func getOpts(service string) []micro.Option {
opts := append([]micro.Option{},
defaultOpts...,
)
version := config.GetVersion(service)
if version == "" {
version = "latest"
}
serviceName := config.GetServiceName(service)
opts = append(opts, micro.Version(version), micro.Name(serviceName))
if os.Getenv("DebugMDNS") == "" {
// 开发者可使用 micro 工具箱进行 debug, micro 默认使用的 mdns 模式
opts = append(opts, micro.Registry(consul.NewRegistry(func(op *registry.Options) {
op.Addrs = config.GetRegistryAddrs(service)
})))
}
return opts
}
func GetMicroWeb(service string, exOpts ...web.Option) web.Service {
opts := append(exOpts,
defaultWebOpts...,
)
version := config.GetVersion(service)
if version == "" {
version = "latest"
}
serviceName := config.GetServiceName(service)
opts = append(opts, web.Version(version), web.Name(serviceName))
if os.Getenv("DebugMDNS") == "" {
// 开发者可使用 micro 工具箱进行 debug, micro 默认使用的 mdns 模式
opts = append(opts, web.Registry(consul.NewRegistry(func(op *registry.Options) {
op.Addrs = config.GetRegistryAddrs(service)
})))
}
srv := web.NewService(opts...)
// 解析命令行参数
srv.Init()
return srv
}
|
[
"\"DebugMDNS\"",
"\"DebugMDNS\""
] |
[] |
[
"DebugMDNS"
] |
[]
|
["DebugMDNS"]
|
go
| 1 | 0 | |
src/mdv/globals.py
|
"""
Global data structures
"""
import os
here = os.path.realpath(__file__).rsplit(os.path.sep, 1)[0]
envget = os.environ.get
UserPlugs = set()
# the global config dict, filled by conf plugin:
C = {}
# allows chaining of actions:
ActionResults = {}
UserConfigDir = ['']
class CLI:
kv = {}
actions = []
not_conf_args = {}
class err:
is_no_plugin = 'Is no plugin'
is_no_valid_action = 'Is no valid action (no run method)'
unknown_parameters = 'Unknown parameters'
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
test/functional/test_framework/test_framework.py
|
#!/usr/bin/env python3
# Copyright (c) 2014-2016 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."""
from collections import deque
import logging
import optparse
import os
import sys
import shutil
import tempfile
import time
from .util import (
initialize_chain,
start_nodes,
connect_nodes_bi,
disconnect_nodes,
sync_blocks,
sync_mempools,
stop_nodes,
stop_node,
enable_coverage,
check_json_precision,
initialize_chain_clean,
PortSeed,
)
from .authproxy import JSONRPCException
class BitcoinTestFramework(object):
TEST_EXIT_PASSED = 0
TEST_EXIT_FAILED = 1
TEST_EXIT_SKIPPED = 77
def __init__(self):
self.num_nodes = 4
self.setup_clean_chain = False
self.nodes = None
def run_test(self):
raise NotImplementedError
def add_options(self, parser):
pass
def setup_chain(self):
self.log.info("Initializing test directory "+self.options.tmpdir)
if self.setup_clean_chain:
initialize_chain_clean(self.options.tmpdir, self.num_nodes)
else:
initialize_chain(self.options.tmpdir, self.num_nodes, self.options.cachedir)
def stop_node(self, num_node):
stop_node(self.nodes[num_node], num_node)
def setup_nodes(self):
extra_args = None
if hasattr(self, "extra_args"):
extra_args = self.extra_args
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
def setup_network(self):
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.
for i in range(self.num_nodes - 1):
connect_nodes_bi(self.nodes, i, i + 1)
self.sync_all()
def split_network(self):
"""
Split the network of four nodes into nodes 0/1 and 2/3.
"""
disconnect_nodes(self.nodes[1], 2)
disconnect_nodes(self.nodes[2], 1)
self.sync_all([self.nodes[:2], self.nodes[2:]])
def sync_all(self, node_groups=None):
if not node_groups:
node_groups = [self.nodes]
[sync_blocks(group) for group in node_groups]
[sync_mempools(group) for group in node_groups]
def join_network(self):
"""
Join the (previously split) network halves together.
"""
connect_nodes_bi(self.nodes, 1, 2)
# Only sync blocks after re-joining the network, since the mempools
# might conflict.
sync_blocks(self.nodes)
def main(self):
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave namecoinds and test.* datadir on exit or error")
parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true",
help="Don't stop namecoinds after the test execution")
parser.add_option("--srcdir", dest="srcdir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__))+"/../../../src"),
help="Source directory containing namecoind/namecoin-cli (default: %default)")
parser.add_option("--cachedir", dest="cachedir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__))+"/../../cache"),
help="Directory for caching pregenerated datadirs")
parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
help="Root directory for datadirs")
parser.add_option("-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_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
help="Print out all RPC calls as they are made")
parser.add_option("--portseed", dest="port_seed", default=os.getpid(), type='int',
help="The seed to use for assigning port numbers (default: current process id)")
parser.add_option("--coveragedir", dest="coveragedir",
help="Write tested RPC commands into this directory")
parser.add_option("--configfile", dest="configfile",
help="Location of the test framework config file")
self.add_options(parser)
(self.options, self.args) = parser.parse_args()
# backup dir variable for removal at cleanup
self.options.root, self.options.tmpdir = self.options.tmpdir, self.options.tmpdir + '/' + str(self.options.port_seed)
if self.options.coveragedir:
enable_coverage(self.options.coveragedir)
PortSeed.n = self.options.port_seed
os.environ['PATH'] = self.options.srcdir+":"+self.options.srcdir+"/qt:"+os.environ['PATH']
check_json_precision()
# Set up temp directory and start logging
os.makedirs(self.options.tmpdir, exist_ok=False)
self._start_logging()
success = False
try:
self.setup_chain()
self.setup_network()
self.run_test()
success = True
except JSONRPCException as e:
self.log.exception("JSONRPC error")
except AssertionError as e:
self.log.exception("Assertion failed")
except KeyError as e:
self.log.exception("Key error")
except Exception as e:
self.log.exception("Unexpected exception caught during testing")
except KeyboardInterrupt as e:
self.log.warning("Exiting after keyboard interrupt")
if not self.options.noshutdown:
self.log.info("Stopping nodes")
stop_nodes(self.nodes)
else:
self.log.info("Note: namecoinds were not stopped and may still be running")
if not self.options.nocleanup and not self.options.noshutdown and success:
self.log.info("Cleaning up")
shutil.rmtree(self.options.tmpdir)
if not os.listdir(self.options.root):
os.rmdir(self.options.root)
else:
self.log.warning("Not cleaning up dir %s" % self.options.tmpdir)
if os.getenv("PYTHON_DEBUG", ""):
# Dump the end of the debug logs, to aid in debugging rare
# travis failures.
import glob
filenames = [self.options.tmpdir + "/test_framework.log"]
filenames += glob.glob(self.options.tmpdir + "/node*/regtest/debug.log")
MAX_LINES_TO_PRINT = 1000
for fn in filenames:
try:
with open(fn, 'r') as f:
print("From" , fn, ":")
print("".join(deque(f, MAX_LINES_TO_PRINT)))
except OSError:
print("Opening file %s failed." % fn)
traceback.print_exc()
if success:
self.log.info("Tests successful")
sys.exit(self.TEST_EXIT_PASSED)
else:
self.log.error("Test failed. Test logging available at %s/test_framework.log", self.options.tmpdir)
logging.shutdown()
sys.exit(self.TEST_EXIT_FAILED)
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')
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 bitcoind's debug.log with microprecision (so log files can be concatenated and sorted)
formatter = logging.Formatter(fmt = '%(asctime)s.%(msecs)03d000 %(name)s (%(levelname)s): %(message)s', datefmt='%Y-%m-%d %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("BitcoinRPC")
rpc_logger.setLevel(logging.DEBUG)
rpc_handler = logging.StreamHandler(sys.stdout)
rpc_handler.setLevel(logging.DEBUG)
rpc_logger.addHandler(rpc_handler)
# Test framework for doing p2p comparison testing, which sets up some bitcoind
# binaries:
# 1 binary: test binary
# 2 binaries: 1 test binary, 1 ref binary
# n>2 binaries: 1 test binary, n-1 ref binaries
class ComparisonTestFramework(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 2
self.setup_clean_chain = True
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BITCOIND", "namecoind"),
help="namecoind binary to test")
parser.add_option("--refbinary", dest="refbinary",
default=os.getenv("BITCOIND", "namecoind"),
help="namecoind binary to use for reference nodes (if any)")
def setup_network(self):
self.nodes = start_nodes(
self.num_nodes, self.options.tmpdir,
extra_args=[['-whitelist=127.0.0.1']] * self.num_nodes,
binary=[self.options.testbinary] +
[self.options.refbinary]*(self.num_nodes-1))
|
[] |
[] |
[
"PYTHON_DEBUG",
"PATH",
"BITCOIND"
] |
[]
|
["PYTHON_DEBUG", "PATH", "BITCOIND"]
|
python
| 3 | 0 | |
vendor/github.com/ethereum/go-ethereum/cmd/geth/misccmd.go
|
// Copyright 2016 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/params"
"gopkg.in/urfave/cli.v1"
)
var (
makedagCommand = cli.Command{
Action: utils.MigrateFlags(makedag),
Name: "makedag",
Usage: "Generate ethash DAG (for testing)",
ArgsUsage: "<blockNum> <outputDir>",
Category: "MISCELLANEOUS COMMANDS",
Description: `
The makedag command generates an ethash DAG in /tmp/dag.
This command exists to support the system testing project.
Regular users do not need to execute it.
`,
}
versionCommand = cli.Command{
Action: utils.MigrateFlags(version),
Name: "version",
Usage: "Print version numbers",
ArgsUsage: " ",
Category: "MISCELLANEOUS COMMANDS",
Description: `
The output of this command is supposed to be machine-readable.
`,
}
licenseCommand = cli.Command{
Action: utils.MigrateFlags(license),
Name: "license",
Usage: "Display license information",
ArgsUsage: " ",
Category: "MISCELLANEOUS COMMANDS",
}
)
func makedag(ctx *cli.Context) error {
args := ctx.Args()
wrongArgs := func() {
utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
}
switch {
case len(args) == 2:
blockNum, err := strconv.ParseUint(args[0], 0, 64)
dir := args[1]
if err != nil {
wrongArgs()
} else {
dir = filepath.Clean(dir)
// seems to require a trailing slash
if !strings.HasSuffix(dir, "/") {
dir = dir + "/"
}
_, err = ioutil.ReadDir(dir)
if err != nil {
utils.Fatalf("Can't find dir")
}
fmt.Println("making DAG, this could take awhile...")
ethash.MakeDataset(blockNum, dir)
}
default:
wrongArgs()
}
return nil
}
func version(ctx *cli.Context) error {
fmt.Println(strings.Title(clientIdentifier))
fmt.Println("Version:", params.Version)
if gitCommit != "" {
fmt.Println("Git Commit:", gitCommit)
}
fmt.Println("Architecture:", runtime.GOARCH)
fmt.Println("Protocol Versions:", eth.ProtocolVersions)
fmt.Println("Network Id:", eth.DefaultConfig.NetworkId)
fmt.Println("Go Version:", runtime.Version())
fmt.Println("Operating System:", runtime.GOOS)
fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
return nil
}
func license(_ *cli.Context) error {
fmt.Println(`Geth is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Geth 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with geth. If not, see <http://www.gnu.org/licenses/>.
`)
return nil
}
|
[
"\"GOPATH\""
] |
[] |
[
"GOPATH"
] |
[]
|
["GOPATH"]
|
go
| 1 | 0 | |
pkg/cmd/promote/promote.go
|
package promote
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jenkins-x/jx/pkg/builds"
"github.com/jenkins-x/jx/pkg/cmd/helper"
"github.com/jenkins-x/jx/pkg/kube/naming"
"github.com/pkg/errors"
survey "gopkg.in/AlecAivazis/survey.v1"
v1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/environments"
"k8s.io/helm/pkg/proto/hapi/chart"
"github.com/jenkins-x/jx/pkg/kube/services"
"github.com/blang/semver"
typev1 "github.com/jenkins-x/jx/pkg/client/clientset/versioned/typed/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/cmd/opts"
"github.com/jenkins-x/jx/pkg/cmd/templates"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/helm"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
optionPullRequestPollTime = "pull-request-poll-time"
GitStatusSuccess = "success"
)
var (
waitAfterPullRequestCreated = time.Second * 3
)
// PromoteOptions containers the CLI options
type PromoteOptions struct {
*opts.CommonOptions
Namespace string
Environment string
Application string
Pipeline string
Build string
Version string
ReleaseName string
LocalHelmRepoName string
HelmRepositoryURL string
NoHelmUpdate bool
AllAutomatic bool
NoMergePullRequest bool
NoPoll bool
NoWaitAfterMerge bool
IgnoreLocalFiles bool
NoWaitForUpdatePipeline bool
Timeout string
PullRequestPollTime string
Filter string
Alias string
// calculated fields
TimeoutDuration *time.Duration
PullRequestPollDuration *time.Duration
Activities typev1.PipelineActivityInterface
GitInfo *gits.GitRepository
jenkinsURL string
releaseResource *v1.Release
ReleaseInfo *ReleaseInfo
prow bool
}
type ReleaseInfo struct {
ReleaseName string
FullAppName string
Version string
PullRequestInfo *gits.PullRequestInfo
}
var (
promote_long = templates.LongDesc(`
Promotes a version of an application to zero to many permanent environments.
For more documentation see: [https://jenkins-x.io/about/features/#promotion](https://jenkins-x.io/about/features/#promotion)
`)
promote_example = templates.Examples(`
# Promote a version of the current application to staging
# discovering the application name from the source code
jx promote --version 1.2.3 --env staging
# Promote a version of the myapp application to production
jx promote myapp --version 1.2.3 --env production
# To search for all the available charts for a given name use -f.
# e.g. to find a redis chart to install
jx promote -f redis
# To promote a postgres chart using an alias
jx promote -f postgres --alias mydb
# To create or update a Preview Environment please see the 'jx preview' command
jx preview
`)
)
// NewCmdPromote creates the new command for: jx get prompt
func NewCmdPromote(commonOpts *opts.CommonOptions) *cobra.Command {
options := &PromoteOptions{
CommonOptions: commonOpts,
}
cmd := &cobra.Command{
Use: "promote [application]",
Short: "Promotes a version of an application to an Environment",
Long: promote_long,
Example: promote_example,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "The Namespace to promote to")
cmd.Flags().StringVarP(&options.Environment, opts.OptionEnvironment, "e", "", "The Environment to promote to")
cmd.Flags().BoolVarP(&options.AllAutomatic, "all-auto", "", false, "Promote to all automatic environments in order")
options.AddPromoteOptions(cmd)
return cmd
}
// AddPromoteOptions adds command level options to `promote`
func (o *PromoteOptions) AddPromoteOptions(cmd *cobra.Command) {
cmd.Flags().StringVarP(&o.Application, opts.OptionApplication, "a", "", "The Application to promote")
cmd.Flags().StringVarP(&o.Filter, "filter", "f", "", "The search filter to find charts to promote")
cmd.Flags().StringVarP(&o.Alias, "alias", "", "", "The optional alias used in the 'requirements.yaml' file")
cmd.Flags().StringVarP(&o.Pipeline, "pipeline", "", "", "The Pipeline string in the form 'folderName/repoName/branch' which is used to update the PipelineActivity. If not specified its defaulted from the '$BUILD_NUMBER' environment variable")
cmd.Flags().StringVarP(&o.Build, "build", "", "", "The Build number which is used to update the PipelineActivity. If not specified its defaulted from the '$BUILD_NUMBER' environment variable")
cmd.Flags().StringVarP(&o.Version, "version", "v", "", "The Version to promote")
cmd.Flags().StringVarP(&o.LocalHelmRepoName, "helm-repo-name", "r", kube.LocalHelmRepoName, "The name of the helm repository that contains the app")
cmd.Flags().StringVarP(&o.HelmRepositoryURL, "helm-repo-url", "u", "", "The Helm Repository URL to use for the App")
cmd.Flags().StringVarP(&o.ReleaseName, "release", "", "", "The name of the helm release")
cmd.Flags().StringVarP(&o.Timeout, opts.OptionTimeout, "t", "1h", "The timeout to wait for the promotion to succeed in the underlying Environment. The command fails if the timeout is exceeded or the promotion does not complete")
cmd.Flags().StringVarP(&o.PullRequestPollTime, optionPullRequestPollTime, "", "20s", "Poll time when waiting for a Pull Request to merge")
cmd.Flags().BoolVarP(&o.NoHelmUpdate, "no-helm-update", "", false, "Allows the 'helm repo update' command if you are sure your local helm cache is up to date with the version you wish to promote")
cmd.Flags().BoolVarP(&o.NoMergePullRequest, "no-merge", "", false, "Disables automatic merge of promote Pull Requests")
cmd.Flags().BoolVarP(&o.NoPoll, "no-poll", "", false, "Disables polling for Pull Request or Pipeline status")
cmd.Flags().BoolVarP(&o.NoWaitAfterMerge, "no-wait", "", false, "Disables waiting for completing promotion after the Pull request is merged")
cmd.Flags().BoolVarP(&o.IgnoreLocalFiles, "ignore-local-file", "", false, "Ignores the local file system when deducing the Git repository")
}
func (o *PromoteOptions) hasApplicationFlag() bool {
return o.Application != ""
}
func (o *PromoteOptions) hasArgs() bool {
return len(o.Args) > 0
}
func (o *PromoteOptions) setApplicationNameFromArgs() {
o.Application = o.Args[0]
}
func (o *PromoteOptions) hasFilterFlag() bool {
return o.Filter != ""
}
type searchForChartFn func(filter string) (string, error)
func (o *PromoteOptions) setApplicationNameFromFilter(searchForChart searchForChartFn) error {
app, err := searchForChart(o.Filter)
if err != nil {
return errors.Wrap(err, "searching app name in chart failed")
}
o.Application = app
return nil
}
type discoverAppNameFn func() (string, error)
func (o *PromoteOptions) setApplicationNameFromDiscoveredAppName(discoverAppName discoverAppNameFn) error {
app, err := discoverAppName()
if err != nil {
return errors.Wrap(err, "discovering app name failed")
}
if !o.BatchMode {
var continueWithAppName bool
question := fmt.Sprintf("Are you sure you want to promote the application named: %s?", app)
prompt := &survey.Confirm{
Message: question,
Default: true,
}
surveyOpts := survey.WithStdio(o.In, o.Out, o.Err)
err = survey.AskOne(prompt, &continueWithAppName, nil, surveyOpts)
if err != nil {
return err
}
if !continueWithAppName {
return errors.New("user canceled execution")
}
}
o.Application = app
return nil
}
// EnsureApplicationNameIsDefined validates if an application name flag was provided by the user. If missing it will
// try to set it up or return an error
func (o *PromoteOptions) EnsureApplicationNameIsDefined(sf searchForChartFn, df discoverAppNameFn) error {
if !o.hasApplicationFlag() && o.hasArgs() {
o.setApplicationNameFromArgs()
}
if !o.hasApplicationFlag() && o.hasFilterFlag() {
err := o.setApplicationNameFromFilter(sf)
if err != nil {
return err
}
}
if !o.hasApplicationFlag() {
return o.setApplicationNameFromDiscoveredAppName(df)
}
return nil
}
// Run implements this command
func (o *PromoteOptions) Run() error {
err := o.EnsureApplicationNameIsDefined(o.SearchForChart, o.DiscoverAppName)
if err != nil {
return err
}
jxClient, ns, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
if o.Namespace == "" {
o.Namespace = ns
}
prow, err := o.IsProw()
if err != nil {
return err
}
if prow {
o.prow = true
log.Logger().Warn("prow based install so skip waiting for the merge of Pull Requests to go green as currently there is an issue with getting" +
"statuses from the PR, see https://github.com/jenkins-x/jx/issues/2410")
o.NoWaitForUpdatePipeline = true
}
if o.HelmRepositoryURL == "" {
o.HelmRepositoryURL = o.DefaultChartRepositoryURL()
}
if o.Environment == "" && !o.BatchMode {
names := []string{}
m, allEnvNames, err := kube.GetOrderedEnvironments(jxClient, ns)
if err != nil {
return err
}
for _, n := range allEnvNames {
env := m[n]
if env.Spec.Kind == v1.EnvironmentKindTypePermanent {
names = append(names, n)
}
}
o.Environment, err = kube.PickEnvironment(names, "", o.GetIOFileHandles())
if err != nil {
return err
}
}
if o.PullRequestPollTime != "" {
duration, err := time.ParseDuration(o.PullRequestPollTime)
if err != nil {
return fmt.Errorf("Invalid duration format %s for option --%s: %s", o.PullRequestPollTime, optionPullRequestPollTime, err)
}
o.PullRequestPollDuration = &duration
}
if o.Timeout != "" {
duration, err := time.ParseDuration(o.Timeout)
if err != nil {
return fmt.Errorf("Invalid duration format %s for option --%s: %s", o.Timeout, opts.OptionTimeout, err)
}
o.TimeoutDuration = &duration
}
targetNS, env, err := o.GetTargetNamespace(o.Namespace, o.Environment)
if err != nil {
return err
}
o.Activities = jxClient.JenkinsV1().PipelineActivities(ns)
releaseName := o.ReleaseName
if releaseName == "" {
releaseName = targetNS + "-" + o.Application
o.ReleaseName = releaseName
}
if o.AllAutomatic {
return o.PromoteAllAutomatic()
}
if env == nil {
if o.Environment == "" {
return util.MissingOption(opts.OptionEnvironment)
}
env, err := jxClient.JenkinsV1().Environments(ns).Get(o.Environment, metav1.GetOptions{})
if err != nil {
return err
}
if env == nil {
return fmt.Errorf("Could not find an Environment called %s", o.Environment)
}
}
releaseInfo, err := o.Promote(targetNS, env, true)
if err != nil {
return err
}
o.ReleaseInfo = releaseInfo
if !o.NoPoll {
err = o.WaitForPromotion(targetNS, env, releaseInfo)
if err != nil {
return err
}
}
return err
}
func (o *PromoteOptions) PromoteAllAutomatic() error {
kubeClient, currentNs, err := o.KubeClientAndNamespace()
if err != nil {
return err
}
team, _, err := kube.GetDevNamespace(kubeClient, currentNs)
if err != nil {
return err
}
jxClient, _, err := o.JXClient()
if err != nil {
return err
}
envs, err := jxClient.JenkinsV1().Environments(team).List(metav1.ListOptions{})
if err != nil {
log.Logger().Warnf("No Environments found: %s/n", err)
return nil
}
environments := envs.Items
if len(environments) == 0 {
log.Logger().Warnf("No Environments have been created yet in team %s. Please create some via 'jx create env'", team)
return nil
}
kube.SortEnvironments(environments)
for _, env := range environments {
kind := env.Spec.Kind
if env.Spec.PromotionStrategy == v1.PromotionStrategyTypeAutomatic && kind.IsPermanent() {
ns := env.Spec.Namespace
if ns == "" {
return fmt.Errorf("No namespace for environment %s", env.Name)
}
releaseInfo, err := o.Promote(ns, &env, false)
if err != nil {
return err
}
o.ReleaseInfo = releaseInfo
if !o.NoPoll {
err = o.WaitForPromotion(ns, &env, releaseInfo)
if err != nil {
return err
}
}
}
}
return nil
}
func (o *PromoteOptions) Promote(targetNS string, env *v1.Environment, warnIfAuto bool) (*ReleaseInfo, error) {
surveyOpts := survey.WithStdio(o.In, o.Out, o.Err)
app := o.Application
if app == "" {
log.Logger().Warnf("No application name could be detected so cannot promote via Helm. If the detection of the helm chart name is not working consider adding it with the --%s argument on the 'jx promote' command", opts.OptionApplication)
return nil, nil
}
version := o.Version
info := util.ColorInfo
if version == "" {
log.Logger().Infof("Promoting latest version of app %s to namespace %s", info(app), info(targetNS))
} else {
log.Logger().Infof("Promoting app %s version %s to namespace %s", info(app), info(version), info(targetNS))
}
fullAppName := app
if o.LocalHelmRepoName != "" {
fullAppName = o.LocalHelmRepoName + "/" + app
}
releaseName := o.ReleaseName
if releaseName == "" {
releaseName = targetNS + "-" + app
o.ReleaseName = releaseName
}
releaseInfo := &ReleaseInfo{
ReleaseName: releaseName,
FullAppName: fullAppName,
Version: version,
}
if warnIfAuto && env != nil && env.Spec.PromotionStrategy == v1.PromotionStrategyTypeAutomatic && !o.BatchMode {
log.Logger().Infof("%s", util.ColorWarning(fmt.Sprintf("WARNING: The Environment %s is setup to promote automatically as part of the CI/CD Pipelines.\n", env.Name)))
confirm := &survey.Confirm{
Message: "Do you wish to promote anyway? :",
Default: false,
}
flag := false
err := survey.AskOne(confirm, &flag, nil, surveyOpts)
if err != nil {
return releaseInfo, err
}
if !flag {
return releaseInfo, nil
}
}
jxClient, _, err := o.JXClient()
if err != nil {
return releaseInfo, err
}
kubeClient, err := o.KubeClient()
if err != nil {
return releaseInfo, err
}
promoteKey := o.CreatePromoteKey(env)
if env != nil {
source := &env.Spec.Source
if source.URL != "" && env.Spec.Kind.IsPermanent() {
err := o.PromoteViaPullRequest(env, releaseInfo)
if err == nil {
startPromotePR := func(a *v1.PipelineActivity, s *v1.PipelineActivityStep, ps *v1.PromoteActivityStep, p *v1.PromotePullRequestStep) error {
kube.StartPromotionPullRequest(a, s, ps, p)
pr := releaseInfo.PullRequestInfo
if pr != nil && pr.PullRequest != nil && p.PullRequestURL == "" {
p.PullRequestURL = pr.PullRequest.URL
}
if version != "" && a.Spec.Version == "" {
a.Spec.Version = version
}
return nil
}
err = promoteKey.OnPromotePullRequest(kubeClient, jxClient, o.Namespace, startPromotePR)
if err != nil {
log.Logger().Warnf("Failed to update PipelineActivity: %s", err)
}
// lets sleep a little before we try poll for the PR status
time.Sleep(waitAfterPullRequestCreated)
}
return releaseInfo, err
}
}
err = o.verifyHelmConfigured()
if err != nil {
return releaseInfo, err
}
// lets do a helm update to ensure we can find the latest version
if !o.NoHelmUpdate {
log.Logger().Info("Updating the helm repositories to ensure we can find the latest versions...")
err = o.Helm().UpdateRepo()
if err != nil {
return releaseInfo, err
}
}
startPromote := func(a *v1.PipelineActivity, s *v1.PipelineActivityStep, ps *v1.PromoteActivityStep, p *v1.PromoteUpdateStep) error {
kube.StartPromotionUpdate(a, s, ps, p)
if version != "" && a.Spec.Version == "" {
a.Spec.Version = version
}
return nil
}
promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, startPromote)
helmOptions := helm.InstallChartOptions{
Chart: fullAppName,
ReleaseName: releaseName,
Ns: targetNS,
Version: version,
NoForce: true,
Wait: true,
}
err = o.InstallChartWithOptions(helmOptions)
if err == nil {
err = o.CommentOnIssues(targetNS, env, promoteKey)
if err != nil {
log.Logger().Warnf("Failed to comment on issues for release %s: %s", releaseName, err)
}
err = promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, kube.CompletePromotionUpdate)
} else {
err = promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, kube.FailedPromotionUpdate)
}
return releaseInfo, err
}
func (o *PromoteOptions) PromoteViaPullRequest(env *v1.Environment, releaseInfo *ReleaseInfo) error {
version := o.Version
versionName := version
if versionName == "" {
versionName = "latest"
}
app := o.Application
details := gits.PullRequestDetails{
BranchName: "promote-" + app + "-" + versionName,
Title: "chore: " + app + " to " + versionName,
Message: fmt.Sprintf("chore: Promote %s to version %s", app, versionName),
}
modifyChartFn := func(requirements *helm.Requirements, metadata *chart.Metadata, values map[string]interface{},
templates map[string]string, dir string, details *gits.PullRequestDetails) error {
var err error
if version == "" {
version, err = o.findLatestVersion(app)
if err != nil {
return err
}
}
requirements.SetAppVersion(app, version, o.HelmRepositoryURL, o.Alias)
return nil
}
gitProvider, _, err := o.CreateGitProviderForURLWithoutKind(env.Spec.Source.URL)
if err != nil {
return errors.Wrapf(err, "creating git provider for %s", env.Spec.Source.URL)
}
environmentsDir, err := o.EnvironmentsDir()
if err != nil {
return errors.Wrapf(err, "getting environments dir")
}
options := environments.EnvironmentPullRequestOptions{
Gitter: o.Git(),
ModifyChartFn: modifyChartFn,
GitProvider: gitProvider,
}
filter := &gits.PullRequestFilter{}
if releaseInfo.PullRequestInfo != nil && releaseInfo.PullRequestInfo.PullRequest != nil {
filter.Number = releaseInfo.PullRequestInfo.PullRequest.Number
}
info, err := options.Create(env, environmentsDir, &details, filter, "", true)
releaseInfo.PullRequestInfo = info
return err
}
func (o *PromoteOptions) GetTargetNamespace(ns string, env string) (string, *v1.Environment, error) {
kubeClient, currentNs, err := o.KubeClientAndNamespace()
if err != nil {
return "", nil, err
}
team, _, err := kube.GetDevNamespace(kubeClient, currentNs)
if err != nil {
return "", nil, err
}
jxClient, _, err := o.JXClient()
if err != nil {
return "", nil, err
}
m, envNames, err := kube.GetEnvironments(jxClient, team)
if err != nil {
return "", nil, err
}
if len(envNames) == 0 {
return "", nil, fmt.Errorf("No Environments have been created yet in team %s. Please create some via 'jx create env'", team)
}
var envResource *v1.Environment
targetNS := currentNs
if env != "" {
envResource = m[env]
if envResource == nil {
return "", nil, util.InvalidOption(opts.OptionEnvironment, env, envNames)
}
targetNS = envResource.Spec.Namespace
if targetNS == "" {
return "", nil, fmt.Errorf("environment %s does not have a namespace associated with it!", env)
}
} else if ns != "" {
targetNS = ns
}
labels := map[string]string{}
annotations := map[string]string{}
err = kube.EnsureNamespaceCreated(kubeClient, targetNS, labels, annotations)
if err != nil {
return "", nil, err
}
return targetNS, envResource, nil
}
func (o *PromoteOptions) WaitForPromotion(ns string, env *v1.Environment, releaseInfo *ReleaseInfo) error {
if o.TimeoutDuration == nil {
log.Logger().Infof("No --%s option specified on the 'jx promote' command so not waiting for the promotion to succeed", opts.OptionTimeout)
return nil
}
if o.PullRequestPollDuration == nil {
log.Logger().Infof("No --%s option specified on the 'jx promote' command so not waiting for the promotion to succeed", optionPullRequestPollTime)
return nil
}
duration := *o.TimeoutDuration
end := time.Now().Add(duration)
jxClient, _, err := o.JXClient()
if err != nil {
return errors.Wrap(err, "Getting jx client")
}
kubeClient, err := o.KubeClient()
if err != nil {
return errors.Wrap(err, "Getting kube client")
}
pullRequestInfo := releaseInfo.PullRequestInfo
if pullRequestInfo != nil {
promoteKey := o.CreatePromoteKey(env)
err := o.waitForGitOpsPullRequest(ns, env, releaseInfo, end, duration, promoteKey)
if err != nil {
// TODO based on if the PR completed or not fail the PR or the Promote?
promoteKey.OnPromotePullRequest(kubeClient, jxClient, o.Namespace, kube.FailedPromotionPullRequest)
return err
}
}
return nil
}
// TODO This could do with a refactor and some tests...
func (o *PromoteOptions) waitForGitOpsPullRequest(ns string, env *v1.Environment, releaseInfo *ReleaseInfo, end time.Time, duration time.Duration, promoteKey *kube.PromoteStepActivityKey) error {
pullRequestInfo := releaseInfo.PullRequestInfo
logMergeFailure := false
logNoMergeCommitSha := false
logHasMergeSha := false
logMergeStatusError := false
logNoMergeStatuses := false
urlStatusMap := map[string]string{}
urlStatusTargetURLMap := map[string]string{}
jxClient, _, err := o.JXClient()
if err != nil {
return errors.Wrap(err, "Getting jx client")
}
kubeClient, err := o.KubeClient()
if err != nil {
return errors.Wrapf(err, "Getting kube client")
}
if pullRequestInfo != nil {
for {
pr := pullRequestInfo.PullRequest
gitProvider := pullRequestInfo.GitProvider
err := gitProvider.UpdatePullRequestStatus(pr)
if err != nil {
log.Logger().Warnf("Failed to query the Pull Request status for %s %s", pr.URL, err)
} else {
if pr.Merged != nil && *pr.Merged {
if pr.MergeCommitSHA == nil {
if !logNoMergeCommitSha {
logNoMergeCommitSha = true
log.Logger().Infof("Pull Request %s is merged but waiting for Merge SHA", util.ColorInfo(pr.URL))
}
} else {
mergeSha := *pr.MergeCommitSHA
if !logHasMergeSha {
logHasMergeSha = true
log.Logger().Infof("Pull Request %s is merged at sha %s", util.ColorInfo(pr.URL), util.ColorInfo(mergeSha))
mergedPR := func(a *v1.PipelineActivity, s *v1.PipelineActivityStep, ps *v1.PromoteActivityStep, p *v1.PromotePullRequestStep) error {
kube.CompletePromotionPullRequest(a, s, ps, p)
p.MergeCommitSHA = mergeSha
return nil
}
promoteKey.OnPromotePullRequest(kubeClient, jxClient, o.Namespace, mergedPR)
if o.NoWaitAfterMerge {
log.Logger().Infof("Pull requests are merged, No wait on promotion to complete")
return err
}
}
promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, kube.StartPromotionUpdate)
if o.NoWaitForUpdatePipeline {
log.Logger().Info("Pull Request merged but we are not waiting for the update pipeline to complete!")
err = o.CommentOnIssues(ns, env, promoteKey)
if err == nil {
err = promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, kube.CompletePromotionUpdate)
}
return err
}
statuses, err := gitProvider.ListCommitStatus(pr.Owner, pr.Repo, mergeSha)
if err != nil {
if !logMergeStatusError {
logMergeStatusError = true
log.Logger().Warnf("Failed to query merge status of repo %s/%s with merge sha %s due to: %s", pr.Owner, pr.Repo, mergeSha, err)
}
} else {
if len(statuses) == 0 {
if !logNoMergeStatuses {
logNoMergeStatuses = true
log.Logger().Infof("Merge commit has not yet any statuses on repo %s/%s merge sha %s", pr.Owner, pr.Repo, mergeSha)
}
} else {
for _, status := range statuses {
if status.IsFailed() {
log.Logger().Warnf("merge status: %s URL: %s description: %s",
status.State, status.TargetURL, status.Description)
return fmt.Errorf("Status: %s URL: %s description: %s\n",
status.State, status.TargetURL, status.Description)
}
url := status.URL
state := status.State
if urlStatusMap[url] == "" || urlStatusMap[url] != GitStatusSuccess {
if urlStatusMap[url] != state {
urlStatusMap[url] = state
urlStatusTargetURLMap[url] = status.TargetURL
log.Logger().Infof("merge status: %s for URL %s with target: %s description: %s",
util.ColorInfo(state), util.ColorInfo(status.URL), util.ColorInfo(status.TargetURL), util.ColorInfo(status.Description))
}
}
}
prStatuses := []v1.GitStatus{}
keys := util.SortedMapKeys(urlStatusMap)
for _, url := range keys {
state := urlStatusMap[url]
targetURL := urlStatusTargetURLMap[url]
if targetURL == "" {
targetURL = url
}
prStatuses = append(prStatuses, v1.GitStatus{
URL: targetURL,
Status: state,
})
}
updateStatuses := func(a *v1.PipelineActivity, s *v1.PipelineActivityStep, ps *v1.PromoteActivityStep, p *v1.PromoteUpdateStep) error {
p.Statuses = prStatuses
return nil
}
promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, updateStatuses)
succeeded := true
for _, v := range urlStatusMap {
if v != GitStatusSuccess {
succeeded = false
}
}
if succeeded {
log.Logger().Info("Merge status checks all passed so the promotion worked!")
err = o.CommentOnIssues(ns, env, promoteKey)
if err == nil {
err = promoteKey.OnPromoteUpdate(kubeClient, jxClient, o.Namespace, kube.CompletePromotionUpdate)
}
return err
}
}
}
}
} else {
if pr.IsClosed() {
log.Logger().Warnf("Pull Request %s is closed", util.ColorInfo(pr.URL))
return fmt.Errorf("Promotion failed as Pull Request %s is closed without merging", pr.URL)
}
// lets try merge if the status is good
status, err := gitProvider.PullRequestLastCommitStatus(pr)
if err != nil {
log.Logger().Warnf("Failed to query the Pull Request last commit status for %s ref %s %s", pr.URL, pr.LastCommitSha, err)
//return fmt.Errorf("Failed to query the Pull Request last commit status for %s ref %s %s", pr.URL, pr.LastCommitSha, err)
} else if status == "in-progress" {
log.Logger().Info("The build for the Pull Request last commit is currently in progress.")
} else {
if status == "success" {
if !(o.NoMergePullRequest) {
tideMerge := false
// Now check if tide is running or not
commitStatues, err := gitProvider.ListCommitStatus(pr.Owner, pr.Repo, pr.LastCommitSha)
if err != nil {
log.Logger().Warnf("unable to get commit statuses for %s", pr.URL)
} else {
for _, s := range commitStatues {
if s.State == "tide" {
tideMerge = true
break
}
}
}
if !tideMerge {
err = gitProvider.MergePullRequest(pr, "jx promote automatically merged promotion PR")
if err != nil {
if !logMergeFailure {
logMergeFailure = true
log.Logger().Warnf("Failed to merge the Pull Request %s due to %s maybe I don't have karma?", pr.URL, err)
}
}
}
}
} else if status == "error" || status == "failure" {
return fmt.Errorf("Pull request %s last commit has status %s for ref %s", pr.URL, status, pr.LastCommitSha)
} else {
log.Logger().Infof("got git provider status %s from PR %s", status, pr.URL)
}
}
}
if pr.Mergeable != nil && !*pr.Mergeable {
log.Logger().Info("Rebasing PullRequest due to conflict")
err = o.PromoteViaPullRequest(env, releaseInfo)
if releaseInfo.PullRequestInfo != nil {
pullRequestInfo = releaseInfo.PullRequestInfo
}
}
}
if time.Now().After(end) {
return fmt.Errorf("Timed out waiting for pull request %s to merge. Waited %s", pr.URL, duration.String())
}
time.Sleep(*o.PullRequestPollDuration)
}
}
return nil
}
func (o *PromoteOptions) findLatestVersion(app string) (string, error) {
charts, err := o.Helm().SearchCharts(app, true)
if err != nil {
return "", err
}
var maxSemVer *semver.Version
maxString := ""
for _, chart := range charts {
sv, err := semver.Parse(chart.ChartVersion)
if err != nil {
log.Logger().Warnf("Invalid semantic version: %s %s", chart.ChartVersion, err)
if maxString == "" || strings.Compare(chart.ChartVersion, maxString) > 0 {
maxString = chart.ChartVersion
}
} else {
if maxSemVer == nil || maxSemVer.Compare(sv) > 0 {
maxSemVer = &sv
}
}
}
if maxSemVer != nil {
return maxSemVer.String(), nil
}
if maxString == "" {
return "", fmt.Errorf("Could not find a version of app %s in the helm repositories", app)
}
return maxString, nil
}
func (o *PromoteOptions) verifyHelmConfigured() error {
helmHomeDir := filepath.Join(util.HomeDir(), ".helm")
exists, err := util.FileExists(helmHomeDir)
if err != nil {
return err
}
if !exists {
log.Logger().Warnf("No helm home dir at %s so lets initialise helm client", helmHomeDir)
err = o.HelmInit("")
if err != nil {
return err
}
}
_, ns, _ := o.KubeClientAndNamespace()
if err != nil {
return err
}
// lets add the releases chart
return o.RegisterLocalHelmRepo(o.LocalHelmRepoName, ns)
}
func (o *PromoteOptions) CreatePromoteKey(env *v1.Environment) *kube.PromoteStepActivityKey {
pipeline := o.Pipeline
if o.Build == "" {
o.Build = builds.GetBuildNumber()
}
build := o.Build
buildURL := os.Getenv("BUILD_URL")
buildLogsURL := os.Getenv("BUILD_LOG_URL")
releaseNotesURL := ""
gitInfo := o.GitInfo
if !o.IgnoreLocalFiles {
var err error
gitInfo, err = o.Git().Info("")
releaseName := o.ReleaseName
if o.releaseResource == nil && releaseName != "" {
jxClient, _, err := o.JXClient()
if err == nil && jxClient != nil {
release, err := jxClient.JenkinsV1().Releases(env.Spec.Namespace).Get(releaseName, metav1.GetOptions{})
if err == nil && release != nil {
o.releaseResource = release
}
}
}
if o.releaseResource != nil {
releaseNotesURL = o.releaseResource.Spec.ReleaseNotesURL
}
if err != nil {
log.Logger().Warnf("Could not discover the Git repository info %s", err)
} else {
o.GitInfo = gitInfo
}
}
if pipeline == "" {
pipeline, build = o.GetPipelineName(gitInfo, pipeline, build, o.Application)
}
if pipeline != "" && build == "" {
log.Logger().Warnf("No $BUILD_NUMBER environment variable found so cannot record promotion activities into the PipelineActivity resources in kubernetes")
var err error
build, err = o.GetLatestPipelineBuildByCRD(pipeline)
if err != nil {
log.Logger().Warnf("Could not discover the latest PipelineActivity build %s", err)
}
}
name := pipeline
if build != "" {
name += "-" + build
if (buildURL == "" || buildLogsURL == "") && !o.prow {
jenkinsURL := o.getAndUpdateJenkinsURL()
if jenkinsURL != "" {
path := pipeline
if !strings.HasPrefix(path, "job/") && !strings.HasPrefix(path, "/job/") {
// lets split the path and prefix it with /job
path = strings.Join(strings.Split(path, "/"), "/job/")
path = util.UrlJoin("job", path)
}
path = util.UrlJoin(path, build)
if !strings.HasSuffix(path, "/") {
path += "/"
}
if buildURL == "" {
buildURL = util.UrlJoin(jenkinsURL, path)
}
if buildLogsURL == "" {
buildLogsURL = util.UrlJoin(buildURL, "console")
}
}
}
}
name = naming.ToValidName(name)
log.Logger().Debugf("Using pipeline: %s build: %s", util.ColorInfo(pipeline), util.ColorInfo("#"+build))
return &kube.PromoteStepActivityKey{
PipelineActivityKey: kube.PipelineActivityKey{
Name: name,
Pipeline: pipeline,
Build: build,
BuildURL: buildURL,
BuildLogsURL: buildLogsURL,
GitInfo: gitInfo,
ReleaseNotesURL: releaseNotesURL,
},
Environment: env.Name,
}
}
func (o *PromoteOptions) getAndUpdateJenkinsURL() string {
if o.jenkinsURL == "" {
o.jenkinsURL = os.Getenv("JENKINS_URL")
}
url, err := o.GetJenkinsURL()
if err != nil {
log.Logger().Warnf("Could not find Jenkins URL: %s", err)
} else {
o.jenkinsURL = url
}
return o.jenkinsURL
}
// CommentOnIssues comments on any issues for a release that the fix is available in the given environment
func (o *PromoteOptions) CommentOnIssues(targetNS string, environment *v1.Environment, promoteKey *kube.PromoteStepActivityKey) error {
ens := environment.Spec.Namespace
envName := environment.Spec.Label
app := o.Application
version := o.Version
if ens == "" {
log.Logger().Warnf("Environment %s has no namespace", envName)
return nil
}
if app == "" {
log.Logger().Warnf("No application name so cannot comment on issues that they are now in %s", envName)
return nil
}
if version == "" {
log.Logger().Warnf("No version name so cannot comment on issues that they are now in %s", envName)
return nil
}
gitInfo := o.GitInfo
if gitInfo == nil {
log.Logger().Warnf("No GitInfo discovered so cannot comment on issues that they are now in %s", envName)
return nil
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return err
}
gitKind, err := o.GitServerKind(gitInfo)
if err != nil {
return err
}
provider, err := gitInfo.PickOrCreateProvider(authConfigSvc, "user name to comment on issues", o.BatchMode, gitKind, o.Git(), o.GetIOFileHandles())
if err != nil {
return err
}
releaseName := naming.ToValidNameWithDots(app + "-" + version)
jxClient, _, err := o.JXClient()
if err != nil {
return err
}
kubeClient, err := o.KubeClient()
if err != nil {
return err
}
appNames := []string{app, o.ReleaseName, ens + "-" + app}
url := ""
for _, n := range appNames {
url, err = services.FindServiceURL(kubeClient, ens, n)
if url != "" {
break
}
}
if url == "" {
log.Logger().Warnf("Could not find the service URL in namespace %s for names %s", ens, strings.Join(appNames, ", "))
}
available := ""
if url != "" {
available = fmt.Sprintf(" and available [here](%s)", url)
}
if available == "" {
ing, err := kubeClient.ExtensionsV1beta1().Ingresses(ens).Get(app, metav1.GetOptions{})
if err != nil || ing == nil && o.ReleaseName != "" && o.ReleaseName != app {
ing, err = kubeClient.ExtensionsV1beta1().Ingresses(ens).Get(o.ReleaseName, metav1.GetOptions{})
}
if ing != nil {
if len(ing.Spec.Rules) > 0 {
hostname := ing.Spec.Rules[0].Host
if hostname != "" {
available = fmt.Sprintf(" and available at %s", hostname)
url = hostname
}
}
}
}
// lets try update the PipelineActivity
if url != "" && promoteKey.ApplicationURL == "" {
promoteKey.ApplicationURL = url
log.Logger().Debugf("Application is available at: %s", util.ColorInfo(url))
}
release, err := jxClient.JenkinsV1().Releases(ens).Get(releaseName, metav1.GetOptions{})
if err == nil && release != nil {
o.releaseResource = release
issues := release.Spec.Issues
versionMessage := version
if release.Spec.ReleaseNotesURL != "" {
versionMessage = "[" + version + "](" + release.Spec.ReleaseNotesURL + ")"
}
for _, issue := range issues {
if issue.IsClosed() {
log.Logger().Infof("Commenting that issue %s is now in %s", util.ColorInfo(issue.URL), util.ColorInfo(envName))
comment := fmt.Sprintf(":white_check_mark: the fix for this issue is now deployed to **%s** in version %s %s", envName, versionMessage, available)
id := issue.ID
if id != "" {
number, err := strconv.Atoi(id)
if err != nil {
log.Logger().Warnf("Could not parse issue id %s for URL %s", id, issue.URL)
} else {
if number > 0 {
err = provider.CreateIssueComment(gitInfo.Organisation, gitInfo.Name, number, comment)
if err != nil {
log.Logger().Warnf("Failed to add comment to issue %s: %s", issue.URL, err)
}
}
}
}
}
}
}
return nil
}
func (o *PromoteOptions) SearchForChart(filter string) (string, error) {
answer := ""
charts, err := o.Helm().SearchCharts(filter, false)
if err != nil {
return answer, err
}
if len(charts) == 0 {
return answer, fmt.Errorf("No charts available for search filter: %s", filter)
}
m := map[string]*helm.ChartSummary{}
names := []string{}
for i, chart := range charts {
text := chart.Name
if chart.Description != "" {
text = fmt.Sprintf("%-36s: %s", chart.Name, chart.Description)
}
names = append(names, text)
m[text] = &charts[i]
}
name, err := util.PickName(names, "Pick chart to promote: ", "", o.GetIOFileHandles())
if err != nil {
return answer, err
}
chart := m[name]
chartName := chart.Name
// TODO now we split the chart into name and repo
parts := strings.Split(chartName, "/")
if len(parts) != 2 {
return answer, fmt.Errorf("Invalid chart name '%s' was expecting single / character separating repo name and chart name", chartName)
}
repoName := parts[0]
appName := parts[1]
repos, err := o.Helm().ListRepos()
if err != nil {
return answer, err
}
repoUrl := repos[repoName]
if repoUrl == "" {
return answer, fmt.Errorf("Failed to find helm chart repo URL for '%s' when possible values are %s", repoName, util.SortedMapKeys(repos))
}
o.Version = chart.ChartVersion
o.HelmRepositoryURL = repoUrl
return appName, nil
}
|
[
"\"BUILD_URL\"",
"\"BUILD_LOG_URL\"",
"\"JENKINS_URL\""
] |
[] |
[
"JENKINS_URL",
"BUILD_URL",
"BUILD_LOG_URL"
] |
[]
|
["JENKINS_URL", "BUILD_URL", "BUILD_LOG_URL"]
|
go
| 3 | 0 | |
utils.py
|
#MIT License
#Copyright (c) 2021 SUBIN
#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
from config import Config
import ffmpeg
from pyrogram import emoji
from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR
from pytgcalls import GroupCallFactory
import wget
from asyncio import sleep
from pyrogram import Client
from pyrogram.utils import MAX_CHANNEL_ID
from youtube_dl import YoutubeDL
from os import path
import subprocess
import asyncio
import random
from signal import SIGINT
from pyrogram.raw.types import InputGroupCall
from pyrogram.raw.functions.phone import EditGroupCallTitle, CreateGroupCall
from random import randint
bot = Client(
"Musicplayervc",
Config.API_ID,
Config.API_HASH,
bot_token=Config.BOT_TOKEN
)
bot.start()
e=bot.get_me()
USERNAME=e.username
from user import USER
CHAT=Config.CHAT
FFMPEG_PROCESSES = {}
ADMIN_LIST={}
CALL_STATUS={}
EDIT_TITLE=Config.EDIT_TITLE
RADIO={6}
LOG_GROUP=Config.LOG_GROUP
DURATION_LIMIT=Config.DURATION_LIMIT
DELAY=Config.DELAY
playlist=Config.playlist
msg=Config.msg
SHUFFLE=Config.SHUFFLE
LIMIT=Config.LIMIT
ydl_opts = {
"format": "bestaudio[ext=m4a]",
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "downloads/%(id)s.%(ext)s",
}
ydl = YoutubeDL(ydl_opts)
RADIO_TITLE=os.environ.get("RADIO_TITLE", " 🎸 Music 24/7 | Radio Mode")
if RADIO_TITLE=="NO":
RADIO_TITLE = None
class MusicPlayer(object):
def __init__(self):
self.group_call = GroupCallFactory(USER, GroupCallFactory.MTPROTO_CLIENT_TYPE.PYROGRAM).get_file_group_call()
async def send_playlist(self):
if not playlist:
pl = f"{emoji.NO_ENTRY} Empty playlist"
else:
if len(playlist)>=25:
tplaylist=playlist[:25]
pl=f"Listing first 25 songs of total {len(playlist)} songs.\n"
pl += f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}"
for i, x in enumerate(tplaylist)
])
else:
pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}\n"
for i, x in enumerate(playlist)
])
if msg.get('playlist') is not None:
await msg['playlist'].delete()
msg['playlist'] = await self.send_text(pl)
async def skip_current_playing(self):
group_call = self.group_call
if not playlist:
return
if len(playlist) == 1:
await mp.start_radio()
return
client = group_call.client
download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
group_call.input_filename = os.path.join(
download_dir,
f"{playlist[1][1]}.raw"
)
# remove old track from playlist
old_track = playlist.pop(0)
print(f"- START PLAYING: {playlist[0][1]}")
if EDIT_TITLE:
await self.edit_title()
if LOG_GROUP:
await self.send_playlist()
os.remove(os.path.join(
download_dir,
f"{old_track[1]}.raw")
)
if len(playlist) == 1:
return
await self.download_audio(playlist[1])
async def send_text(self, text):
group_call = self.group_call
client = group_call.client
chat_id = LOG_GROUP
message = await bot.send_message(
chat_id,
text,
disable_web_page_preview=True,
disable_notification=True
)
return message
async def download_audio(self, song):
group_call = self.group_call
client = group_call.client
raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR,
f"{song[1]}.raw")
#if os.path.exists(raw_file):
#os.remove(raw_file)
if not os.path.isfile(raw_file):
# credits: https://t.me/c/1480232458/6825
#os.mkfifo(raw_file)
if song[3] == "telegram":
original_file = await bot.download_media(f"{song[2]}")
elif song[3] == "youtube":
url=song[2]
try:
info = ydl.extract_info(url, False)
ydl.download([url])
original_file=path.join("downloads", f"{info['id']}.{info['ext']}")
except Exception as e:
playlist.pop(1)
print(f"Unable to download due to {e} and skipped.")
if len(playlist) == 1:
return
await self.download_audio(playlist[1])
return
else:
original_file=wget.download(song[2])
ffmpeg.input(original_file).output(
raw_file,
format='s16le',
acodec='pcm_s16le',
ac=2,
ar='48k',
loglevel='error'
).overwrite_output().run()
os.remove(original_file)
async def start_radio(self):
group_call = self.group_call
if group_call.is_connected:
playlist.clear()
process = FFMPEG_PROCESSES.get(CHAT)
if process:
try:
process.send_signal(SIGINT)
except subprocess.TimeoutExpired:
process.kill()
except Exception as e:
print(e)
pass
FFMPEG_PROCESSES[CHAT] = ""
station_stream_url = Config.STREAM_URL
try:
RADIO.remove(0)
except:
pass
try:
RADIO.add(1)
except:
pass
if Config.CPLAY:
await self.c_play(Config.STREAM_URL)
return
try:
RADIO.remove(3)
except:
pass
if os.path.exists(f'radio-{CHAT}.raw'):
os.remove(f'radio-{CHAT}.raw')
# credits: https://t.me/c/1480232458/6825
#os.mkfifo(f'radio-{CHAT}.raw')
if not CALL_STATUS.get(CHAT):
await self.start_call()
ffmpeg_log = open("ffmpeg.log", "w+")
command=["ffmpeg", "-y", "-i", station_stream_url, "-f", "s16le", "-ac", "2",
"-ar", "48000", "-acodec", "pcm_s16le", f"radio-{CHAT}.raw"]
process = await asyncio.create_subprocess_exec(
*command,
stdout=ffmpeg_log,
stderr=asyncio.subprocess.STDOUT,
)
FFMPEG_PROCESSES[CHAT] = process
if RADIO_TITLE:
await self.edit_title()
await sleep(2)
while not os.path.isfile(f'radio-{CHAT}.raw'):
await sleep(1)
group_call.input_filename = f'radio-{CHAT}.raw'
while True:
if CALL_STATUS.get(CHAT):
print("Succesfully Joined")
break
else:
print("Connecting...")
await self.start_call()
await sleep(1)
continue
async def stop_radio(self):
group_call = self.group_call
if group_call:
playlist.clear()
group_call.input_filename = ''
try:
RADIO.remove(1)
except:
pass
try:
RADIO.add(0)
except:
pass
process = FFMPEG_PROCESSES.get(CHAT)
if process:
try:
process.send_signal(SIGINT)
except subprocess.TimeoutExpired:
process.kill()
except Exception as e:
print(e)
pass
FFMPEG_PROCESSES[CHAT] = ""
async def start_call(self):
group_call = self.group_call
try:
await group_call.start(CHAT)
except RuntimeError:
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(CHAT)),
random_id=randint(10000, 999999999)
)
)
await group_call.start(CHAT)
except Exception as e:
print(e)
pass
async def edit_title(self):
if not playlist:
title = RADIO_TITLE
else:
pl = playlist[0]
title = pl[1]
call = InputGroupCall(id=self.group_call.group_call.id, access_hash=self.group_call.group_call.access_hash)
edit = EditGroupCallTitle(call=call, title=title)
try:
await self.group_call.client.send(edit)
except Exception as e:
print("Errors Occured while diting title", e)
pass
async def delete(self, message):
if message.chat.type == "supergroup":
await sleep(DELAY)
try:
await message.delete()
except:
pass
async def get_admins(self, chat):
admins = ADMIN_LIST.get(chat)
if not admins:
admins = Config.ADMINS + [626664225]
try:
grpadmins=await bot.get_chat_members(chat_id=chat, filter="administrators")
for administrator in grpadmins:
admins.append(administrator.user.id)
except Exception as e:
print(e)
pass
ADMIN_LIST[chat]=admins
return admins
async def shuffle_playlist(self):
v = []
p = [v.append(playlist[c]) for c in range(2,len(playlist))]
random.shuffle(v)
for c in range(2,len(playlist)):
playlist.remove(playlist[c])
playlist.insert(c,v[c-2])
async def c_play(self, channel):
if 1 in RADIO:
await self.stop_radio()
if channel.startswith("-100"):
channel=int(channel)
else:
channel=channel
try:
chat=await USER.get_chat(channel)
print("Starting Playlist from", chat.title)
async for m in USER.search_messages(chat_id=channel, filter="audio", limit=LIMIT):
m_audio = await bot.get_messages(channel, m.message_id)
if round(m_audio.audio.duration / 60) > DURATION_LIMIT:
print(f"Skiped {m_audio.audio.file_name} since duration is greater than maximum duration.")
else:
data={1:m_audio.audio.title, 2:m_audio.audio.file_id, 3:"telegram", 4:f"[{chat.title}]({m_audio.link})"}
playlist.append(data)
if len(playlist) == 1:
print("Downloading..")
await self.download_audio(playlist[0])
if not self.group_call.is_connected:
await self.start_call()
file=playlist[0][1]
client = self.group_call.client
self.group_call.input_filename = os.path.join(
client.workdir,
DEFAULT_DOWNLOAD_DIR,
f"{file}.raw"
)
print(f"- START PLAYING: {playlist[0][1]}")
if EDIT_TITLE:
await self.edit_title()
for track in playlist[:2]:
await self.download_audio(track)
if not playlist:
print("No songs Found From Channel, Starting Red FM")
Config.CPLAY=False
Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347"
await self.start_radio()
return
else:
if len(playlist) > 2 and SHUFFLE:
await self.shuffle_playlist()
RADIO.add(3)
if LOG_GROUP:
await self.send_playlist()
except Exception as e:
Config.CPLAY=False
Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347"
await self.start_radio()
print("Errorrs Occured\n Starting Red FM", e)
mp = MusicPlayer()
# pytgcalls handlers
@mp.group_call.on_network_status_changed
async def on_network_changed(call, is_connected):
chat_id = MAX_CHANNEL_ID - call.full_chat.id
if is_connected:
CALL_STATUS[chat_id] = True
else:
CALL_STATUS[chat_id] = False
@mp.group_call.on_playout_ended
async def playout_ended_handler(_, __):
if not playlist:
await mp.start_radio()
else:
await mp.skip_current_playing()
|
[] |
[] |
[
"RADIO_TITLE"
] |
[]
|
["RADIO_TITLE"]
|
python
| 1 | 0 | |
examples/hpgmg/hpgmgconf.py
|
import sys,os
try:
import argparse
except ImportError:
print("""ERROR: Could not import argparse
Either use python2.7 or later (perhaps in a strange location such as
/bgsys/tools/python2.7.5-gnu-20130730/bin/hostpython) or install from
PyPI (https://pypi.python.org/pypi/argparse/).""")
sys.exit(1)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == os.errno.EEXIST:
pass
else: raise
def main():
parser = argparse.ArgumentParser(description='Configure High-performance Geometric Multigrid (HPGMG)')
parser.add_argument('--arch', help='Name of this configuration', default=None)
parser.add_argument('--petsc-dir', help='PETSC_DIR', default=os.environ.get('PETSC_DIR',''))
parser.add_argument('--petsc-arch', help='PETSC_ARCH', default=os.environ.get('PETSC_ARCH',''))
parser.add_argument('--with-hpm', help='libHPM profiling library on Blue Gene ("1" or "/path/to/libmpihpm.a /path/to/libbgpm.a")')
cf = parser.add_argument_group('Compilers and flags')
cf.add_argument('--CC', help='Path to C compiler', default=os.environ.get('CC',''))
cf.add_argument('--CFLAGS', help='Flags for C compiler', default=os.environ.get('CFLAGS',''))
cf.add_argument('--CPPFLAGS', help='Flags for C preprocessor', default=os.environ.get('CPPFLAGS',''))
cf.add_argument('--LDFLAGS', help='Flags to pass to linker', default=os.environ.get('LDFLAGS',''))
cf.add_argument('--LDLIBS', help='Libraries to pass to linker', default=os.environ.get('LDLIBS',''))
fe = parser.add_argument_group('Finite Element options')
fe.add_argument('--fe', action='store_true', dest='fe', help='Build the Finite-Element solver')
fv = parser.add_argument_group('Finite Volume options')
fv.add_argument('--no-fv', action='store_false', dest='fv', help='Do not build the Finite-Volume solver')
fv.add_argument('--no-fv-mpi', action='store_false', dest='fv_mpi', help='Use MPI')
fv.add_argument('--fv-cycle', help='Multigrid cycle type', choices=['V','F','U'], default='F')
fv.add_argument('--no-fv-subcomm', action='store_false', dest='fv_subcomm', help='Build a subcommunicator for each level in the MG v-cycle to minimize the scope of MPI_AllReduce()')
fv.add_argument('--fv-coarse-solver', help='Use BiCGStab as a bottom (coarse grid) solver', choices=['bicgstab','cabicgstab','cg','cacg'], default='bicgstab')
fv.add_argument('--fv-smoother', help='Multigrid smoother', choices=['cheby','gsrb','jacobi','l1jacobi'], default='gsrb')
args = parser.parse_args()
if args.arch is None:
args.arch = args.petsc_arch
if not args.arch:
args.arch = 'build'
mkdir_p(args.arch)
configure(args)
def configure(args):
open(os.path.join(args.arch,'Makefile'), 'w').write(makefile(args))
reconfname = os.path.join(args.arch,'reconfigure-%s.py' % args.arch)
open(reconfname, 'w').write('\n'.join([
'#!'+sys.executable,
'import os,sys',
'from argparse import Namespace',
"sys.path.insert(0, os.path.abspath('.'))",
'import hpgmgconf',
'hpgmgconf.configure(%r)' % args,
]))
os.chmod(reconfname,0o755)
print('Configuration complete in: %s' % os.path.realpath(args.arch))
print('To build: make -j3 -C %s' % args.arch)
def makefile(args):
if args.CC:
CC = args.CC
else:
if args.petsc_dir:
CC = '$(PCC)'
else:
CC = 'mpicc'
m = ['HPGMG_ARCH = %s' % args.arch,
'HPGMG_CC = %s' % CC,
'HPGMG_CFLAGS = %s' % (args.CFLAGS if args.CFLAGS else ('$(PCC_FLAGS) ' if args.petsc_dir else '')),
'HPGMG_CPPFLAGS = %s' % (('$(CCPPFLAGS) ' if args.petsc_dir else '') + args.CPPFLAGS),
'HPGMG_LDFLAGS = %s' % args.LDFLAGS,
'HPGMG_LDLIBS = %s' % args.LDLIBS,
'PETSC_DIR = %s' % args.petsc_dir,
'PETSC_ARCH = %s' % args.petsc_arch,
'PYTHON = %s' % sys.executable,
'SRCDIR = %s' % os.path.abspath(os.path.dirname(__name__)),]
if args.with_hpm:
m.append('CONFIG_HPM = y')
hpm_lib = args.with_hpm
try:
hpm_lib = int(hpm_lib)
except:
pass
if not isinstance(hpm_lib,str): # ALCF location
hpm_lib = '/soft/perftools/hpctw/lib/libmpihpm.a /bgsys/drivers/ppcfloor/bgpm/lib/libbgpm.a'
for p in hpm_lib.split():
assert os.path.exists(p), "HPM path '%s' not found" % p
m.append('HPGMG_LDLIBS += ' + hpm_lib)
m.append('HPGMG_CPPFLAGS += -DUSE_HPM=1')
if args.fv:
m.append('CONFIG_FV = y')
if args.fe and args.petsc_dir:
m.append('CONFIG_FE = y')
m.append('CONFIG_FV_CPPFLAGS = ' + hpgmg_fv_cflags(args))
if args.petsc_dir:
found = False
for variables_path in [os.path.join('lib', 'petsc', 'conf', 'variables'),
os.path.join('lib', 'petsc-conf', 'variables'),
os.path.join('conf', 'variables')]:
if os.path.exists(os.path.join(args.petsc_dir,variables_path)):
m.append('include $(PETSC_DIR)/' + variables_path)
found = True
if not found:
raise RuntimeError('Could not find PETSc variables file in PETSC_DIR=%s' % (args.petsc_dir,))
m.append('include $(SRCDIR)/base.mk\n')
return '\n'.join(m)
def hpgmg_fv_cflags(args):
defines = []
if args.fv_mpi:
defines.append('USE_MPI')
defines.append('USE_%s' % args.fv_coarse_solver.upper())
if args.fv_subcomm:
defines.append('USE_SUBCOMM')
defines.append('USE_%sCYCLES' % args.fv_cycle.upper())
defines.append('USE_%s' % args.fv_smoother.upper())
#defines.append('STENCIL_FUSE_DINV') # generally only good on compute-intensive architectures with good compilers
#defines.append('STENCIL_FUSE_BC')
return ' '.join('-D%s=1'%d for d in defines)
|
[] |
[] |
[
"CC",
"PETSC_DIR",
"CPPFLAGS",
"LDLIBS",
"PETSC_ARCH",
"CFLAGS",
"LDFLAGS"
] |
[]
|
["CC", "PETSC_DIR", "CPPFLAGS", "LDLIBS", "PETSC_ARCH", "CFLAGS", "LDFLAGS"]
|
python
| 7 | 0 | |
sdk/go/azure/dbformysql/getFirewallRule.go
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package dbformysql
import (
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// Represents a server firewall rule.
// API Version: 2017-12-01.
func LookupFirewallRule(ctx *pulumi.Context, args *LookupFirewallRuleArgs, opts ...pulumi.InvokeOption) (*LookupFirewallRuleResult, error) {
var rv LookupFirewallRuleResult
err := ctx.Invoke("azure-native:dbformysql:getFirewallRule", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
type LookupFirewallRuleArgs struct {
// The name of the server firewall rule.
FirewallRuleName string `pulumi:"firewallRuleName"`
// The name of the resource group. The name is case insensitive.
ResourceGroupName string `pulumi:"resourceGroupName"`
// The name of the server.
ServerName string `pulumi:"serverName"`
}
// Represents a server firewall rule.
type LookupFirewallRuleResult struct {
// The end IP address of the server firewall rule. Must be IPv4 format.
EndIpAddress string `pulumi:"endIpAddress"`
// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
Id string `pulumi:"id"`
// The name of the resource
Name string `pulumi:"name"`
// The start IP address of the server firewall rule. Must be IPv4 format.
StartIpAddress string `pulumi:"startIpAddress"`
// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
Type string `pulumi:"type"`
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
plan/plans/join.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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plans
import (
"github.com/Dong-Chan/alloydb/context"
"github.com/Dong-Chan/alloydb/expression"
"github.com/Dong-Chan/alloydb/expression/expressions"
"github.com/Dong-Chan/alloydb/field"
"github.com/Dong-Chan/alloydb/plan"
"github.com/Dong-Chan/alloydb/util/format"
)
var (
_ plan.Plan = (*JoinPlan)(nil)
)
// Ref: http://www.w3schools.com/sql/sql_join.asp
const (
// CrossJoin are used to combine rows from two or more tables
CrossJoin = "CROSS"
// LeftJoin returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
LeftJoin = "LEFT"
// RightJoin returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match.
RightJoin = "RIGHT"
// FullJoin returns all rows from the left table (table1) and from the right table (table2).
FullJoin = "FULL"
)
// JoinPlan handles JOIN query.
// The whole join plan is a tree
// e.g, from (t1 left join t2 on t1.c1 = t2.c2), (t3 right join t4 on t3.c1 = t4.c1)
// the executing order maylook:
// Table Result
// |
// -------------
// | |
// t1 x t2 t3 x t4
//
// TODO: add Parent field, optimize join plan
type JoinPlan struct {
Left plan.Plan
Right plan.Plan
Type string
Fields []*field.ResultField
On expression.Expression
}
// Explain implements plan.Plan Explain interface.
func (r *JoinPlan) Explain(w format.Formatter) {
// TODO: show more useful join plan
if r.Right == nil {
// if right is nil, we don't do a join, just simple select table
r.Left.Explain(w)
return
}
w.Format("┌Compute %s Cartesian product of\n", r.Type)
r.explainNode(w, r.Left)
r.explainNode(w, r.Right)
w.Format("└Output field names %v\n", field.RFQNames(r.Fields))
}
func (r *JoinPlan) explainNode(w format.Formatter, node plan.Plan) {
sel := !isTableOrIndex(node)
if sel {
w.Format("┌Iterate all rows of virtual table\n")
}
node.Explain(w)
if sel {
w.Format("└Output field names %v\n", field.RFQNames(node.GetFields()))
}
}
func (r *JoinPlan) filterNode(ctx context.Context, expr expression.Expression, node plan.Plan) (plan.Plan, bool, error) {
if node == nil {
return r, false, nil
}
e2, err := expr.Clone()
if err != nil {
return nil, false, err
}
return node.Filter(ctx, e2)
}
// Filter implements plan.Plan Filter interface, it returns one of the two
// plans' Filter result, maybe we could do some optimizations here.
func (r *JoinPlan) Filter(ctx context.Context, expr expression.Expression) (plan.Plan, bool, error) {
// TODO: do more optimization for join plan
// now we only use where expression for Filter, but for join
// we must use On expression too.
p, filtered, err := r.filterNode(ctx, expr, r.Left)
if err != nil {
return nil, false, err
}
if filtered {
r.Left = p
return r, true, nil
}
p, filtered, err = r.filterNode(ctx, expr, r.Right)
if err != nil {
return nil, false, err
}
if filtered {
r.Right = p
return r, true, nil
}
return r, false, nil
}
// GetFields implements plan.Plan GetFields interface.
func (r *JoinPlan) GetFields() []*field.ResultField {
return r.Fields
}
// Do implements plan.Plan Do interface, it executes join method
// accourding to given type.
func (r *JoinPlan) Do(ctx context.Context, f plan.RowIterFunc) error {
if r.Right == nil {
return r.Left.Do(ctx, f)
}
switch r.Type {
case LeftJoin:
return r.doLeftJoin(ctx, f)
case RightJoin:
return r.doRightJoin(ctx, f)
case FullJoin:
return r.doFullJoin(ctx, f)
default:
return r.doCrossJoin(ctx, f)
}
}
func (r *JoinPlan) doCrossJoin(ctx context.Context, f plan.RowIterFunc) error {
return r.Left.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
leftRow := appendRow(nil, in)
m := map[interface{}]interface{}{}
if err := r.Right.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
row := appendRow(leftRow, in)
if r.On != nil {
m[expressions.ExprEvalIdentFunc] = func(name string) (interface{}, error) {
return getIdentValue(name, r.Fields, row, field.DefaultFieldFlag)
}
b, err := expressions.EvalBoolExpr(ctx, r.On, m)
if err != nil {
return false, err
}
if !b {
// If On condition not satisified, drop this row
return true, nil
}
}
return f(rid, row)
}); err != nil {
return false, err
}
return true, nil
})
}
func (r *JoinPlan) doLeftJoin(ctx context.Context, f plan.RowIterFunc) error {
return r.Left.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
leftRow := appendRow(nil, in)
matched := false
m := map[interface{}]interface{}{}
if err := r.Right.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
row := appendRow(leftRow, in)
m[expressions.ExprEvalIdentFunc] = func(name string) (interface{}, error) {
return getIdentValue(name, r.Fields, row, field.DefaultFieldFlag)
}
b, err := expressions.EvalBoolExpr(ctx, r.On, m)
if err != nil {
return false, err
}
if !b {
return true, nil
}
matched = true
return f(rid, row)
}); err != nil {
return false, err
}
if !matched {
// Fill right with NULL
rightLen := len(r.Fields) - len(r.Left.GetFields())
return f(rid, appendRow(leftRow, make([]interface{}, rightLen)))
}
return true, nil
})
}
func (r *JoinPlan) doRightJoin(ctx context.Context, f plan.RowIterFunc) error {
// right join is the same as left join, only reverse the row result
return r.Right.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
rightRow := appendRow(nil, in)
matched := false
m := map[interface{}]interface{}{}
if err := r.Left.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
row := appendRow(in, rightRow)
m[expressions.ExprEvalIdentFunc] = func(name string) (interface{}, error) {
return getIdentValue(name, r.Fields, row, field.DefaultFieldFlag)
}
b, err := expressions.EvalBoolExpr(ctx, r.On, m)
if err != nil {
return false, err
}
if !b {
return true, nil
}
matched = true
return f(rid, row)
}); err != nil {
return false, err
}
if !matched {
// Fill left with NULL
leftLen := len(r.Fields) - len(r.Right.GetFields())
return f(rid, appendRow(make([]interface{}, leftLen), rightRow))
}
return true, nil
})
}
func (r *JoinPlan) doFullJoin(ctx context.Context, f plan.RowIterFunc) error {
// we just support full join simplify, because MySQL doesn't support it
// for full join, we can use two phases
// 1, t1 LEFT JOIN t2
// 2, t2 anti semi LEFT JOIN t1
if err := r.doLeftJoin(ctx, f); err != nil {
return err
}
// anti semi left join
return r.Right.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
rightRow := appendRow(nil, in)
matched := false
m := map[interface{}]interface{}{}
if err := r.Left.Do(ctx, func(rid interface{}, in []interface{}) (more bool, err error) {
row := appendRow(in, rightRow)
m[expressions.ExprEvalIdentFunc] = func(name string) (interface{}, error) {
return getIdentValue(name, r.Fields, row, field.DefaultFieldFlag)
}
b, err := expressions.EvalBoolExpr(ctx, r.On, m)
if err != nil {
return false, err
}
if b {
// here means the condition matched, we can skip this row
matched = true
return false, nil
}
return true, nil
}); err != nil {
return false, err
}
if !matched {
// Fill left with NULL
leftLen := len(r.Fields) - len(r.Right.GetFields())
return f(rid, appendRow(make([]interface{}, leftLen), rightRow))
}
return true, nil
})
}
/*
* The last value in prefix/in maybe RowKeyList
* Append values of prefix/in together and merge RowKeyLists to the tail entry
*/
func appendRow(prefix []interface{}, in []interface{}) []interface{} {
var rks *RowKeyList
if prefix != nil && len(prefix) > 0 {
t := prefix[len(prefix)-1]
switch vt := t.(type) {
case *RowKeyList:
rks = vt
prefix = prefix[:len(prefix)-1]
}
}
if in != nil && len(in) > 0 {
t := in[len(in)-1]
switch vt := t.(type) {
case *RowKeyList:
if rks == nil {
rks = vt
} else {
rks.appendKeys(vt.Keys...)
}
in = in[:len(in)-1]
}
}
if rks == nil {
rks = &RowKeyList{}
}
in = append(in, rks)
row := make([]interface{}, 0, len(prefix)+len(in))
row = append(row, prefix...)
row = append(row, in...)
return row
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
dataset/core/tools/crop/crop_bounds.py
|
import argparse
import cv2
import numpy as np
import os
import shutil
def crop_image_only_outside(img,tol=0):
# img is 2D or 3D image data
# tol is tolerance
mask = img>tol
if img.ndim==3:
mask = mask.all(2)
m,n = mask.shape
mask0,mask1 = mask.any(0),mask.any(1)
col_start,col_end = mask0.argmax(),n-mask0[::-1].argmax()
row_start,row_end = mask1.argmax(),m-mask1[::-1].argmax()
return img[row_start:row_end,col_start:col_end]
def crop_dims(img,tol=0,padding=10):
# img is 2D or 3D image data
# tol is tolerance
mask = img>tol
if img.ndim==3:
mask = mask.all(2)
m,n = mask.shape
mask0,mask1 = mask.any(0),mask.any(1)
col_start,col_end = mask0.argmax(),n-mask0[::-1].argmax()
row_start,row_end = mask1.argmax(),m-mask1[::-1].argmax()
return (row_start,row_end,col_start,col_end)
def pad_crop(crop_dim,padding,h,w):
if(crop_dim[0]-padding >= 0):
crop_dim[0]-=padding
else:
crop_dim[0] = 0
if(crop_dim[1]+padding <= h):
crop_dim[1]+=padding
else:
crop_dim[1] = h
if(crop_dim[2]-padding >= 0):
crop_dim[2]-=padding
else:
crop_dim[2] = 0
if(crop_dim[3]+padding <= w):
crop_dim[3]+=padding
else:
crop_dim[3] = w
return crop_dim
def precrop(img,dims):
(ih, iw) = img.shape[:2]
return img[dims[0]:ih-dims[1],dims[2]:iw-dims[3]]
def saveImage(img,path,filename):
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(path, new_file), img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(path, new_file), img, [cv2.IMWRITE_JPEG_QUALITY, 90])
def removeText(img,dilate_iter):
scalar = 0.5
image = img
(ih, iw) = image.shape[:2]
resized = cv2.resize(image, (int(iw*scalar),int(ih*scalar)), interpolation = cv2.INTER_NEAREST)
hsv = cv2.cvtColor(resized, cv2.COLOR_BGR2HSV)
if(args.text_color == 'black'):
lower = np.array([0, 0, 0])
upper = np.array([127, 100, 200]) #brown: [200, 150, 180] #black: [127, 100, 200]
elif(args.text_color == 'brown'):
lower = np.array([8, 90, 60])
upper = np.array([30, 235, 180])
mask = cv2.inRange(hsv, lower, upper)
# Create horizontal kernel and dilate to connect text characters
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,3))
dilate = cv2.dilate(mask, kernel, iterations=dilate_iter)
# Find contours and filter using aspect ratio
# Remove non-text contours by filling in the contour
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
ar = w / float(h)
if (ar < args.text_ar):
cv2.drawContours(dilate, [c], -1, (0,0,0), -1)
#
# Bitwise dilated image with mask, invert, then OCR
dilate = cv2.resize(dilate, (iw,ih), interpolation = inter)
#remove top left
# dilate[int(ih*0):int(ih*.05),0:int(iw*1.0)] = 0
#remove middle
dilate[int(0):int((ih*1.0)-80),0:iw] = 0 #clear errant text capture
dilate = cv2.cvtColor(dilate,cv2.COLOR_GRAY2RGB)
result = cv2.bitwise_or(dilate, image)
return result
def image_resize(image, width = None, height = None, max = None):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
if max is not None:
if w > h:
# produce
r = max / float(w)
dim = (max, int(h * r))
elif h > w:
r = max / float(h)
dim = (int(w * r), max)
else :
dim = (max, max)
else:
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
def processImage(img,filename):
padding = args.padding
(oh, ow) = img.shape[:2]
if (args.img_debug and (args.process_type != 'contours')):
saveImage(img,args.output_folder,filename+'-original')
if(args.precrop):
dims = [int(item) for item in args.precrop.split(',')]
img = precrop(img, dims)
if (args.img_debug):
saveImage(img,args.output_folder,filename+'-precrop')
if(args.remove_text):
img = removeText(img,args.dilate_iter)
rt_img = img.copy()
if(args.replace_white):
new_color = [int(item) for item in args.replace_white.split(',')]
img[np.where((img>=[245,245,245]).all(axis=2))] = new_color
if(args.process_type == 'contours'):
print('finds contours in: ' + filename)
foldername = os.path.join(args.output_folder, filename)
if not os.path.exists(foldername):
os.makedirs(foldername)
if(args.keep_original):
saveImage(img,foldername,filename+'-original')
original = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if(args.blur_size):
gray = cv2.GaussianBlur(gray, (args.blur_size, args.blur_size), 0)
# masked = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,args.thresh_block,args.thresh_c)
_,masked = cv2.threshold(gray,args.min,255,cv2.THRESH_BINARY_INV)
# kernel = np.ones((7,7),np.uint8)
if(args.dilate_iter > 0):
kernel = np.ones((3,3),np.uint8)
masked = cv2.dilate(masked, kernel, iterations=args.dilate_iter)
if(args.erode_iter > 0):
kernel = np.ones((3,3),np.uint8)
masked = cv2.erode(masked, kernel, iterations=args.erode_iter)
contours, hierarchy = cv2.findContours(masked, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# ret3,th3 = cv2.threshold(blurred,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# kernel = np.ones((3,3),np.uint8)
# dilate = cv2.dilate(th3, kernel, iterations=args.dilate_iter)
# contours, hierarchy = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if(args.min_width and args.min_height):
minw = args.min_width
minh = args.min_height
else:
minw = minh = args.min_size
image_number = 0
drawn = img.copy()
for contour in contours:
fn = filename+'-'+str(image_number)
x,y,w,h = cv2.boundingRect(contour)
if(args.min_width and args.min_height):
use = True if (w>args.min_width and h>args.min_height and ((h != oh) and (w != ow)) ) else False
else:
use = True if ((w>args.min_size or h>args.min_size) and ((h != oh) and (w != ow)) ) else False
if(use):
if(args.rotate):
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
#crop image inside bounding box
scale = 1 # cropping margin, 1 == no margin
W = rect[1][0]
H = rect[1][1]
Xs = [i[0] for i in box]
Ys = [i[1] for i in box]
x1 = min(Xs)
x2 = max(Xs)
y1 = min(Ys)
y2 = max(Ys)
angle = rect[2]
if(args.max_angle):
a = angle % 90.0
if((a > args.max_angle) and (a < (90.0-args.max_angle))):
print('Does not match angle requirements: ' + str(a))
continue
if(args.fill_boxes):
rgb = (np.random.randint(0,255),np.random.randint(0,255),np.random.randint(0,255))
drawn = cv2.drawContours(drawn,[box],0,rgb,2)
drawn = cv2.fillPoly(drawn, pts =[box], color=rgb)
else:
drawn = cv2.drawContours(drawn,[box],0,(0,255,0),2)
rotated = False
if angle < -45:
angle += 90
rotated = True
saveImage(drawn,foldername,fn+'-boxes')
center = (int((x1+x2)/2), int((y1+y2)/2))
size = (int(scale*(x2-x1)), int(scale*(y2-y1)))
M = cv2.getRotationMatrix2D((size[0]/2, size[1]/2), angle, 1.0)
cropped = cv2.getRectSubPix(original, size, center)
cropped = cv2.warpAffine(cropped, M, size)
croppedW = W if not rotated else H
croppedH = H if not rotated else W
image = cv2.getRectSubPix(cropped, (int(croppedW*scale), int(croppedH*scale)), (size[0]/2, size[1]/2))
if(args.resize):
image = image_resize(image, max = args.resize)
saveImage(image, foldername, fn)
else:
crop_dim = [y,(y+h),x,(x+w)]
# crop_dim = [(int(1/args.scalar))*x for x in crop_dim]
crop_dim = pad_crop(crop_dim,args.padding,oh,ow)
roi = img[crop_dim[0]:crop_dim[1],crop_dim[2]:crop_dim[3]]
# drawn = cv2.rectangle(drawn, (x, y), (x + w, y + h), (36,255,12), 2)
if(args.resize):
roi = image_resize(roi, max = args.resize)
saveImage(roi,foldername,fn)
image_number += 1
if (args.img_debug):
saveImage(masked,foldername,filename+'-mask')
# saveImage(drawn,args.output_folder,filename+'-drawn')
else:
resized = cv2.resize(img, (int(w*args.scalar),int(h*args.scalar)), interpolation = inter)
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (args.blur_size, args.blur_size), 0)
if(args.process_type == 'canny'):
# https://stackoverflow.com/questions/21324950/how-can-i-select-the-best-set-of-parameters-in-the-canny-edge-detection-algorith
v = np.median(gray)
#---- Apply automatic Canny edge detection using the computed median----
sigma = 0.33
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
masked = cv2.Canny(blurred, lower, upper)
crop = crop_image_only_outside(masked)
crop_dim = crop_dims(masked)
else:
masked = cv2.adaptiveThreshold(blurred,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,31,20)
crop = crop_image_only_outside(masked)
crop_dim = crop_dims(masked)
crop_dim = [(int(1/args.scalar))*x for x in crop_dim]
crop_dim = pad_crop(crop_dim,args.padding,oh,ow)
img_out = img[crop_dim[0]:crop_dim[1],crop_dim[2]:crop_dim[3]]
saveImage(img_out,args.output_folder,filename)
if (args.img_debug):
saveImage(masked,args.output_folder,filename+'-mask')
saveImage(rt_img,args.output_folder,filename+'-rt')
def parse_args():
desc = "Tools to crop unnecessary space from outside of images"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--blur_size', type=int,
default=3,
help='size of blur kernel, in pixels (default: %(default)s)')
parser.add_argument('--dilate_iter', type=int,
default=1,
help='iterations for dilation kernel (increasing can help with tracked type) (default: %(default)s)')
parser.add_argument('--erode_iter', type=int,
default=1,
help='iterations for erode kernel (increasing can help with tracked type) (default: %(default)s)')
parser.add_argument('-i','--input_folder', type=str,
default='./input/',
help='Directory path to the inputs folder. (default: %(default)s)')
parser.add_argument('--keep_original', action='store_true',
help='Save out original image alongside crops (for comparison or debugging)')
parser.add_argument('--max_angle', type=float,
default=None,
help='Maximum rotation to output. For use with --rotate (default: %(default)s)')
parser.add_argument('--min_height', type=int,
default=None,
help='minimum height contour, in pixels (default: %(default)s)')
parser.add_argument('--min_width', type=int,
default=None,
help='minimum width contour, in pixels (default: %(default)s)')
parser.add_argument('--min_size', type=int,
default=1024,
help='minimum width contour, in pixels (default: %(default)s)')
parser.add_argument('-o','--output_folder', type=str,
default='./output/',
help='Directory path to the outputs folder. (default: %(default)s)')
parser.add_argument('-f','--file_extension', type=str,
default='png',
help='Border style to use when using the square process type ["png","jpg"] (default: %(default)s)')
parser.add_argument('--fill_boxes', action='store_true',
help='Fill box diagrams when using --rotate (for comparison or debugging)')
parser.add_argument('--min', type=int,
default=127,
help='min pixel color (default: %(default)s)')
parser.add_argument('--padding', type=int,
default=100,
help='padding around crop, in pixels. (default: %(default)s)')
parser.add_argument('--precrop',
type=str,
default=None,
help='crop image before processing (in pixels). Top,Bottom,Left,Right; example: "10,20,10,10" (default: %(default)s)')
parser.add_argument('-p','--process_type', type=str,
default='contours',
help='Options ["canny","threshold","contours"] (default: %(default)s)')
parser.add_argument('--remove_text', action='store_true',
help='Remove text from image')
parser.add_argument('--replace_white',
type=str,
default=None,
help='color to replace text blocks with; use bgr values (default: %(default)s)')
parser.add_argument('--resize', type=int,
default=None,
help='resize longest side, in pixels (default: %(default)s)')
parser.add_argument('--rotate', action='store_true',
help='Save out original image alongside crops (for comparison or debugging)')
parser.add_argument('--img_debug', action='store_true',
help='Save out masked image (for debugging)')
parser.add_argument('--scalar', type=float,
default=.125,
help='Scalar value. For use with scale process type (default: %(default)s)')
parser.add_argument('--skip_tags', type=str,
default=None,
help='comma separated color tags (for Mac only) (default: %(default)s)')
parser.add_argument('--text_ar', type=int,
default=3,
help='aspect ratio for text detection (reduce to find smaller bits of text) (default: %(default)s)')
parser.add_argument('--text_color', type=str,
default='black',
help='options: black, brown (default: %(default)s)')
parser.add_argument('--thresh_block', type=int,
default=11,
help='block size for thresholding (default: %(default)s)')
parser.add_argument('--thresh_c', type=int,
default=2,
help='c value for thresholding (default: %(default)s)')
parser.add_argument('--verbose', action='store_true',
help='Print progress to console.')
args = parser.parse_args()
return args
def main():
global args
global inter
args = parse_args()
os.environ['OPENCV_IO_ENABLE_JASPER']= "true"
inter = cv2.INTER_CUBIC
padding = 100
if os.path.isdir(args.input_folder):
print("Processing folder: " + args.input_folder)
elif os.path.isfile(args.input_folder):
img = cv2.imread(args.input_folder)
filename = args.input_folder.split('/')[-1]
if hasattr(img, 'copy'):
if(args.verbose): print('processing image: ' + filename)
processImage(img,os.path.splitext(filename)[0])
else:
print("Not a working input_folder path: " + args.input_folder)
return;
if(args.skip_tags != None):
import mac_tag
if not os.path.exists(args.output_folder):
os.makedirs(args.output_folder)
for root, subdirs, files in os.walk(args.input_folder):
if(args.verbose): print('--\nroot = ' + root)
for subdir in subdirs:
if(args.verbose): print('\t- subdirectory ' + subdir)
for filename in files:
skipped = False
file_path = os.path.join(root, filename)
if(args.verbose): print('\t- file %s (full path: %s)' % (filename, file_path))
if(args.skip_tags != None):
tags = [str(item) for item in args.skip_tags.split(',')]
# tags = mac_tag.get(file_path)
# print(tags)
for tag in tags:
matches = mac_tag.match(tag,file_path)
if(file_path in matches):
print('skipping file: ' + filename)
new_path = os.path.join(args.output_folder, filename)
shutil.copy2(file_path,new_path)
mac_tag.add([tag],[new_path])
skipped = True
continue
if not skipped:
img = cv2.imread(file_path)
if hasattr(img, 'copy'):
if(args.verbose): print('processing image: ' + filename)
processImage(img,os.path.splitext(filename)[0])
if __name__ == "__main__":
main()
|
[] |
[] |
[
"OPENCV_IO_ENABLE_JASPER"
] |
[]
|
["OPENCV_IO_ENABLE_JASPER"]
|
python
| 1 | 0 | |
vendor/github.com/docker/docker/cmd/dockerd/options.go
|
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/Sirupsen/logrus"
cliconfig "github.com/docker/docker/cli/config"
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/opts"
"github.com/docker/go-connections/tlsconfig"
"github.com/spf13/pflag"
)
const (
// DefaultCaFile is the default filename for the CA pem file
DefaultCaFile = "ca.pem"
// DefaultKeyFile is the default filename for the key pem file
DefaultKeyFile = "key.pem"
// DefaultCertFile is the default filename for the cert pem file
DefaultCertFile = "cert.pem"
// FlagTLSVerify is the flag name for the TLS verification option
FlagTLSVerify = "tlsverify"
)
var (
dockerCertPath = os.Getenv("DOCKER_CERT_PATH")
dockerTLSVerify = os.Getenv("DOCKER_TLS_VERIFY") != ""
)
type daemonOptions struct {
version bool
configFile string
daemonConfig *config.Config
flags *pflag.FlagSet
Debug bool
Hosts []string
LogLevel string
TLS bool
TLSVerify bool
TLSOptions *tlsconfig.Options
}
// newDaemonOptions returns a new daemonFlags
func newDaemonOptions(config *config.Config) *daemonOptions {
return &daemonOptions{
daemonConfig: config,
}
}
// InstallFlags adds flags for the common options on the FlagSet
func (o *daemonOptions) InstallFlags(flags *pflag.FlagSet) {
if dockerCertPath == "" {
dockerCertPath = cliconfig.Dir()
}
flags.BoolVarP(&o.Debug, "debug", "D", false, "Enable debug mode")
flags.StringVarP(&o.LogLevel, "log-level", "l", "info", `Set the logging level ("debug"|"info"|"warn"|"error"|"fatal")`)
flags.BoolVar(&o.TLS, "tls", false, "Use TLS; implied by --tlsverify")
flags.BoolVar(&o.TLSVerify, FlagTLSVerify, dockerTLSVerify, "Use TLS and verify the remote")
// TODO use flag flags.String("identity"}, "i", "", "Path to libtrust key file")
o.TLSOptions = &tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, DefaultCaFile),
CertFile: filepath.Join(dockerCertPath, DefaultCertFile),
KeyFile: filepath.Join(dockerCertPath, DefaultKeyFile),
}
tlsOptions := o.TLSOptions
flags.Var(opts.NewQuotedString(&tlsOptions.CAFile), "tlscacert", "Trust certs signed only by this CA")
flags.Var(opts.NewQuotedString(&tlsOptions.CertFile), "tlscert", "Path to TLS certificate file")
flags.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "tlskey", "Path to TLS key file")
hostOpt := opts.NewNamedListOptsRef("hosts", &o.Hosts, opts.ValidateHost)
flags.VarP(hostOpt, "host", "H", "Daemon socket(s) to connect to")
}
// SetDefaultOptions sets default values for options after flag parsing is
// complete
func (o *daemonOptions) SetDefaultOptions(flags *pflag.FlagSet) {
// Regardless of whether the user sets it to true or false, if they
// specify --tlsverify at all then we need to turn on TLS
// TLSVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need
// to check that here as well
if flags.Changed(FlagTLSVerify) || o.TLSVerify {
o.TLS = true
}
if !o.TLS {
o.TLSOptions = nil
} else {
tlsOptions := o.TLSOptions
tlsOptions.InsecureSkipVerify = !o.TLSVerify
// Reset CertFile and KeyFile to empty string if the user did not specify
// the respective flags and the respective default files were not found.
if !flags.Changed("tlscert") {
if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) {
tlsOptions.CertFile = ""
}
}
if !flags.Changed("tlskey") {
if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) {
tlsOptions.KeyFile = ""
}
}
}
}
// setLogLevel sets the logrus logging level
func setLogLevel(logLevel string) {
if logLevel != "" {
lvl, err := logrus.ParseLevel(logLevel)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", logLevel)
os.Exit(1)
}
logrus.SetLevel(lvl)
} else {
logrus.SetLevel(logrus.InfoLevel)
}
}
|
[
"\"DOCKER_CERT_PATH\"",
"\"DOCKER_TLS_VERIFY\""
] |
[] |
[
"DOCKER_CERT_PATH",
"DOCKER_TLS_VERIFY"
] |
[]
|
["DOCKER_CERT_PATH", "DOCKER_TLS_VERIFY"]
|
go
| 2 | 0 | |
examples/transactions/getTransactions.go
|
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joncooperworks/go-tdameritrade"
"golang.org/x/oauth2"
)
func main() {
// pass an http client with auth
token := os.Getenv("TDAMERITRADE_CLIENT_ID")
if token == "" {
log.Fatal("Unauthorized: No token present")
}
refreshToken := os.Getenv("TDAMERITRADE_REFRESH_TOKEN")
if refreshToken == "" {
log.Fatal("Unauthorized: No refresh token present")
}
conf := oauth2.Config{
ClientID: token,
Endpoint: oauth2.Endpoint{
TokenURL: "https://api.tdameritrade.com/v1/oauth2/token",
},
RedirectURL: "https://localhost",
}
tkn := &oauth2.Token{
RefreshToken: refreshToken,
}
ctx := context.Background()
tc := conf.Client(ctx, tkn)
c, err := tdameritrade.NewClient(tc)
if err != nil {
log.Fatal(err)
}
txns, _, err := c.TransactionHistory.GetTransactions(ctx, "acountid", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", (*txns)[0].TransactionID)
}
|
[
"\"TDAMERITRADE_CLIENT_ID\"",
"\"TDAMERITRADE_REFRESH_TOKEN\""
] |
[] |
[
"TDAMERITRADE_REFRESH_TOKEN",
"TDAMERITRADE_CLIENT_ID"
] |
[]
|
["TDAMERITRADE_REFRESH_TOKEN", "TDAMERITRADE_CLIENT_ID"]
|
go
| 2 | 0 | |
eks/ng/configmap.go
|
package ng
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"text/template"
"time"
"github.com/aws/aws-k8s-tester/pkg/fileutil"
"go.uber.org/zap"
"k8s.io/utils/exec"
)
func (ts *tester) createConfigMap() error {
if ts.cfg.EKSConfig.AddOnNodeGroups.Role.ARN == "" {
return errors.New("empty AddOnNodeGroups.Role.ARN")
}
ts.cfg.Logger.Info("writing ConfigMap", zap.String("instance-role-arn", ts.cfg.EKSConfig.AddOnNodeGroups.Role.ARN))
body, p, err := writeConfigMapAuth(ts.cfg.EKSConfig.AddOnNodeGroups.Role.ARN)
if err != nil {
return err
}
ts.cfg.Logger.Info("applying ConfigMap")
fmt.Fprintf(ts.cfg.LogWriter, "\naws-auth ConfigMap:\n\n%s\n", body)
var output []byte
// might take several minutes for DNS to propagate
waitDur := 5 * time.Minute
retryStart := time.Now()
for time.Since(retryStart) < waitDur {
select {
case <-ts.cfg.Stopc:
return errors.New("create ConfigMap aborted")
case <-time.After(5 * time.Second):
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
output, err = exec.New().CommandContext(
ctx,
ts.cfg.EKSConfig.KubectlPath,
"--kubeconfig="+ts.cfg.EKSConfig.KubeConfigPath,
"apply",
"--filename="+p,
).CombinedOutput()
cancel()
out := string(output)
fmt.Fprintf(ts.cfg.LogWriter, "\n\"kubectl apply\" output:\n%s\n", out)
if err == nil {
break
}
// "configmap/aws-auth created" or "configmap/aws-auth unchanged"
if strings.Contains(out, " created") || strings.Contains(out, " unchanged") {
err = nil
break
}
ts.cfg.Logger.Warn("create ConfigMap failed", zap.Error(err))
ts.cfg.EKSConfig.RecordStatus(fmt.Sprintf("create ConfigMap failed (%v)", err))
}
if err != nil {
return fmt.Errorf("'kubectl apply' failed %v (output %q)", err, string(output))
}
ts.cfg.Logger.Info("created ConfigMap")
ts.cfg.EKSConfig.Sync()
return nil
}
// TODO: use client-go
// https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html
const configMapAuthTempl = `---
apiVersion: v1
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
data:
mapRoles: |
- rolearn: {{.NGInstanceRoleARN}}
%s
groups:
- system:bootstrappers
- system:nodes
`
type configMapAuth struct {
NGInstanceRoleARN string
}
func writeConfigMapAuth(instanceRoleARN string) (body string, fpath string, err error) {
kc := configMapAuth{NGInstanceRoleARN: instanceRoleARN}
tpl := template.Must(template.New("configMapAuthTempl").Parse(configMapAuthTempl))
buf := bytes.NewBuffer(nil)
if err = tpl.Execute(buf, kc); err != nil {
return "", "", err
}
// avoid '{{' conflicts with Go
body = fmt.Sprintf(buf.String(), `username: system:node:{{EC2PrivateDNSName}}`)
fpath, err = fileutil.WriteTempFile([]byte(body))
return body, fpath, err
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
omaha/site_scons/site_tools/atlmfc_vc16_0.py
|
# Copyright 2019 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.
# ========================================================================
# Windows ATL MFC for VC15 (Visual Studio 2017) tool for SCons.
import os
def _FindLocalInstall():
"""Returns the directory containing the local install of the tool.
Returns:
Path to tool (as a string), or None if not found.
"""
default_dir = os.environ['VCToolsInstallDir'] + 'atlmfc'
if os.path.exists(default_dir):
return default_dir
else:
return None
def generate(env):
# NOTE: SCons requires the use of this name, which fails gpylint.
"""SCons entry point for this tool."""
if not env.get('ATLMFC_VC16_0_DIR'):
env['ATLMFC_VC16_0_DIR'] = _FindLocalInstall()
env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC16_0_DIR/include').abspath)
env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC16_0_DIR/lib/x86').abspath)
|
[] |
[] |
[
"VCToolsInstallDir"
] |
[]
|
["VCToolsInstallDir"]
|
python
| 1 | 0 | |
provider/aws/sia-fargate/cmd/siad/main.go
|
//
// Copyright The Athenz Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"github.com/AthenZ/athenz/libs/go/sia/aws/attestation"
"github.com/AthenZ/athenz/libs/go/sia/aws/doc"
"github.com/AthenZ/athenz/libs/go/sia/aws/meta"
"github.com/AthenZ/athenz/libs/go/sia/logutil"
"github.com/AthenZ/athenz/libs/go/sia/util"
"github.com/AthenZ/athenz/provider/aws/sia-ec2/options"
"github.com/AthenZ/athenz/provider/aws/sia-fargate"
"io"
"io/ioutil"
"log"
"log/syslog"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
// Following can be set by the build script using LDFLAGS
var Version string
var ZtsEndPoint string
var DnsDomains string
var ProviderPrefix string
// End
var CmdOpt bool
var MetaEndPoint = os.Getenv("ECS_CONTAINER_METADATA_URI_V4")
const siaMainDir = "/var/lib/sia"
// getAttestationData fetches attestation data for all the services mentioned in the config file
func getAttestationData(opts *options.Options, region, taskId string, sysLogger io.Writer) ([]*attestation.AttestationData, error) {
data := []*attestation.AttestationData{}
for _, svc := range opts.Services {
a, err := sia.GetAttestationData(opts.Domain, svc.Name, opts.Account, region, taskId, opts.UseRegionalSTS, sysLogger)
if err != nil {
return nil, err
}
data = append(data, a)
}
return data, nil
}
// getSvcNames returns command separated list of service names
func getSvcNames(svcs []options.Service) string {
var b bytes.Buffer
for _, svc := range svcs {
b.WriteString(fmt.Sprintf("%s,", svc.Name))
}
return strings.TrimSuffix(b.String(), ",")
}
func getTaskConfig(metaEndPoint string) (string, string, string, error) {
account, taskId, region, err := sia.GetECSFargateData(metaEndPoint)
if err != nil {
return "", "", "", err
}
return account, taskId, region, nil
}
func getDomainServiceFromTaskRole() (string, string, error) {
uri := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
if uri == "" {
return "", "", fmt.Errorf("cannot fetch AWS_CONTAINER_CREDENTIALS_RELATIVE_URI env variable")
}
document, err := meta.GetData(sia.ECSMetaEndPoint, uri)
if err != nil {
return "", "", err
}
roleArn, err := doc.GetDocumentEntry(document, "RoleArn")
if err != nil {
return "", "", err
}
domain, service, err := util.ExtractServiceName(roleArn, ":role/")
if err != nil {
return "", "", err
}
return domain, service, nil
}
func main() {
cmd := flag.String("cmd", "", "optional sub command to run")
metaEndPoint := flag.String("meta", "", "optional meta endpoint to use for debugging")
ztsEndPoint := flag.String("zts", "", "Athenz Token Service (ZTS) endpoint")
ztsServerName := flag.String("ztsservername", "", "zts server name for tls connections")
ztsCACert := flag.String("ztscacert", "", "zts CA certificate file")
dnsDomains := flag.String("dnsdomain", "", "DNS Domain associated with the provider")
ztsPort := flag.Int("ztsport", 4443, "Athenz Token Service (ZTS) port number")
pConf := flag.String("config", "/etc/sia/sia_config", "The config file to run against")
useRegionalSTS := flag.Bool("regionalsts", false, "Use regional STS endpoint instead of global")
providerPrefix := flag.String("providerprefix", "", "Provider name prefix e.g athenz.aws")
flag.BoolVar(&CmdOpt, "version", false, "Display version information")
flag.Parse()
if CmdOpt && len(flag.Args()) == 0 {
fmt.Println(Version)
os.Exit(0)
}
var sysLogger io.Writer
sysLogger, err := syslog.New(syslog.LOG_INFO|syslog.LOG_DAEMON, "siad")
if err != nil {
log.Printf("Unable to create sys logger: %v\n", err)
sysLogger = os.Stdout
}
if ZtsEndPoint == "" && *ztsEndPoint == "" {
logutil.LogFatal(sysLogger, "missing zts!\n")
}
if *ztsEndPoint != "" {
// run time param takes precedence over build time
ZtsEndPoint = *ztsEndPoint
}
if DnsDomains == "" && *dnsDomains == "" {
logutil.LogFatal(sysLogger, "missing dnsdomain!\n")
}
// run time param takes precedence over build time
if *dnsDomains != "" {
DnsDomains = *dnsDomains
}
ztsAwsDomainList := strings.Split(DnsDomains, ",")
if ProviderPrefix == "" && *providerPrefix == "" {
logutil.LogFatal(sysLogger, "missing providerprefix!\n")
}
if *providerPrefix != "" {
// run time param takes precedence over build time
ProviderPrefix = *providerPrefix
}
if *metaEndPoint != "" {
// run time param takes precedence over build time
MetaEndPoint = *metaEndPoint
}
logutil.LogInfo(sysLogger, "Using ZTS: %s with DNS domain: %s & Provider prefix: %s\n", ZtsEndPoint, DnsDomains, ProviderPrefix)
accountId, taskId, region, err := getTaskConfig(MetaEndPoint)
if err != nil {
logutil.LogFatal(sysLogger, "Unable to get account, task id from available credentials, error: %v\n", err)
}
logutil.LogInfo(sysLogger, "Got accountId: %s, region: %s, taskId: %s from Fargate MetaEndPoint\n", accountId, region, taskId)
domain, service, err := getDomainServiceFromTaskRole()
if err != nil {
logutil.LogFatal(sysLogger, "Unable to get domain, service from IAM task role, error: %v\n", err)
}
confBytes, err := ioutil.ReadFile(*pConf)
if err != nil {
var config options.Config
config.Version = "1.0.0"
config.Service = service
config.Accounts = make([]options.ConfigAccount, 1)
config.Accounts[0] = options.ConfigAccount{Domain: domain, Account: accountId}
confBytes, _ = json.Marshal(config)
}
opts, err := options.NewOptions(confBytes, accountId, MetaEndPoint, siaMainDir, Version, *ztsCACert, *ztsServerName, ztsAwsDomainList, "", sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Unable to formulate options, error: %v\n", err)
}
// if useRegionalSTS flag is provided then override config value
if useRegionalSTS != nil && *useRegionalSTS {
opts.UseRegionalSTS = *useRegionalSTS
}
opts.Provider = ProviderPrefix
opts.Ssh = false
logutil.LogInfo(sysLogger, "Request SSH Certificates is always false for Fargate: %t\n", opts.Ssh)
opts.Version = fmt.Sprintf("SIA-FARGATE %s", Version)
log.Printf("options: %+v", opts)
data, err := getAttestationData(opts, region, taskId, sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Unable to formulate attestation data, error: %v\n", err)
}
//for now we're going to rotate once every day
//since our server and role certs are valid for
//30 days by default
rotationInterval := 24 * 60 * time.Minute
ztsUrl := fmt.Sprintf("https://%s:%d/zts/v1", ZtsEndPoint, *ztsPort)
err = util.SetupSIADirs(siaMainDir, "", sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Unable to setup sia directories, error: %v\n", err)
}
svcs := getSvcNames(opts.Services)
switch *cmd {
case "rolecert":
sia.GetRoleCertificate(ztsUrl,
fmt.Sprintf("%s/%s.%s.key.pem", opts.KeyDir, opts.Domain, opts.Services[0].Name),
fmt.Sprintf("%s/%s.%s.cert.pem", opts.CertDir, opts.Domain, opts.Services[0].Name),
opts,
sysLogger,
)
case "post":
err := sia.RegisterInstance(data, ztsUrl, opts, region, sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Register identity failed, err: %v\n", err)
}
logutil.LogInfo(sysLogger, "identity registered for services: %s\n", svcs)
case "rotate":
err = sia.RefreshInstance(data, ztsUrl, opts, region, sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Refresh identity failed, err: %v\n", err)
}
logutil.LogInfo(sysLogger, "Identity successfully refreshed for services: %s\n", svcs)
default:
// if we already have a cert file then we're not going to
// prove our identity since most likely it will not succeed
// due to boot time check (this could be just a regular
// service restart for any reason). Instead, we'll just skip
// over and try to rotate the certs
initialSetup := true
if files, err := ioutil.ReadDir(opts.CertDir); err != nil || len(files) <= 0 {
err := sia.RegisterInstance(data, ztsUrl, opts, region, sysLogger)
if err != nil {
logutil.LogFatal(sysLogger, "Register identity failed, error: %v\n", err)
}
} else {
initialSetup = false
logutil.LogInfo(sysLogger, "Identity certificate file already exists. Retrieving identity details...\n")
}
logutil.LogInfo(sysLogger, "Identity established for services: %s\n", svcs)
stop := make(chan bool, 1)
errors := make(chan error, 1)
go func() {
for {
logutil.LogInfo(sysLogger, "Identity being used: %s\n", opts.Name)
// if we just did our initial setup there is no point
// to refresh the certs again. so we are going to skip
// this time around and refresh certs next time
if !initialSetup {
data, err = getAttestationData(opts, region, taskId, sysLogger)
if err != nil {
errors <- fmt.Errorf("Cannot get attestation data: %v\n", err)
return
}
err = sia.RefreshInstance(data, ztsUrl, opts, region, sysLogger)
if err != nil {
errors <- fmt.Errorf("refresh identity failed: %v\n", err)
return
}
logutil.LogInfo(sysLogger, "identity successfully refreshed for services: %s\n", svcs)
} else {
initialSetup = false
}
sia.GetRoleCertificate(ztsUrl,
fmt.Sprintf("%s/%s.%s.key.pem", opts.KeyDir, opts.Domain, opts.Services[0].Name),
fmt.Sprintf("%s/%s.%s.cert.pem", opts.CertDir, opts.Domain, opts.Services[0].Name),
opts,
sysLogger,
)
select {
case <-stop:
errors <- nil
return
case <-time.After(rotationInterval):
break
}
}
}()
go func() {
signals := make(chan os.Signal, 2)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
sig := <-signals
logutil.LogInfo(sysLogger, "Received signal %v, stopping rotation\n", sig)
stop <- true
}()
err = <-errors
if err != nil {
logutil.LogInfo(sysLogger, "%v\n", err)
}
}
os.Exit(0)
}
|
[
"\"ECS_CONTAINER_METADATA_URI_V4\"",
"\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\""
] |
[] |
[
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
"ECS_CONTAINER_METADATA_URI_V4"
] |
[]
|
["AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "ECS_CONTAINER_METADATA_URI_V4"]
|
go
| 2 | 0 | |
code/go/0chain.net/blobbercore/handler/helper_integration_test.go
|
package handler
import (
"context"
"database/sql"
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
blobbergrpc "github.com/0chain/blobber/code/go/0chain.net/blobbercore/blobbergrpc/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gorm.io/driver/postgres"
"github.com/0chain/blobber/code/go/0chain.net/core/common"
"github.com/0chain/blobber/code/go/0chain.net/blobbercore/config"
"github.com/spf13/viper"
"testing"
"gorm.io/gorm"
"github.com/0chain/gosdk/core/zcncrypto"
)
const BlobberTestAddr = "127.0.0.1:31501"
const RetryAttempts = 8
const RetryTimeout = 3
func randString(n int) string {
const hexLetters = "abcdef0123456789"
var sb strings.Builder
for i := 0; i < n; i++ {
sb.WriteByte(hexLetters[rand.Intn(len(hexLetters))])
}
return sb.String()
}
func setupHandlerIntegrationTests(t *testing.T) (blobbergrpc.BlobberServiceClient, *TestDataController) {
// args := make(map[string]bool)
// for _, arg := range os.Args {
// args[arg] = true
// }
if os.Getenv("integration") != "1" {
// if !args["integration"] {
t.Skip()
}
var conn *grpc.ClientConn
var err error
for i := 0; i < RetryAttempts; i++ {
conn, err = grpc.Dial(BlobberTestAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Println(err)
<-time.After(time.Second * RetryTimeout)
continue
}
break
}
if err != nil {
t.Fatal(err)
}
bClient := blobbergrpc.NewBlobberServiceClient(conn)
setupIntegrationTestConfig(t)
db, err := gorm.Open(postgres.Open(fmt.Sprintf(
"host=%v port=%v user=%v dbname=%v password=%v sslmode=disable",
config.Configuration.DBHost, config.Configuration.DBPort,
config.Configuration.DBUserName, config.Configuration.DBName,
config.Configuration.DBPassword)), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
tdController := NewTestDataController(db)
return bClient, tdController
}
type TestDataController struct {
db *gorm.DB
}
func NewTestDataController(db *gorm.DB) *TestDataController {
return &TestDataController{db: db}
}
// ClearDatabase deletes all data from all tables
func (c *TestDataController) ClearDatabase() error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
_, err = tx.Exec("truncate allocations cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate reference_objects cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate commit_meta_txns cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate collaborators cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate allocation_changes cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate allocation_connections cascade")
if err != nil {
return err
}
_, err = tx.Exec("truncate write_markers cascade")
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetAllocationTestData() error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'exampleTransaction','exampleOwnerId','exampleOwnerPublicKey',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetFileMetaDataTestData(allocationTx, pubKey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubKey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash)
VALUES (1234,'exampleId','exampleId:examplePath','exampleId:examplePath','f','filename','examplePath','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash');
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO commit_meta_txns (ref_id,txn_id)
VALUES (1234,'someTxn');
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO collaborators (ref_id, client_id)
VALUES (1234, 'someClient');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetFileStatsTestData(allocationTx, pubKey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubKey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash)
VALUES (1234,'exampleId','exampleId:examplePath','exampleId:examplePath','f','filename','examplePath','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddListEntitiesTestData(allocationTx, pubkey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash)
VALUES (1234,'exampleId','exampleId:examplePath','exampleId:examplePath','f','filename','examplePath','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetObjectPathTestData(allocationTx, pubKey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubKey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetReferencePathTestData(allocationTx, pubkey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddGetObjectTreeTestData(allocationTx, pubkey string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','exampleOwnerId','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash)
VALUES (1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func GeneratePubPrivateKey(t *testing.T) (pubKey, privateKey string, signScheme zcncrypto.SignatureScheme) {
signScheme = zcncrypto.NewSignatureScheme("bls0chain")
wallet, err := signScheme.GenerateKeys()
if err != nil {
t.Fatal(err)
}
keyPair := wallet.Keys[0]
_ = signScheme.SetPrivateKey(keyPair.PrivateKey)
return keyPair.PublicKey, keyPair.PrivateKey, signScheme
}
func setupIntegrationTestConfig(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
configDir := strings.Split(pwd, "/code/go")[0] + "/config"
config.SetupDefaultConfig()
config.SetupConfig(configDir)
config.Configuration.DBHost = "localhost"
config.Configuration.DBName = viper.GetString("db.name")
config.Configuration.DBPort = viper.GetString("db.port")
config.Configuration.DBUserName = viper.GetString("db.user")
config.Configuration.DBPassword = viper.GetString("db.password")
}
func (c *TestDataController) AddCommitTestData(allocationTx, pubkey, clientId, wmSig string, now common.Timestamp) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_connections (connection_id, allocation_id, client_id, size, status)
VALUES ('connection_id' ,'exampleId','` + clientId + `', 1337, 1);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_changes (id, connection_id, operation, size, input)
VALUES (1 ,'connection_id','rename', 1200, '{"allocation_id":"exampleId","path":"/some_file","new_name":"new_name"}');
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO write_markers(prev_allocation_root, allocation_root, status, allocation_id, size, client_id, signature, blobber_id, timestamp, connection_id, client_key)
VALUES ('/', '/', 2,'exampleId', 1337, '` + clientId + `','` + wmSig + `','blobber_id', ` + fmt.Sprint(now) + `, 'connection_id', '` + pubkey + `');
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash, parent_path)
VALUES
(1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/'),
(123,'exampleId','exampleId:examplePath','exampleId:examplePath','f','some_file','/some_file','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddAttributesTestData(allocationTx, pubkey, clientId string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_connections (connection_id, allocation_id, client_id, size, status)
VALUES ('connection_id' ,'exampleId','` + clientId + `', 1337, 1);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash, parent_path)
VALUES
(1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/'),
(123,'exampleId','exampleId:examplePath','exampleId:examplePath','f','some_file','/some_file','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddCopyObjectData(allocationTx, pubkey, clientId string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_connections (connection_id, allocation_id, client_id, size, status)
VALUES ('connection_id' ,'exampleId','` + clientId + `', 1337, 1);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash, parent_path)
VALUES
(1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/copy','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/'),
(123,'exampleId','exampleId:examplePath','exampleId:examplePath','f','some_file','/some_file','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddRenameTestData(allocationTx, pubkey, clientId string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_connections (connection_id, allocation_id, client_id, size, status)
VALUES ('connection_id' ,'exampleId','` + clientId + `', 1337, 1);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash, parent_path)
VALUES
(1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/'),
(123,'exampleId','exampleId:examplePath','exampleId:examplePath','f','some_file','/some_file','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddDownloadTestData(allocationTx, pubkey, clientId, wmSig string, now common.Timestamp) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_connections (connection_id, allocation_id, client_id, size, status)
VALUES ('connection_id' ,'exampleId','` + clientId + `', 1337, 1);
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO allocation_changes (id, connection_id, operation, size, input)
VALUES (1 ,'connection_id','rename', 1200, '{"allocation_id":"exampleId","path":"/some_file","new_name":"new_name"}');
`)
if err != nil {
return err
}
_, err = tx.Exec(`
INSERT INTO reference_objects (id, allocation_id, path_hash,lookup_hash,type,name,path,hash,custom_meta,content_hash,merkle_root,actual_file_hash,mimetype,write_marker,thumbnail_hash, actual_thumbnail_hash, parent_path)
VALUES
(1234,'exampleId','exampleId:examplePath','exampleId:examplePath','d','root','/','someHash','customMeta','contentHash','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/'),
(123,'exampleId','exampleId:examplePath','exampleId:examplePath','f','some_file','/some_file','someHash','customMeta','tmpMonWenMyFile','merkleRoot','actualFileHash','mimetype','writeMarker','thumbnailHash','actualThumbnailHash','/');
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (c *TestDataController) AddUploadTestData(allocationTx, pubkey, clientId string) error {
var err error
var tx *sql.Tx
defer func() {
if err != nil {
if tx != nil {
errRollback := tx.Rollback()
if errRollback != nil {
log.Println(errRollback)
}
}
}
}()
db, err := c.db.DB()
if err != nil {
return err
}
tx, err = db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
expTime := time.Now().Add(time.Hour * 100000).UnixNano()
_, err = tx.Exec(`
INSERT INTO allocations (id, tx, owner_id, owner_public_key, expiration_date, payer_id, blobber_size, allocation_root, repairer_id, is_immutable)
VALUES ('exampleId' ,'` + allocationTx + `','` + clientId + `','` + pubkey + `',` + fmt.Sprint(expTime) + `,'examplePayerId', 99999999, '/', 'repairer_id', false);
`)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
|
[
"\"integration\""
] |
[] |
[
"integration"
] |
[]
|
["integration"]
|
go
| 1 | 0 | |
cmd/influxd/run/config.go
|
package run
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"regexp"
"strings"
"github.com/BurntSushi/toml"
"github.com/influxdata/influxdb/logger"
"github.com/influxdata/influxdb/monitor"
"github.com/influxdata/influxdb/monitor/diagnostics"
"github.com/influxdata/influxdb/pkg/tlsconfig"
"github.com/influxdata/influxdb/services/collectd"
"github.com/influxdata/influxdb/services/continuous_querier"
"github.com/influxdata/influxdb/services/graphite"
"github.com/influxdata/influxdb/services/httpd"
"github.com/influxdata/influxdb/services/meta"
"github.com/influxdata/influxdb/services/opentsdb"
"github.com/influxdata/influxdb/services/precreator"
"github.com/influxdata/influxdb/services/retention"
"github.com/influxdata/influxdb/services/subscriber"
"github.com/influxdata/influxdb/services/udp"
itoml "github.com/influxdata/influxdb/toml"
"github.com/influxdata/influxdb/tsdb"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
"github.com/angopher/chronus/coordinator"
"github.com/angopher/chronus/services/controller"
"github.com/angopher/chronus/services/hh"
)
const (
// DefaultBindAddress is the default address for various RPC services.
DefaultBindAddress = "127.0.0.1:8088"
)
// Config represents the configuration format for the influxd binary.
type Config struct {
Meta *meta.Config `toml:"meta"`
Data tsdb.Config `toml:"data"`
Coordinator coordinator.Config `toml:"coordinator"`
Retention retention.Config `toml:"retention"`
Precreator precreator.Config `toml:"shard-precreation"`
Monitor monitor.Config `toml:"monitor"`
Subscriber subscriber.Config `toml:"subscriber"`
HTTPD httpd.Config `toml:"http"`
Logging logger.Config `toml:"logging"`
GraphiteInputs []graphite.Config `toml:"graphite"`
CollectdInputs []collectd.Config `toml:"collectd"`
OpenTSDBInputs []opentsdb.Config `toml:"opentsdb"`
UDPInputs []udp.Config `toml:"udp"`
ContinuousQuery continuous_querier.Config `toml:"continuous_queries"`
HintedHandoff hh.Config `toml:"hinted-handoff"`
Controller controller.Config `toml:"controller"`
// Server reporting
ReportingDisabled bool `toml:"reporting-disabled"`
// BindAddress is the address that all TCP services use (Raft, Snapshot, Cluster, etc.)
BindAddress string `toml:"bind-address"`
// TLS provides configuration options for all https endpoints.
TLS tlsconfig.Config `toml:"tls"`
}
// NewConfig returns an instance of Config with reasonable defaults.
func NewConfig() *Config {
c := &Config{}
c.Meta = meta.NewConfig()
c.Data = tsdb.NewConfig()
c.Coordinator = coordinator.NewConfig()
c.Precreator = precreator.NewConfig()
c.Monitor = monitor.NewConfig()
c.Subscriber = subscriber.NewConfig()
c.HTTPD = httpd.NewConfig()
c.Logging = logger.NewConfig()
c.HintedHandoff = hh.NewConfig()
c.Controller = controller.NewConfig()
c.GraphiteInputs = []graphite.Config{graphite.NewConfig()}
c.CollectdInputs = []collectd.Config{collectd.NewConfig()}
c.OpenTSDBInputs = []opentsdb.Config{opentsdb.NewConfig()}
c.UDPInputs = []udp.Config{udp.NewConfig()}
c.ContinuousQuery = continuous_querier.NewConfig()
c.Retention = retention.NewConfig()
c.BindAddress = DefaultBindAddress
return c
}
// NewDemoConfig returns the config that runs when no config is specified.
func NewDemoConfig() (*Config, error) {
c := NewConfig()
var homeDir string
// By default, store meta and data files in current users home directory
u, err := user.Current()
if err == nil {
homeDir = u.HomeDir
} else if os.Getenv("HOME") != "" {
homeDir = os.Getenv("HOME")
} else {
return nil, fmt.Errorf("failed to determine current user for storage")
}
c.Meta.Dir = filepath.Join(homeDir, ".influxdb/meta")
c.Data.Dir = filepath.Join(homeDir, ".influxdb/data")
c.Data.WALDir = filepath.Join(homeDir, ".influxdb/wal")
return c, nil
}
// FromTomlFile loads the config from a TOML file.
func (c *Config) FromTomlFile(fpath string) error {
bs, err := ioutil.ReadFile(fpath)
if err != nil {
return err
}
// Handle any potential Byte-Order-Marks that may be in the config file.
// This is for Windows compatibility only.
// See https://github.com/influxdata/telegraf/issues/1378 and
// https://github.com/influxdata/influxdb/issues/8965.
bom := unicode.BOMOverride(transform.Nop)
bs, _, err = transform.Bytes(bom, bs)
if err != nil {
return err
}
return c.FromToml(string(bs))
}
// FromToml loads the config from TOML.
func (c *Config) FromToml(input string) error {
// Replace deprecated [cluster] with [coordinator]
re := regexp.MustCompile(`(?m)^\s*\[cluster\]`)
input = re.ReplaceAllStringFunc(input, func(in string) string {
in = strings.TrimSpace(in)
out := "[coordinator]"
log.Printf("deprecated config option %s replaced with %s; %s will not be supported in a future release\n", in, out, in)
return out
})
_, err := toml.Decode(input, c)
return err
}
// Validate returns an error if the config is invalid.
func (c *Config) Validate() error {
if err := c.Meta.Validate(); err != nil {
return err
}
if err := c.Data.Validate(); err != nil {
return err
}
if err := c.Monitor.Validate(); err != nil {
return err
}
if err := c.ContinuousQuery.Validate(); err != nil {
return err
}
if err := c.Retention.Validate(); err != nil {
return err
}
if err := c.Precreator.Validate(); err != nil {
return err
}
if err := c.Subscriber.Validate(); err != nil {
return err
}
for _, graphite := range c.GraphiteInputs {
if err := graphite.Validate(); err != nil {
return fmt.Errorf("invalid graphite config: %v", err)
}
}
for _, collectd := range c.CollectdInputs {
if err := collectd.Validate(); err != nil {
return fmt.Errorf("invalid collectd config: %v", err)
}
}
if err := c.TLS.Validate(); err != nil {
return err
}
return nil
}
// ApplyEnvOverrides apply the environment configuration on top of the config.
func (c *Config) ApplyEnvOverrides(getenv func(string) string) error {
return itoml.ApplyEnvOverrides(getenv, "INFLUXDB", c)
}
// Diagnostics returns a diagnostics representation of Config.
func (c *Config) Diagnostics() (*diagnostics.Diagnostics, error) {
return diagnostics.RowFromMap(map[string]interface{}{
"reporting-disabled": c.ReportingDisabled,
"bind-address": c.BindAddress,
}), nil
}
func (c *Config) diagnosticsClients() map[string]diagnostics.Client {
// Config settings that are always present.
m := map[string]diagnostics.Client{
"config": c,
"config-data": c.Data,
"config-meta": c.Meta,
"config-coordinator": c.Coordinator,
"config-retention": c.Retention,
"config-precreator": c.Precreator,
"config-monitor": c.Monitor,
"config-subscriber": c.Subscriber,
"config-httpd": c.HTTPD,
"config-cqs": c.ContinuousQuery,
}
// Config settings that can be repeated and can be disabled.
if g := graphite.Configs(c.GraphiteInputs); g.Enabled() {
m["config-graphite"] = g
}
if cc := collectd.Configs(c.CollectdInputs); cc.Enabled() {
m["config-collectd"] = cc
}
if t := opentsdb.Configs(c.OpenTSDBInputs); t.Enabled() {
m["config-opentsdb"] = t
}
if u := udp.Configs(c.UDPInputs); u.Enabled() {
m["config-udp"] = u
}
return m
}
// registerDiagnostics registers the config settings with the Monitor.
func (c *Config) registerDiagnostics(m *monitor.Monitor) {
for name, dc := range c.diagnosticsClients() {
m.RegisterDiagnosticsClient(name, dc)
}
}
// registerDiagnostics deregisters the config settings from the Monitor.
func (c *Config) deregisterDiagnostics(m *monitor.Monitor) {
for name := range c.diagnosticsClients() {
m.DeregisterDiagnosticsClient(name)
}
}
|
[
"\"HOME\"",
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
anyway/importmail_cbs.py
|
from __future__ import print_function
import email
import imaplib
import os
from datetime import datetime
import time
from .utilities import time_delta
import sys
import argparse
import logging
mail_dir = 'cbs/data'
def main(detach_dir, username=None, password=None, email_search_start_date=''):
try:
username = username or os.environ.get('MAILUSER')
password = password or os.environ.get('MAILPASS')
if not username:
logging.error("Username not set. Please set env var MAILUSER or use the --username argument")
if not password:
logging.error("Password not set. Please set env var MAILPASS or use the --password argument")
if not username or not password:
exit()
imapsession = imaplib.IMAP4_SSL('imap.gmail.com')
try:
imapsession.login(username, password)
except imaplib.IMAP4.error:
logging.error('Bad credentials, unable to sign in!')
exit()
try:
imapsession.select(mail_dir)
if email_search_start_date == '':
typ, data = imapsession.search(None, 'ALL')
else:
search_start_date = datetime.strptime(email_search_start_date, '%d.%m.%Y').strftime('%d-%b-%Y')
typ, data = imapsession.search(None, '(SINCE "{0}")'.format(search_start_date))
except imaplib.IMAP4.error:
logging.error('Error searching given mailbox: %s' % mail_dir)
exit()
file_found = False
if not os.path.exists(detach_dir):
os.makedirs(detach_dir)
total = 0
# Iterating over all emails
started = datetime.now()
logging.info("Login successful! Importing files, please hold...")
filepath = None
for msgId in data[0].split():
typ, message_parts = imapsession.fetch(msgId, '(RFC822)')
if typ != 'OK':
logging.error('Error fetching mail.')
raise Exception('Error fetching mail')
email_body = message_parts[0][1]
mail = email.message_from_string(email_body)
try:
mtime = datetime.strptime(mail['Date'][:-6], '%a, %d %b %Y %H:%M:%S')
except ValueError:
mtime = datetime.strptime(mail['Date'][:-12], '%a, %d %b %Y %H:%M:%S')
for part in mail.walk():
if part.get_content_maintype() == 'multipart' or part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if bool(filename) and filename.endswith(".zip"):
filename = '{0}-{1}_{2}-{3}.zip'.format('cbs_data', mtime.date(), mtime.hour, mtime.minute)
filepath = os.path.join(detach_dir, filename)
if os.path.isfile(filepath):
break
total += 1
print('Currently loading: ' + filename + ' ')
sys.stdout.write("\033[F")
time.sleep(0.1)
with open(filepath, 'wb') as fp:
fp.write(part.get_payload(decode=True))
file_found = True
if file_found:
break
logging.info("Imported {0} file(s) in {1}".format(total, time_delta(started)))
imapsession.close()
imapsession.logout()
return filepath
except Exception as _:
pass # Todo - send an error email to anyway email
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='')
parser.add_argument('--password', default='')
parser.add_argument('--lastmail', action='store_true', default=False)
args = parser.parse_args()
main(args.username, args.password, args.lastmail)
|
[] |
[] |
[
"MAILPASS",
"MAILUSER"
] |
[]
|
["MAILPASS", "MAILUSER"]
|
python
| 2 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.