text
stringlengths 11
4.05M
|
|---|
package algorithms
import (
"AlgorizmiGo/algorithms"
"testing"
)
func TestPlay(t *testing.T) {
algorithms.Play()
}
|
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"testing"
)
func Test_validateIsIbcDenomParam(t *testing.T) {
type args struct {
i interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{"invalid type", args{sdk.OneInt()}, true},
{"wrong length", args{"ibc/6B5A664BF0AF4F71B2F0BAA33141E2F1321242FBD"}, true},
{"invalid denom", args{"aaa/6B5A664BF0AF4F71B2F0BAA33141E2F1321242FBD5D19762F541EC971ACB0865"}, true},
{"correct IBC denom", args{IbcCroDenomDefaultValue}, false},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.wantErr, validateIsIbcDenom(tt.args.i) != nil)
})
}
}
func Test_validateIsUint64(t *testing.T) {
type args struct {
i interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{"invalid type", args{"a"}, true},
{"correct IBC timeout", args{IbcTimeoutDefaultValue}, false},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.wantErr, validateIsUint64(tt.args.i) != nil)
})
}
}
|
package carchivum
import (
"archive/tar"
"compress/gzip"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
type testFile struct {
name string
content []byte
}
var TestFiles []testFile
func initTestFiles() {
TestFiles = make([]testFile, 0)
TestFiles = append(TestFiles, testFile{name: "test/test1.txt", content: []byte("some content\n")})
TestFiles = append(TestFiles, testFile{name: "test/test2.txt", content: []byte("some more content\n")})
TestFiles = append(TestFiles, testFile{name: "test/dir/test1.txt", content: []byte("different content\n")})
TestFiles = append(TestFiles, testFile{name: "test/dir/test2.txt", content: []byte("might be different content\n")})
}
func CreateTempTgz() (string, error) {
tmpDir := os.TempDir()
testTar := filepath.Join(tmpDir, "test.tgz")
f, _ := os.OpenFile(testTar, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0777)
// create a tgz file
gw := gzip.NewWriter(f)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
for _, testF := range TestFiles {
hdr := &tar.Header{
Name: testF.name,
Size: int64(len(testF.content)),
}
err := tw.WriteHeader(hdr)
if err != nil {
return testTar, err
}
_, err = tw.Write(testF.content)
if err != nil {
return testTar, err
}
}
return testTar, nil
}
func CreateTempFiles() (dir string, err error) {
initTestFiles()
tmpDir, _ := ioutil.TempDir("", "car")
err = os.Chdir(tmpDir)
if err != nil {
return "", err
}
err = os.MkdirAll("test/dir", 0755)
if err != nil {
return "", err
}
for _, f := range TestFiles {
err = ioutil.WriteFile(f.name, f.content, 0755)
if err != nil {
return tmpDir, err
}
}
return tmpDir, nil
}
func RemoveTmpDir(s string) error {
if s == "" {
return nil
}
return os.RemoveAll(s)
}
func TestGetFileParts(t *testing.T) {
tests := []struct {
value string
expectedDir string
expectedFilename string
expectedExt string
expectedErr string
}{
{"", "", "", "", ""},
{"test", "", "test", "", ""},
{"test.tar", "", "test", "tar", ""},
{"/dir/name/test.tar", "/dir/name/", "test", "tar", ""},
{"dir/name/test.tar", "dir/name/", "test", "tar", ""},
{"../dir/name/test.tar", "../dir/name/", "test", "tar", ""},
}
for i, test := range tests {
dir, fname, ext, err := getFileParts(test.value)
if err != nil {
if err.Error() != test.expectedErr {
t.Errorf("%d: expected error to be %q, got %q", i, test.expectedErr, err)
}
continue
}
if test.expectedDir != dir {
t.Errorf("%d: expected dir to be %q got %q", i, test.expectedDir, dir)
}
if test.expectedFilename != fname {
t.Errorf("%d: expected filename to be %q got %q", i, test.expectedFilename, fname)
}
if test.expectedExt != ext {
t.Errorf("%d: expected ext to be %q got %q", i, test.expectedExt, ext)
}
}
}
|
package mtasts_test
import (
"context"
"fmt"
"github.com/foxcpp/go-mtasts"
)
func ExampleCache_Get() {
c := mtasts.NewRAMCache()
policy, err := c.Get(context.Background(), "gmail.com")
if err != nil {
fmt.Println("Oh noes!", err)
return
}
fmt.Println("Allowed MXs:", policy.MX)
}
|
package port
import (
"fmt"
"net"
"time"
"sync"
)
type PortResult struct {
Port int
State bool
Service string
}
type PortRange struct {
Start int
End int
}
func ScanPorts(hostname string) []PortResult{
wg := sync.WaitGroup{}
var portResult []PortResult
results := make(chan PortResult, len(common))
for port, service := range common {
wg.Add(1)
go ScanPort(hostname, port, service, results, &wg)
}
wg.Wait()
close(results)
for result := range results {
portResult = append(portResult, result)
}
return portResult
}
func ScanPort(hostname string, port int, service string, result chan PortResult, wg *sync.WaitGroup) {
defer wg.Done()
address := fmt.Sprintf("%s:%d", hostname, port)
portResult := PortResult{
Port: port,
Service: service,
}
conn, err := net.DialTimeout("tcp", address, 3 *time.Second)
if err != nil {
portResult.State = false
result <-portResult
return
}
defer conn.Close()
portResult.State = true
result <- portResult
}
|
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
type CallbackPostRequestBody struct {
JobID string `json:"job_id" bson:"job_id"`
JobName string `json:"job_name" bson:"job_name"`
JobContainerID string `json:"job_container_id" bson:"job_container_id"`
JobInstanceID string `json:"job_instance_id" bson:"job_instance_id"`
State int `json:"state" bson:"state"`
Status int `json:"status" bson:"status"`
StatusDescription string `json:"status_description" bson:"status_description"`
}
func jobCallbackMethod(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
paramsID := params["id"]
var jobInfo CallbackPostRequestBody
if err := json.NewDecoder(req.Body).Decode(&jobInfo); err != nil {
fmt.Println("Error decoding JSON: ", err)
return
}
//DELETE THIS later
fmt.Println("job info: ", jobInfo)
fmt.Printf("Received job completion at: %v\n", time.Now())
fmt.Printf("Params ID: %s\n", paramsID)
fmt.Printf("Job ID: %s\nJob Name: %s\nJob Container ID: %s\nJob Instance ID: %s\n",
jobInfo.JobID, jobInfo.JobName, jobInfo.JobContainerID, jobInfo.JobInstanceID)
fmt.Printf("State: %d\nStatus: %d\nStatus Description: %s\n",
jobInfo.State, jobInfo.Status, jobInfo.StatusDescription)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/jobcallback/{id}", jobCallbackMethod).Methods("POST")
log.Fatal(http.ListenAndServe(":3007", router))
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package cgroups
import (
"bufio"
"bytes"
"context"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/system"
"github.com/cockroachdb/errors"
)
const (
cgroupV1MemLimitFilename = "memory.stat"
cgroupV2MemLimitFilename = "memory.max"
cgroupV1CPUQuotaFilename = "cpu.cfs_quota_us"
cgroupV1CPUPeriodFilename = "cpu.cfs_period_us"
cgroupV1CPUSysUsageFilename = "cpuacct.usage_sys"
cgroupV1CPUUserUsageFilename = "cpuacct.usage_user"
cgroupV2CPUMaxFilename = "cpu.max"
cgroupV2CPUStatFilename = "cpu.stat"
)
// GetMemoryLimit attempts to retrieve the cgroup memory limit for the current
// process
func GetMemoryLimit() (limit int64, warnings string, err error) {
return getCgroupMem("/")
}
// `root` is set to "/" in production code and exists only for testing.
// cgroup memory limit detection path implemented here as
// /proc/self/cgroup file -> /proc/self/mountinfo mounts -> cgroup version -> version specific limit check
func getCgroupMem(root string) (limit int64, warnings string, err error) {
path, err := detectCntrlPath(filepath.Join(root, "/proc/self/cgroup"), "memory")
if err != nil {
return 0, "", err
}
// no memory controller detected
if path == "" {
return 0, "no cgroup memory controller detected", nil
}
mount, ver, err := getCgroupDetails(filepath.Join(root, "/proc/self/mountinfo"), path, "memory")
if err != nil {
return 0, "", err
}
switch ver {
case 1:
limit, warnings, err = detectMemLimitInV1(filepath.Join(root, mount))
case 2:
limit, warnings, err = detectMemLimitInV2(filepath.Join(root, mount, path))
default:
limit, err = 0, fmt.Errorf("detected unknown cgroup version index: %d", ver)
}
return limit, warnings, err
}
func readFile(filepath string) (res []byte, err error) {
var f *os.File
f, err = os.Open(filepath)
if err != nil {
return nil, err
}
defer func() {
err = errors.CombineErrors(err, f.Close())
}()
res, err = ioutil.ReadAll(f)
return res, err
}
func cgroupFileToUint64(filepath, desc string) (res uint64, err error) {
contents, err := readFile(filepath)
if err != nil {
return 0, errors.Wrapf(err, "error when reading %s from cgroup v1 at %s", desc, filepath)
}
res, err = strconv.ParseUint(string(bytes.TrimSpace(contents)), 10, 64)
if err != nil {
return 0, errors.Wrapf(err, "error when parsing %s from cgroup v1 at %s", desc, filepath)
}
return res, err
}
func cgroupFileToInt64(filepath, desc string) (res int64, err error) {
contents, err := readFile(filepath)
if err != nil {
return 0, errors.Wrapf(err, "error when reading %s from cgroup v1 at %s", desc, filepath)
}
res, err = strconv.ParseInt(string(bytes.TrimSpace(contents)), 10, 64)
if err != nil {
return 0, errors.Wrapf(err, "error when parsing %s from cgroup v1 at %s", desc, filepath)
}
return res, nil
}
func detectCPUQuotaInV1(cRoot string) (period, quota int64, err error) {
quotaFilePath := filepath.Join(cRoot, cgroupV1CPUQuotaFilename)
periodFilePath := filepath.Join(cRoot, cgroupV1CPUPeriodFilename)
quota, err = cgroupFileToInt64(quotaFilePath, "cpu quota")
if err != nil {
return 0, 0, err
}
period, err = cgroupFileToInt64(periodFilePath, "cpu period")
if err != nil {
return 0, 0, err
}
return period, quota, err
}
func detectCPUUsageInV1(cRoot string) (stime, utime uint64, err error) {
sysFilePath := filepath.Join(cRoot, cgroupV1CPUSysUsageFilename)
userFilePath := filepath.Join(cRoot, cgroupV1CPUUserUsageFilename)
stime, err = cgroupFileToUint64(sysFilePath, "cpu system time")
if err != nil {
return 0, 0, err
}
utime, err = cgroupFileToUint64(userFilePath, "cpu user time")
if err != nil {
return 0, 0, err
}
return stime, utime, err
}
func detectCPUQuotaInV2(cRoot string) (period, quota int64, err error) {
maxFilePath := filepath.Join(cRoot, cgroupV2CPUMaxFilename)
contents, err := readFile(maxFilePath)
if err != nil {
return 0, 0, errors.Wrapf(err, "error when read cpu quota from cgroup v2 at %s", maxFilePath)
}
fields := strings.Fields(string(contents))
if len(fields) > 2 || len(fields) == 0 {
return 0, 0, errors.Errorf("unexpected format when reading cpu quota from cgroup v2 at %s: %s", maxFilePath, contents)
}
if fields[0] == "max" {
// Negative quota denotes no limit.
quota = -1
} else {
quota, err = strconv.ParseInt(fields[0], 10, 64)
if err != nil {
return 0, 0, errors.Wrapf(err, "error when reading cpu quota from cgroup v2 at %s", maxFilePath)
}
}
if len(fields) == 2 {
period, err = strconv.ParseInt(fields[1], 10, 64)
if err != nil {
return 0, 0, errors.Wrapf(err, "error when reading cpu period from cgroup v2 at %s", maxFilePath)
}
}
return period, quota, nil
}
func detectCPUUsageInV2(cRoot string) (stime, utime uint64, err error) {
statFilePath := filepath.Join(cRoot, cgroupV2CPUStatFilename)
var stat *os.File
stat, err = os.Open(statFilePath)
if err != nil {
return 0, 0, errors.Wrapf(err, "can't read cpu usage from cgroup v2 at %s", statFilePath)
}
defer func() {
err = errors.CombineErrors(err, stat.Close())
}()
scanner := bufio.NewScanner(stat)
for scanner.Scan() {
fields := bytes.Fields(scanner.Bytes())
if len(fields) != 2 || (string(fields[0]) != "user_usec" && string(fields[0]) != "system_usec") {
continue
}
keyField := string(fields[0])
trimmed := string(bytes.TrimSpace(fields[1]))
usageVar := &stime
if keyField == "user_usec" {
usageVar = &utime
}
*usageVar, err = strconv.ParseUint(trimmed, 10, 64)
if err != nil {
return 0, 0, errors.Wrapf(err, "can't read cpu usage %s from cgroup v1 at %s", keyField, statFilePath)
}
}
return stime, utime, err
}
// Finds memory limit for cgroup V1 via looking in [contoller mount path]/memory.stat
func detectMemLimitInV1(cRoot string) (limit int64, warnings string, err error) {
statFilePath := filepath.Join(cRoot, cgroupV1MemLimitFilename)
stat, err := os.Open(statFilePath)
if err != nil {
return 0, "", errors.Wrapf(err, "can't read available memory from cgroup v1 at %s", statFilePath)
}
defer func() {
_ = stat.Close()
}()
scanner := bufio.NewScanner(stat)
for scanner.Scan() {
fields := bytes.Fields(scanner.Bytes())
if len(fields) != 2 || string(fields[0]) != "hierarchical_memory_limit" {
continue
}
trimmed := string(bytes.TrimSpace(fields[1]))
limit, err = strconv.ParseInt(trimmed, 10, 64)
if err != nil {
return 0, "", errors.Wrapf(err, "can't read available memory from cgroup v1 at %s", statFilePath)
}
return limit, "", nil
}
return 0, "", fmt.Errorf("failed to find expected memory limit for cgroup v1 in %s", statFilePath)
}
// Finds memory limit for cgroup V2 via looking into [controller mount path]/[leaf path]/memory.max
// TODO(vladdy): this implementation was based on podman+criu environment. It may cover not
// all the cases when v2 becomes more widely used in container world.
func detectMemLimitInV2(cRoot string) (limit int64, warnings string, err error) {
limitFilePath := filepath.Join(cRoot, cgroupV2MemLimitFilename)
var buf []byte
if buf, err = ioutil.ReadFile(limitFilePath); err != nil {
return 0, "", errors.Wrapf(err, "can't read available memory from cgroup v2 at %s", limitFilePath)
}
trimmed := string(bytes.TrimSpace(buf))
if trimmed == "max" {
return math.MaxInt64, "", nil
}
limit, err = strconv.ParseInt(trimmed, 10, 64)
if err != nil {
return 0, "", errors.Wrapf(err, "can't parse available memory from cgroup v2 in %s", limitFilePath)
}
return limit, "", nil
}
// The controller is defined via either type `memory` for cgroup v1 or via empty type for cgroup v2,
// where the type is the second field in /proc/[pid]/cgroup file
func detectCntrlPath(cgroupFilePath string, controller string) (string, error) {
cgroup, err := os.Open(cgroupFilePath)
if err != nil {
return "", errors.Wrapf(err, "failed to read %s cgroup from cgroups file: %s", controller, cgroupFilePath)
}
defer func() { _ = cgroup.Close() }()
scanner := bufio.NewScanner(cgroup)
var unifiedPathIfFound string
for scanner.Scan() {
fields := bytes.Split(scanner.Bytes(), []byte{':'})
if len(fields) != 3 {
// The lines should always have three fields, there's something fishy here.
continue
}
f0, f1 := string(fields[0]), string(fields[1])
// First case if v2, second - v1. We give v2 the priority here.
// There is also a `hybrid` mode when both versions are enabled,
// but no known container solutions support it afaik
if f0 == "0" && f1 == "" {
unifiedPathIfFound = string(fields[2])
} else if f1 == controller {
return string(fields[2]), nil
}
}
return unifiedPathIfFound, nil
}
// Reads /proc/[pid]/mountinfo for cgoup or cgroup2 mount which defines the used version.
// See http://man7.org/linux/man-pages/man5/proc.5.html for `mountinfo` format.
func getCgroupDetails(mountinfoPath string, cRoot string, controller string) (string, int, error) {
info, err := os.Open(mountinfoPath)
if err != nil {
return "", 0, errors.Wrapf(err, "failed to read mounts info from file: %s", mountinfoPath)
}
defer func() {
_ = info.Close()
}()
scanner := bufio.NewScanner(info)
for scanner.Scan() {
fields := bytes.Fields(scanner.Bytes())
if len(fields) < 10 {
continue
}
ver, ok := detectCgroupVersion(fields, controller)
if ok {
mountPoint := string(fields[4])
if ver == 2 {
return mountPoint, ver, nil
}
// It is possible that the controller mount and the cgroup path are not the same (both are relative to the NS root).
// So start with the mount and construct the relative path of the cgroup.
// To test:
// cgcreate -t $USER:$USER -a $USER:$USER -g memory:crdb_test
// echo 3999997952 > /sys/fs/cgroup/memory/crdb_test/memory.limit_in_bytes
// cgexec -g memory:crdb_test ./cockroach start-single-node
// cockroach.log -> server/config.go:433 ⋮ system total memory: ‹3.7 GiB›
// without constructing the relative path
// cockroach.log -> server/config.go:433 ⋮ system total memory: ‹63 GiB›
nsRelativePath := string(fields[3])
if !strings.Contains(nsRelativePath, "..") {
// We don't expect to see err here ever but in case that it happens
// the best action is to ignore the line and hope that the rest of the lines
// will allow us to extract a valid path.
if relPath, err := filepath.Rel(nsRelativePath, cRoot); err == nil {
return filepath.Join(mountPoint, relPath), ver, nil
}
}
}
}
return "", 0, fmt.Errorf("failed to detect cgroup root mount and version")
}
// Return version of cgroup mount for memory controller if found
func detectCgroupVersion(fields [][]byte, controller string) (_ int, found bool) {
if len(fields) < 10 {
return 0, false
}
// Due to strange format there can be optional fields in the middle of the set, starting
// from the field #7. The end of the fields is marked with "-" field
var pos = 6
for pos < len(fields) {
if bytes.Equal(fields[pos], []byte{'-'}) {
break
}
pos++
}
// No optional fields separator found or there is less than 3 fields after it which is wrong
if (len(fields) - pos - 1) < 3 {
return 0, false
}
pos++
// Check for controller specifically in cgroup v1 (it is listed in super options field),
// as the limit can't be found if it is not enforced
if bytes.Equal(fields[pos], []byte("cgroup")) && bytes.Contains(fields[pos+2], []byte(controller)) {
return 1, true
} else if bytes.Equal(fields[pos], []byte("cgroup2")) {
return 2, true
}
return 0, false
}
// CPUUsage returns CPU usage and quotas for an entire cgroup.
type CPUUsage struct {
// System time and user time taken by this cgroup or process. In nanoseconds.
Stime, Utime uint64
// CPU period and quota for this process, in microseconds. This cgroup has
// access to up to (quota/period) proportion of CPU resources on the system.
// For instance, if there are 4 CPUs, quota = 150000, period = 100000,
// this cgroup can use around ~1.5 CPUs, or 37.5% of total scheduler time.
// If quota is -1, it's unlimited.
Period, Quota int64
// NumCPUs is the number of CPUs in the system. Always returned even if
// not called from a cgroup.
NumCPU int
}
// CPUShares returns the number of CPUs this cgroup can be expected to
// max out. If there's no limit, NumCPU is returned.
func (c CPUUsage) CPUShares() float64 {
if c.Period <= 0 || c.Quota <= 0 {
return float64(c.NumCPU)
}
return float64(c.Quota) / float64(c.Period)
}
// GetCgroupCPU returns the CPU usage and quota for the current cgroup.
func GetCgroupCPU() (CPUUsage, error) {
cpuusage, err := getCgroupCPU("/")
cpuusage.NumCPU = system.NumCPU()
return cpuusage, err
}
// Helper function for getCgroupCPU. Root is always "/", except in tests.
func getCgroupCPU(root string) (CPUUsage, error) {
path, err := detectCntrlPath(filepath.Join(root, "/proc/self/cgroup"), "cpu,cpuacct")
if err != nil {
return CPUUsage{}, err
}
// No CPU controller detected
if path == "" {
return CPUUsage{}, errors.New("no cpu controller detected")
}
mount, ver, err := getCgroupDetails(filepath.Join(root, "/proc/self/mountinfo"), path, "cpu,cpuacct")
if err != nil {
return CPUUsage{}, err
}
var res CPUUsage
switch ver {
case 1:
res.Period, res.Quota, err = detectCPUQuotaInV1(filepath.Join(root, mount))
if err != nil {
return res, err
}
res.Stime, res.Utime, err = detectCPUUsageInV1(filepath.Join(root, mount))
if err != nil {
return res, err
}
case 2:
res.Period, res.Quota, err = detectCPUQuotaInV2(filepath.Join(root, mount, path))
if err != nil {
return res, err
}
res.Stime, res.Utime, err = detectCPUUsageInV2(filepath.Join(root, mount, path))
if err != nil {
return res, err
}
default:
return CPUUsage{}, fmt.Errorf("detected unknown cgroup version index: %d", ver)
}
return res, nil
}
// AdjustMaxProcs sets GOMAXPROCS (if not overridden by env variables) to be
// the CPU limit of the current cgroup, if running inside a cgroup with a cpu
// limit lower than system.NumCPU(). This is preferable to letting it fall back
// to Go default, which is system.NumCPU(), as the Go scheduler would be running
// more OS-level threads than can ever be concurrently scheduled.
func AdjustMaxProcs(ctx context.Context) {
if _, set := os.LookupEnv("GOMAXPROCS"); !set {
if cpuInfo, err := GetCgroupCPU(); err == nil {
numCPUToUse := int(math.Ceil(cpuInfo.CPUShares()))
if numCPUToUse < system.NumCPU() && numCPUToUse > 0 {
log.Infof(ctx, "running in a container; setting GOMAXPROCS to %d", numCPUToUse)
runtime.GOMAXPROCS(numCPUToUse)
}
}
}
}
|
package proc
import (
"github.com/akhenakh/statgo"
"code.cloudfoundry.org/bytefmt"
"strconv"
)
type Proc struct {
Host *statgo.HostInfos
CPU *statgo.CPUStats
Mem *statgo.MemStats
}
func (p *Proc) Get() Proc {
s := statgo.NewStat()
return Proc{
Host: s.HostInfos(),
CPU: s.CPUStats(),
Mem: s.MemStats(),
}
}
func (p *Proc) GetHTML() string {
str := ""
s := statgo.NewStat()
str += "<h2>" + s.HostInfos().HostName + "</h2>"
str += "Operating System: " + s.HostInfos().OSName + "<br>"
str += "OS Release: " + s.HostInfos().OSRelease + "<br>"
str += "OS Version: " + s.HostInfos().OSVersion + "<br>"
str += "Platform: " + s.HostInfos().Platform + "<br>"
str += "CPUs: " + strconv.Itoa(s.HostInfos().NCPUs) + "<br>"
str += "Max CPUs: " + strconv.Itoa(s.HostInfos().MaxCPUs) + "<br>"
str += "BitWidth: " + strconv.Itoa(s.HostInfos().BitWidth) + "<br>"
str += "<br>"
str += "User CPU: " + strconv.FormatFloat(s.CPUStats().User, 'g', 1, 64) + "<br>"
str += "Kernel CPU: " + strconv.FormatFloat(s.CPUStats().Kernel, 'g', 1, 64) + "<br>"
str += "Idle: " + strconv.FormatFloat(s.CPUStats().Idle, 'g', 1, 64) + "<br>"
str += "IOWait: " + strconv.FormatFloat(s.CPUStats().IOWait, 'g', 1, 64) + "<br>"
str += "Swap: " + strconv.FormatFloat(s.CPUStats().Swap, 'g', 1, 64) + "<br>"
str += "Nice: " + strconv.FormatFloat(s.CPUStats().Nice, 'g', 1, 64) + "<br>"
str += "LoadMin1: " + strconv.FormatFloat(s.CPUStats().LoadMin1, 'g', 1, 64) + "<br>"
str += "LoadMin5: " + strconv.FormatFloat(s.CPUStats().LoadMin5, 'g', 1, 64) + "<br>"
str += "LoadMin15: " + strconv.FormatFloat(s.CPUStats().LoadMin15, 'g', 1, 64) + "<br>"
str += "<br>"
str += "Total: " + bytefmt.ByteSize(uint64(s.MemStats().Total)) + "<br>"
str += "Free: " + bytefmt.ByteSize(uint64(s.MemStats().Free)) + "<br>"
str += "Used: " + bytefmt.ByteSize(uint64(s.MemStats().Used)) + "<br>"
str += "Cache: " + strconv.Itoa(s.MemStats().Cache) + "<br>"
str += "SwapTotal: " + strconv.Itoa(s.MemStats().SwapTotal) + "<br>"
str += "SwapUsed: " + strconv.Itoa(s.MemStats().SwapUsed) + "<br>"
str += "SwapFree: " + strconv.Itoa(s.MemStats().SwapFree) + "<br>"
return str
/*
stat, err := linuxproc.ReadStat("/proc/stat")
if err != nil {
log.Print("stat read fail")
return str
}
str += "<h1>CPU Stats</h1>"
str += "<table>"
str += "<tr>"
str += "<th>User</th>"
str += "<th>Nice</th>"
str += "<th>System</th>"
str += "<th>Idle</th>"
str += "<th>IOWait</th>"
str += "</tr>"
for _, s := range stat.CPUStats {
str += "<tr>"
str += "<td>" + strconv.FormatUint(s.User, 10) + "</td>"
str += "<td>" + strconv.FormatUint(s.Nice, 10) + "</td>"
str += "<td>" + strconv.FormatUint(s.System, 10) + "</td>"
str += "<td>" + strconv.FormatUint(s.Idle, 10) + "</td>"
str += "<td>" + strconv.FormatUint(s.IOWait, 10) + "</td>"
str += "</tr>"
}
str += "</table>"
return str
*/
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package network
import (
"context"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/cellular"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/ossettings"
"chromiumos/tast/local/chrome/uiauto/role"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: UnlockPinLockedSim,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verifies that a PIN locked SIM can only be unlocked by the correct PIN, and then subsequently connected to",
Contacts: []string{
"hsuregan@google.com",
"cros-connectivity@google.com",
},
SoftwareDeps: []string{"chrome"},
// Run test only on cellular capable devices that only have one active SIM.
Attr: []string{"group:cellular", "cellular_unstable", "cellular_sim_active"},
Fixture: "cellular",
Timeout: 8 * time.Minute,
Vars: []string{"autotest_host_info_labels"},
})
}
func UnlockPinLockedSim(ctx context.Context, s *testing.State) {
// Gather Shill Device SIM properties.
labels, err := cellular.GetLabelsAsStringArray(ctx, s.Var, "autotest_host_info_labels")
if err != nil {
s.Fatal("Failed to read autotest_host_info_labels: ", err)
}
// Get cellular helper, used to determine if SIM is actually PIN locked/unlocked.
helper, err := cellular.NewHelperWithLabels(ctx, labels)
if err != nil {
s.Fatal("Failed to create cellular.Helper: ", err)
}
iccid, err := helper.GetCurrentICCID(ctx)
if err != nil {
s.Fatal("Could not get current ICCID: ", err)
}
currentPin, currentPuk, err := helper.GetPINAndPUKForICCID(ctx, iccid)
if err != nil {
s.Fatal("Could not get PIN and PUK: ", err)
}
if currentPin == "" {
// Do graceful exit, not to run tests on unknown PIN duts.
s.Fatal("Unable to find PIN code for ICCID: ", iccid)
}
if currentPuk == "" {
// Do graceful exit, not to run tests on unknown puk duts.
s.Fatal("Unable to find PUK code for ICCID: ", iccid)
}
// Check if PIN enabled and locked/set.
if helper.IsSimPinLocked(ctx) {
s.Fatal("Precondition of an unlocked SIM was not met")
}
// Shorten deadline to leave time for cleanup
cleanupCtx := ctx
cleanupCtx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
s.Log("Attempting to enable sim lock with correct pin")
if err = helper.Device.RequirePin(ctx, currentPin, true); err != nil {
s.Fatal("Failed to enable pin, mostly default pin needs to set on dut: ", err)
}
defer func(ctx context.Context) {
// Unlock and disable pin lock.
if err = helper.Device.RequirePin(ctx, currentPin, false); err != nil {
// Unlock and disable pin lock if failed after locking pin.
if errNew := helper.ClearSIMLock(ctx, currentPin, currentPuk); errNew != nil {
s.Log("Failed to clear default pin lock: ", errNew)
}
s.Fatal("Failed to disable default pin lock: ", err)
}
}(cleanupCtx)
// ResetModem needed for sim power reset to reflect locked type values.
if _, err := helper.ResetModem(ctx); err != nil {
s.Log("Failed to reset modem: ", err)
}
// Start a new chrome session
cr, err := chrome.New(ctx)
if err != nil {
s.Fatal("Failed to create a new instance of Chrome: ", err)
}
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to create Test API connection: ", err)
}
// Opening the mobile data page via ossettings.OpenMobileDataSubpage() will not work if the device does not support multisim and the SIM is locked.
settings, err := ossettings.Launch(ctx, tconn)
if err != nil {
s.Fatal("Failed to launch OS settings: ", err)
}
ui := uiauto.New(tconn).WithTimeout(5 * time.Minute)
goNavigateToMobileData := func() {
mobileDataLinkNode := nodewith.HasClass("cr-title-text").Name("Mobile data").Role(role.Heading)
if err := settings.NavigateToPageURL(ctx, cr, "networks?type=Cellular", ui.WaitUntilExists(mobileDataLinkNode)); err != nil {
s.Fatal("Failed to navigate to mobile data page 1")
}
}
goNavigateToMobileData()
kb, err := input.Keyboard(ctx)
if err != nil {
s.Fatal("Failed to open the keyboard: ", err)
}
defer kb.Close()
refreshProfileText := nodewith.NameStartingWith("Refreshing profile list").Role(role.StaticText)
if err := settings.WithTimeout(5 * time.Second).WaitUntilExists(refreshProfileText)(ctx); err == nil {
s.Log("Wait until refresh profile finishes")
if err := settings.WithTimeout(5 * time.Minute).WaitUntilGone(refreshProfileText)(ctx); err != nil {
s.Fatal("Failed to wait until refresh profile complete: ", err)
}
}
var incorrectPinSublabel = nodewith.NameContaining("Incorrect PIN").Role(role.StaticText)
if err := uiauto.Combine("Incorrect PIN does not unlock the SIM",
ui.LeftClick(ossettings.UnlockButton),
ui.WaitUntilExists(ossettings.CancelButton),
// Use a bad PIN.
kb.TypeAction(currentPin+"0"),
ui.LeftClick(ossettings.UnlockButton),
ui.WaitUntilExists(incorrectPinSublabel),
)(ctx); err != nil {
s.Fatal("Unlock button can still be clicked when incorrect PIN was entered: ", err)
}
networkName, err := helper.GetCurrentNetworkName(ctx)
if err != nil {
s.Fatal("Could not get the Network name: ", err)
}
if err := uiauto.Combine("Correct PIN unlocks the SIM, and subsequently clicking on the network row initiates a connection",
kb.TypeAction(currentPin),
ui.LeftClick(ossettings.UnlockButton),
)(ctx); err != nil {
s.Fatal("Failed to unlock the SIM: ", err)
}
goNavigateToMobileData()
var networkNameDetail = nodewith.NameContaining(networkName).Role(role.Button).ClassName("subpage-arrow").First()
if err := uiauto.Combine("Verify network connected",
ui.WaitUntilExists(networkNameDetail),
ui.LeftClick(networkNameDetail),
ui.WaitUntilExists(ossettings.ConnectedStatus),
)(ctx); err != nil {
s.Fatal("Failed to verify network connected via settings: ", err)
}
}
|
package git
import "github.com/goreleaser/goreleaser/context"
// Pipe for brew deployment
type Pipe struct{}
// Description of the pipe
func (Pipe) Description() string {
return "Getting Git info"
}
// Run the pipe
func (Pipe) Run(ctx *context.Context) (err error) {
tag, err := currentTag()
if err != nil {
return
}
previous, err := previousTag(tag)
if err != nil {
return
}
log, err := log(previous, tag)
if err != nil {
return
}
ctx.Git = context.GitInfo{
CurrentTag: tag,
PreviousTag: previous,
Diff: log,
}
return
}
|
package main
import (
"flag"
"log"
"github.com/gin-gonic/gin"
"github.com/lmdtfy/lmdtfy/pkg/handler"
"github.com/lmdtfy/lmdtfy/pkg/store"
)
var (
listenAddr string
address string
dbName string
staticDir string
insertTestData bool
)
func main() {
// docker.New()
// docker.Build()
flag.StringVar(&address, "dbAddress", "localhost:28015", "")
flag.StringVar(&dbName, "db", "dev_lmdtfy", "")
flag.Parse()
if err := store.Connect(address, dbName); err != nil {
log.Fatal("Error connecting to database: ", err)
}
r := gin.Default()
r.POST("/hook", handler.Hook)
m := r.Group("/api")
//m.POST("/session", handler.Login)
//m.GET("/repo", handler.CreateRepo)
m.GET("/repo", handler.GetAllRepos)
m.GET("/auth/login/github", handler.LinkGithub)
r.Run(":4000")
}
|
package cache
import (
"context"
"github.com/I-Reven/Hexagonal/src/infrastructure/repository/redis"
redisV8 "github.com/go-redis/redis/v8"
"os"
"sync"
)
var (
once sync.Once
client *redisV8.Client
ctx context.Context
config = &redisV8.Options{
Addr: os.Getenv("REDIS_URL"),
Password: "",
DB: 0,
}
)
type Cache struct{}
func (*Cache) Init() redis.Redis {
once.Do(func() {
client = redisV8.NewClient(config)
ctx = context.Background()
})
return redis.Redis{Client: client, Ctx: ctx}
}
|
// Copyright 2020 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.
package stanza
import (
"encoding/xml"
"mellium.im/xmlstream"
"mellium.im/xmpp/internal/attr"
"mellium.im/xmpp/internal/ns"
"mellium.im/xmpp/jid"
)
// Namespaces used by this package, provided as a convenience.
const (
// The namespace for unique and stable stanza and origin IDs.
NSSid = "urn:xmpp:sid:0"
)
const idLen = 32
// ID is a unique and stable stanza ID.
type ID struct {
XMLName xml.Name `xml:"urn:xmpp:sid:0 stanza-id"`
ID string `xml:"id,attr"`
By jid.JID `xml:"by,attr"`
}
// TokenReader implements xmlstream.Marshaler.
func (id ID) TokenReader() xml.TokenReader {
return xmlstream.Wrap(nil, xml.StartElement{
Name: xml.Name{Space: NSSid, Local: "stanza-id"},
Attr: []xml.Attr{
{Name: xml.Name{Local: "id"}, Value: id.ID},
{Name: xml.Name{Local: "by"}, Value: id.By.String()},
},
})
}
// WriteXML implements xmlstream.WriterTo.
func (id ID) WriteXML(w xmlstream.TokenWriter) (int, error) {
return xmlstream.Copy(w, id.TokenReader())
}
// OriginID is a unique and stable stanza ID generated by an originating entity
// that may want to hide its identity.
type OriginID struct {
XMLName xml.Name `xml:"urn:xmpp:sid:0 origin-id"`
ID string `xml:"id,attr"`
}
// TokenReader implements xmlstream.Marshaler.
func (id OriginID) TokenReader() xml.TokenReader {
return xmlstream.Wrap(nil, xml.StartElement{
Name: xml.Name{Space: NSSid, Local: "origin-id"},
Attr: []xml.Attr{
{Name: xml.Name{Local: "id"}, Value: id.ID},
},
})
}
// WriteXML implements xmlstream.WriterTo.
func (id OriginID) WriteXML(w xmlstream.TokenWriter) (int, error) {
return xmlstream.Copy(w, id.TokenReader())
}
// Is tests whether name is a valid stanza based on the localname and namespace.
func Is(name xml.Name) bool {
return (name.Local == "iq" || name.Local == "message" || name.Local == "presence") &&
(name.Space == ns.Client || name.Space == ns.Server)
}
// AddID returns an transformer that adds a random stanza ID to any stanzas that
// does not already have one.
func AddID(by jid.JID) xmlstream.Transformer {
return xmlstream.InsertFunc(func(start xml.StartElement, level uint64, w xmlstream.TokenWriter) error {
if Is(start.Name) && level == 1 {
_, err := ID{
ID: attr.RandomLen(idLen),
By: by,
}.WriteXML(w)
return err
}
return nil
})
}
var (
addOriginID = xmlstream.InsertFunc(func(start xml.StartElement, level uint64, w xmlstream.TokenWriter) error {
if Is(start.Name) && level == 1 {
_, err := OriginID{
ID: attr.RandomLen(idLen),
}.WriteXML(w)
return err
}
return nil
})
)
// AddOriginID is an xmlstream.Transformer that adds an origin ID to any stanzas
// found in the input stream.
func AddOriginID(r xml.TokenReader) xml.TokenReader {
return addOriginID(r)
}
|
package main
func intsSliceExist(slice []int, value int) bool {
for _, v := range slice {
if v == value {
return true
}
}
return false
}
|
package wineutil
import (
"fmt"
"testing"
"github.com/lukeic/vinogo/config"
"github.com/stretchr/testify/assert"
)
func TestNewApiQuery(t *testing.T) {
expected := fmt.Sprintf("akey=%s", config.GetString("SNOOTH_API_KEY"))
actual := NewAPIQuery().Encode()
assert.Equal(t, expected, actual, "should be equal")
}
// func TestRequestURL(t *testing.T) {
// apiKey := config.GetString("SNOOTH_API_KEY")
//
// expected := fmt.Sprintf("akey=%s", apiKey)
// actual := buildWinesQuery(nil)
// assert.Equal(t, expected, actual, "should return query without params")
//
// expected = fmt.Sprintf("%swines?akey=%s", apiRoot, apiKey)
// actual = requestURL("wines", buildWinesQuery(nil))
// assert.Equal(t, expected, actual, "should return full request URL")
// }
|
package util
import (
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"hash"
"strings"
//shanna.chang start at 2018.10.05
"bytes"
"crypto/cipher"
"crypto/aes"
//shanna.chang end at 2018.10.05
)
// source: https://github.com/gogits/gogs/blob/9ee80e3e5426821f03a4e99fad34418f5c736413/modules/base/tool.go#L58
func GetRandomString(n int, alphabets ...byte) string {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
rand.Read(bytes)
for i, b := range bytes {
if len(alphabets) == 0 {
bytes[i] = alphanum[b%byte(len(alphanum))]
} else {
bytes[i] = alphabets[b%byte(len(alphabets))]
}
}
return string(bytes)
}
func EncodePassword(password string, salt string) string {
newPasswd := PBKDF2([]byte(password), []byte(salt), 10000, 50, sha256.New)
return hex.EncodeToString(newPasswd)
}
// Encode string to md5 hex value.
func EncodeMd5(str string) string {
m := md5.New()
m.Write([]byte(str))
return hex.EncodeToString(m.Sum(nil))
}
// http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
prf := hmac.New(h, password)
hashLen := prf.Size()
numBlocks := (keyLen + hashLen - 1) / hashLen
var buf [4]byte
dk := make([]byte, 0, numBlocks*hashLen)
U := make([]byte, hashLen)
for block := 1; block <= numBlocks; block++ {
// N.B.: || means concatenation, ^ means XOR
// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
// U_1 = PRF(password, salt || uint(i))
prf.Reset()
prf.Write(salt)
buf[0] = byte(block >> 24)
buf[1] = byte(block >> 16)
buf[2] = byte(block >> 8)
buf[3] = byte(block)
prf.Write(buf[:4])
dk = prf.Sum(dk)
T := dk[len(dk)-hashLen:]
copy(U, T)
// U_n = PRF(password, U_(n-1))
for n := 2; n <= iter; n++ {
prf.Reset()
prf.Write(U)
U = U[:0]
U = prf.Sum(U)
for x := range U {
T[x] ^= U[x]
}
}
}
return dk[:keyLen]
}
func GetBasicAuthHeader(user string, password string) string {
var userAndPass = user + ":" + password
return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
}
func DecodeBasicAuthHeader(header string) (string, string, error) {
var code string
parts := strings.SplitN(header, " ", 2)
if len(parts) == 2 && parts[0] == "Basic" {
code = parts[1]
}
decoded, err := base64.StdEncoding.DecodeString(code)
if err != nil {
return "", "", err
}
userAndPass := strings.SplitN(string(decoded), ":", 2)
if len(userAndPass) != 2 {
return "", "", errors.New("Invalid basic auth header")
}
return userAndPass[0], userAndPass[1], nil
}
//shanna.chang start at 2018.10.05
// AES
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext) % blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS7UnPadding(origData)
return origData, nil
}
//shanna.chang end at 2018.10.05
|
package handle
import (
"quadtree"
. "twof"
)
const (
QuadtreeInitSize = 6400
)
type GameMap struct {
Name string
Tree *quadtree.Quadtree
}
var (
// All players and monsters are stored in an Quadtree, to make it quick to find distances.
lowerLeftNearCorner = TwoF{-QuadtreeInitSize, -QuadtreeInitSize}
upperLeftFarCorner = TwoF{QuadtreeInitSize, QuadtreeInitSize}
playerQuadtree = quadtree.MakeQuadtree(lowerLeftNearCorner, upperLeftFarCorner, 1)
MapA = GameMap{"MapA", playerQuadtree} //地图A
)
|
/*
Copyright 2020 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package buildpacks
import (
"fmt"
"path/filepath"
"github.com/buildpacks/pack/pkg/project"
"github.com/buildpacks/pack/pkg/project/types"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/build/misc"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/config"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/latest"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
)
func GetEnv(a *latest.Artifact, mode config.RunMode) (map[string]string, error) {
artifact := a.BuildpackArtifact
workspace := a.Workspace
var projectDescriptor types.Descriptor
path := filepath.Join(workspace, artifact.ProjectDescriptor)
if util.IsFile(path) {
var err error
projectDescriptor, err = project.ReadProjectDescriptor(path)
if err != nil {
return nil, fmt.Errorf("failed to read project descriptor %q: %w", path, err)
}
}
return env(a, mode, projectDescriptor)
}
func env(a *latest.Artifact, mode config.RunMode, projectDescriptor types.Descriptor) (map[string]string, error) {
envVars, err := misc.EvaluateEnv(a.BuildpackArtifact.Env)
if err != nil {
return nil, fmt.Errorf("unable to evaluate env variables: %w", err)
}
if mode == config.RunModes.Dev && a.Sync != nil && a.Sync.Auto != nil && *a.Sync.Auto {
envVars = append(envVars, "GOOGLE_DEVMODE=1")
}
env := envMap(envVars)
for _, kv := range projectDescriptor.Build.Env {
env[kv.Name] = kv.Value
}
env = addDefaultArgs(mode, env)
return env, nil
}
|
// Copyright (c) 2018-present, MultiVAC Foundation.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package vrf
import "io"
// PublicKey defines to be public key data structure of MultiVAC account.
type PublicKey []byte
// PrivateKey defines to be private key data structure of MultiVAC account.
type PrivateKey []byte
// VRF is named Verifiable Random Function.
// See https://en.wikipedia.org/wiki//Verifable_random_function for more info.
//
// This class is overall in charge of all functionalities related to VRF, including generating RNG, verification, etc.
//
// VRF is designed to be a stateless oracle(like how it was originally designed). Caller is responsible for
// rendering the private key.
type VRF interface {
// GenerateKey creates a public/private key pair. rnd is used for randomness.
//
// If rnd is nil, 'crypto/rand' is used.
GenerateKey(rnd io.Reader) (pk PublicKey, sk PrivateKey, err error)
// Generates a proof with given private key and public key.
//
// Note: the public key is not necessary. Just for efficiency.
Generate(pk PublicKey, sk PrivateKey, msg []byte) (proof []byte, err error)
// Verifies the proof is indeed for given message.
//
// Notice that the PublicKey belongs to the broadcaster of the RNG, not the node itself.
VerifyProof(publicKey PublicKey, pf []byte, msg []byte) (res bool, err error)
// Renders hash from proof.
ProofToHash(pf []byte) []byte
// TODO Clean up the API and update test for this.
// Generates hash and its proof
VRF(pk PublicKey, sk PrivateKey, msg []byte) (hash []byte, proof []byte, err error)
}
|
package terminal
import (
"fmt"
"io"
"time"
"github.com/loft-sh/devspace/pkg/devspace/kubectl/selector"
"github.com/loft-sh/devspace/pkg/devspace/config/versions/latest"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/kubectl"
"github.com/loft-sh/devspace/pkg/devspace/services/targetselector"
interruptpkg "github.com/loft-sh/devspace/pkg/util/interrupt"
"github.com/loft-sh/devspace/pkg/util/log"
"github.com/loft-sh/devspace/pkg/util/tomb"
"github.com/mgutz/ansi"
"github.com/sirupsen/logrus"
kubectlExec "k8s.io/client-go/util/exec"
"k8s.io/kubectl/pkg/util/term"
)
// StartTerminalFromCMD opens a new terminal
func StartTerminalFromCMD(
ctx devspacecontext.Context,
selector targetselector.TargetSelector,
command []string,
wait,
restart,
tty,
screen bool,
screenSession string,
stdout io.Writer,
stderr io.Writer,
stdin io.Reader,
) (int, error) {
container, err := selector.SelectSingleContainer(ctx.Context(), ctx.KubeClient(), ctx.Log())
if err != nil {
return 0, err
}
ctx.Log().Infof("Opening shell to pod:container %s:%s", ansi.Color(container.Pod.Name, "white+b"), ansi.Color(container.Container.Name, "white+b"))
done := make(chan error)
go func() {
done <- startTerminal(ctx, command, tty, !screen, screenSession, stdout, stderr, stdin, container)
}()
// wait until either client has finished or we got interrupted
select {
case <-ctx.Context().Done():
<-done
return 0, nil
case err = <-done:
if err != nil {
if exitError, ok := err.(kubectlExec.CodeExitError); ok {
// Expected exit codes are (https://shapeshed.com/unix-exit-codes/):
// 1 - Catchall for general errors
// 2 - Misuse of shell builtins (according to Bash documentation)
// 126 - Command invoked cannot execute
// 127 - “command not found”
// 128 - Invalid argument to exit
// 130 - Script terminated by Control-C
if restart && IsUnexpectedExitCode(exitError.Code) {
ctx.Log().WriteString(logrus.InfoLevel, "\n")
ctx.Log().Infof("Restarting because: %s", err)
return StartTerminalFromCMD(ctx, selector, command, wait, restart, tty, screen, screenSession, stdout, stderr, stdin)
}
return exitError.Code, nil
} else if restart {
ctx.Log().WriteString(logrus.InfoLevel, "\n")
ctx.Log().Infof("Restarting because: %s", err)
return StartTerminalFromCMD(ctx, selector, command, wait, restart, tty, screen, screenSession, stdout, stderr, stdin)
}
return 0, err
}
}
return 0, nil
}
// StartTerminal opens a new terminal
func StartTerminal(
ctx devspacecontext.Context,
devContainer *latest.DevContainer,
selector targetselector.TargetSelector,
stdout io.Writer,
stderr io.Writer,
stdin io.Reader,
parent *tomb.Tomb,
) (err error) {
// restart on error
defer func() {
if err != nil {
if ctx.IsDone() {
return
}
ctx.Log().Infof("Restarting because: %s", err)
select {
case <-ctx.Context().Done():
return
case <-time.After(time.Second * 3):
}
err = StartTerminal(ctx, devContainer, selector, stdout, stderr, stdin, parent)
return
}
ctx.Log().Debugf("Stopped terminal")
}()
command := getCommand(devContainer)
container, err := selector.WithContainer(devContainer.Container).SelectSingleContainer(ctx.Context(), ctx.KubeClient(), ctx.Log())
if err != nil {
return err
}
ctx.Log().Infof("Opening shell to %s:%s (pod:container)", ansi.Color(container.Container.Name, "white+b"), ansi.Color(container.Pod.Name, "white+b"))
errChan := make(chan error)
parent.Go(func() error {
errChan <- startTerminal(ctx, command, !devContainer.Terminal.DisableTTY, devContainer.Terminal.DisableScreen, "dev", stdout, stderr, stdin, container)
return nil
})
select {
case <-ctx.Context().Done():
<-errChan
return nil
case err = <-errChan:
if ctx.IsDone() {
return nil
}
if err != nil {
// check if context is done
if exitError, ok := err.(kubectlExec.CodeExitError); ok {
// Expected exit codes are (https://shapeshed.com/unix-exit-codes/):
// 1 - Catchall for general errors
// 2 - Misuse of shell builtins (according to Bash documentation)
// 126 - Command invoked cannot execute
// 127 - “command not found”
// 128 - Invalid argument to exit
// 130 - Script terminated by Control-C
if IsUnexpectedExitCode(exitError.Code) {
return err
}
return nil
}
return fmt.Errorf("lost connection to pod %s: %v", container.Pod.Name, err)
}
}
return nil
}
func startTerminal(
ctx devspacecontext.Context,
command []string,
tty bool,
disableScreen bool,
screenSession string,
stdout io.Writer,
stderr io.Writer,
stdin io.Reader,
container *selector.SelectedPodContainer,
) error {
interruptpkg.Global.Stop()
defer interruptpkg.Global.Start()
// try to install screen
useScreen := false
if term.IsTerminal(stdin) && !disableScreen {
ctx.Log().Debugf("Installing screen in container...")
bufferStdout, bufferStderr, err := ctx.KubeClient().ExecBuffered(ctx.Context(), container.Pod, container.Container.Name, []string{
"sh",
"-c",
`if ! command -v screen; then
if command -v apk; then
apk add --no-cache screen
elif command -v apt-get; then
apt-get -qq update && apt-get install -y screen && rm -rf /var/lib/apt/lists/*
else
echo "Couldn't install screen using neither apt-get nor apk."
exit 1
fi
fi
if command -v screen; then
echo "Screen installed successfully."
if [ ! -f ~/.screenrc ]; then
echo "termcapinfo xterm* ti@:te@" > ~/.screenrc
echo "logfile /tmp/terminal-log.0" >> ~/.screenrc
echo "escape ^tt" >> ~/.screenrc
fi
else
echo "Couldn't find screen, need to fallback."
exit 1
fi`,
}, nil)
if err != nil {
ctx.Log().Debugf("Error installing screen: %s %s %v", string(bufferStdout), string(bufferStderr), err)
} else {
useScreen = true
}
}
if useScreen {
newCommand := []string{"screen", "-dRSqL", screenSession, "--"}
newCommand = append(newCommand, command...)
command = newCommand
}
ctx.Log().Debugf("Starting terminal...")
before := log.GetBaseInstance().GetLevel()
log.GetBaseInstance().SetLevel(logrus.PanicLevel)
err := ctx.KubeClient().ExecStream(ctx.Context(), &kubectl.ExecStreamOptions{
Pod: container.Pod,
Container: container.Container.Name,
Command: command,
TTY: tty,
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
SubResource: kubectl.SubResourceExec,
})
log.GetBaseInstance().SetLevel(before)
if err != nil {
ctx.Log().Debugf("error executing stream: %v", err)
}
return err
}
func IsUnexpectedExitCode(code int) bool {
// Expected exit codes are (https://shapeshed.com/unix-exit-codes/):
// 1 - Catchall for general errors
// 2 - Misuse of shell builtins (according to Bash documentation)
// 126 - Command invoked cannot execute
// 127 - “command not found”
// 128 - Invalid argument to exit
// 130 - Script terminated by Control-C
return code != 0 && code != 1 && code != 2 && code != 126 && code != 127 && code != 128 && code != 130
}
func getCommand(devContainer *latest.DevContainer) []string {
command := devContainer.Terminal.Command
if command == "" {
command = "command -v bash >/dev/null 2>&1 && exec bash || exec sh"
}
if devContainer.Terminal.WorkDir != "" {
return []string{"sh", "-c", fmt.Sprintf("cd %s; %s", devContainer.Terminal.WorkDir, command)}
}
return []string{"sh", "-c", command}
}
|
// Copyright 2018 The gVisor 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 serialization_test
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"testing"
"google.golang.org/protobuf/proto"
"gvisor.dev/gvisor/runsc/container"
"gvisor.dev/gvisor/runsc/sandbox"
)
// ignoreList is a list of field names that are ignored from the
// serializability check in this file.
// No gVisor-related field named should be here; instead, you can tag
// fields that are meant to be unserializable with `nojson:"true"`.
var ignoreList = map[string]struct{}{
// Part of the OCI runtime spec, it uses an `interface{}` type which it
// promises is JSON-serializable in the comments.
"Container.Spec.Windows.CredentialSpec": struct{}{},
}
// implementsSerializableInterface returns true if the given type implements
// an interface which inherently provides serialization.
func implementsSerializableInterface(typ reflect.Type) bool {
jsonMarshaler := reflect.TypeOf((*json.Marshaler)(nil)).Elem()
jsonUnmarshaler := reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
if typ.Implements(jsonMarshaler) && typ.Implements(jsonUnmarshaler) {
return true
}
protoMessage := reflect.TypeOf((*proto.Message)(nil)).Elem()
if typ.Implements(protoMessage) {
return true
}
return false
}
// checkSerializable verifies that the given type is serializable.
func checkSerializable(typ reflect.Type, fieldName []string) error {
if implementsSerializableInterface(typ) || implementsSerializableInterface(reflect.PointerTo(typ)) {
return nil
}
field := func(s string) []string {
return append(append(([]string)(nil), fieldName...), s)
}
fieldPath := strings.Join(fieldName, ".")
if _, ignored := ignoreList[fieldPath]; ignored {
return nil
}
switch typ.Kind() {
case reflect.Bool:
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return nil
case reflect.Float32, reflect.Float64:
return nil
case reflect.Complex64, reflect.Complex128:
return nil
case reflect.String:
return nil
case reflect.UnsafePointer:
return fmt.Errorf("unsafe pointer %q not allowed in serializable struct", fieldPath)
case reflect.Chan:
return fmt.Errorf("channel %q not allowed in serializable struct", fieldPath)
case reflect.Func:
return fmt.Errorf("function %q not allowed in serializable struct", fieldPath)
case reflect.Interface:
return fmt.Errorf("interface %q not allowed in serializable struct", fieldPath)
case reflect.Array:
return fmt.Errorf("fixed-size array %q not allowed in serializable struct (use a slice instead)", fieldPath)
case reflect.Slice:
return checkSerializable(typ.Elem(), field("[]"))
case reflect.Map:
// We only allow a small subset of types as valid map key type.
switch typ.Key().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
case reflect.String:
default:
return fmt.Errorf("map key type %v of %q not allowed", typ.Key().Kind(), fieldPath)
}
// But all the value types are allowed.
return checkSerializable(typ.Elem(), field("{}"))
case reflect.Struct:
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if _, noJSON := f.Tag.Lookup("nojson"); noJSON {
if f.IsExported() {
return fmt.Errorf("struct field %q must not be exported since it is marked `nojson:\"true\"` in a serializable struct", strings.Join(field(f.Name), "."))
}
continue
}
if !f.IsExported() {
return fmt.Errorf("struct field %q must be exported or marked `nojson:\"true\"` since it is in a serializable struct", strings.Join(field(f.Name), "."))
}
if err := checkSerializable(f.Type, field(f.Name)); err != nil {
return err
}
}
return nil
case reflect.Pointer:
return checkSerializable(typ.Elem(), fieldName)
default:
return fmt.Errorf("unknown field type %v for %q", typ, fieldPath)
}
}
// TestSerialization verifies that the Container struct only contains
// serializable fields.
func TestSerializable(t *testing.T) {
for _, test := range []struct {
name string
obj any
}{
{"Sandbox", sandbox.Sandbox{}},
{"Container", container.Container{}},
} {
t.Run(test.name, func(t *testing.T) {
if err := checkSerializable(reflect.TypeOf(test.obj), []string{test.name}); err != nil {
t.Errorf("struct %v must be serializable: %v", test.name, err)
}
})
}
}
|
package main
import (
"./lib"
"./run"
"fmt"
"os"
"path"
"strings"
)
func main() {
config,err:= lib.GetConfig()
if err != nil {
fmt.Printf(err.Error())
}
dir, _ := os.Getwd()
sourceFolderPath:=path.Join(dir,fmt.Sprintf("%s/%s/source",config.OutPath,getVideoName(config)))
mp3Path:=fmt.Sprintf("%s/%s_%s.mp3",sourceFolderPath,getVideoName(config),config.Mp3Bit)
pngFolderPath:=fmt.Sprintf("%s/%s_w%d_h%d_f%d",sourceFolderPath,getVideoName(config),config.SourceWidth,config.SourceHeight,config.SourceFrame)
binFolderPath:=strings.Replace(sourceFolderPath,"source",fmt.Sprintf("w%d_h%d_f%d_s%d/bin",config.OutWidth,config.OutHeight,config.OutFrame,config.ColorSize),1)
//reBinFolderPath:=strings.Replace(sourceFolderPath,"source",fmt.Sprintf("w%d_h%d_f%d_s%d/rebin",config.OutWidth,config.OutHeight,config.OutFrame,config.ColorSize),1)
//gipFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("gip/br%d_bc%d",config.MaxBRowNum,config.MaxBColumnNum),1)
//gppFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("gpp/br%d_bc%d",config.MaxBRowNum,config.MaxBColumnNum),1)
//gbpFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("gbp/br%d_bc%d_bg%d",config.MaxBRowNum,config.MaxBColumnNum,config.MaxBPageNum),1)
gvFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("gv/br%d_bc%d_bg%d_gv%d",config.MaxBRowNum,config.MaxBColumnNum,config.MaxBPageNum,config.GvSeconds),1)
//zipFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("zip/bpo%d_bpg%d_gv%d_zip%d_mp3%s",config.BPointNum,config.BPageNum,config.GvSeconds,config.ZipSeconds,config.Mp3Bit),1)
//configFolderPath:=strings.Replace(binFolderPath,"bin",fmt.Sprintf("config/br%d_bc%d_bg%d_gv%d",config.MaxBRowNum,config.MaxBColumnNum,config.MaxBPageNum,config.GvSeconds),1)
err=run.VideoToSource(sourceFolderPath,mp3Path,pngFolderPath,config)
if err != nil {
fmt.Printf(err.Error())
}
err=run.PngToBin(pngFolderPath,binFolderPath,config)
if err != nil {
fmt.Printf(err.Error())
}
//err=run.BinToGip(binFolderPath,gipFolderPath,reBinFolderPath,config)
//if err != nil {
// fmt.Printf(err.Error())
//}
//err=run.BinToGbp(binFolderPath,gbpFolderPath,reBinFolderPath,config)
//if err != nil {
// fmt.Printf(err.Error())
//}
err=run.BinToGv(binFolderPath,gvFolderPath,config)
if err != nil {
fmt.Printf(err.Error())
}
//err=run.GvToZip(gvFolderPath,zipFolderPath,config)
//if err != nil {
// fmt.Printf(err.Error())
//}
fmt.Println("run success!")
}
func getVideoName(config *lib.ConfigInfo) string {
arr1 :=strings.Split(config.VideoPath, "/")
arr2 :=strings.Split(arr1[len(arr1)-1],".")
return arr2[0]
}
|
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func CheckError(err error, message string) {
if err != nil {
panic(fmt.Sprintf("Error : %v", message))
}
}
func SetupDatabase() *gorm.DB {
db, err := gorm.Open(config.Get("database"), config.Get("databaseURL"))
CheckError(err, "Unable to open database")
db.DB()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.SingularTable(true)
db.AutoMigrate(Photo{})
db.LogMode(true)
// db.Model(Photo{}).AddUniqueIndex("idx_media_path", "path")
// db.Model(Photo{}).AddUniqueIndex("idx_media_hash", "md5hash")
return &db
}
|
package mutator
import (
"fmt"
"net/http"
"github.com/golang/glog"
"github.com/gorilla/mux"
"k8s.io/api/extensions/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
platform "kolihub.io/koli/pkg/apis/core/v1alpha1"
"kolihub.io/koli/pkg/apis/core/v1alpha1/draft"
"kolihub.io/koli/pkg/util"
)
func (h *Handler) IngressOnCreate(w http.ResponseWriter, r *http.Request) {
namespace := mux.Vars(r)["namespace"]
key := fmt.Sprintf("Req-ID=%s, Resource=ingress:%s", r.Header.Get("X-Request-ID"), namespace)
glog.V(3).Infof("%s, User-Agent=%s, Method=%s", key, r.Header.Get("User-Agent"), r.Method)
new := draft.NewIngress(&v1beta1.Ingress{})
if err := util.NewDecoder(r.Body, extensionsCodec).Decode(new); err != nil {
msg := fmt.Sprintf("failed decoding request body [%v]", err)
glog.V(3).Infof("%s - %s", key, msg)
util.WriteResponseError(w, util.StatusInternalError(msg, nil))
return
}
defer r.Body.Close()
if len(new.Spec.Rules) > 1 {
msg := fmt.Sprintf(`spec.rules cannot have more than one host, found %d rules`, len(new.Spec.Rules))
glog.V(3).Infof("%s - %s", key, msg)
details := &metav1.StatusDetails{
Name: new.Name,
Group: new.GroupVersionKind().Group,
Causes: []metav1.StatusCause{{
Type: metav1.CauseTypeFieldValueInvalid,
Message: msg,
Field: fmt.Sprintf(`spec.rules[%d].host`, len(new.Spec.Rules)),
}},
}
util.WriteResponseError(w, util.StatusConflict(msg, new, details))
return
}
// for now, only care for .spec.rules.http
new.Spec.Backend = nil
new.Spec.TLS = []v1beta1.IngressTLS{}
// validate if the services exists before creating it
for _, r := range new.Spec.Rules {
if r.HTTP == nil {
continue
}
for _, p := range r.HTTP.Paths {
if errStatus := h.validateService(new, &p.Backend); errStatus != nil {
glog.V(3).Infof("%s - %s", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
}
}
resp, err := h.clientset.Extensions().Ingresses(namespace).Create(new.GetObject())
switch e := err.(type) {
case *apierrors.StatusError:
glog.Infof("%s:%s - failed creating ingress [%s]", key, new.Name, e.ErrStatus.Reason)
util.WriteResponseError(w, &e.ErrStatus)
case nil:
obj, err := runtime.Encode(extensionsCodec, resp)
if err != nil {
msg := fmt.Sprintf("request was mutated but failed encoding response [%v]", err)
glog.Infof("%s:%s - %s", key, new.Name, msg)
util.WriteResponseError(w, util.StatusInternalError(msg, new))
return
}
glog.Infof("%s:%s - request mutate with success", key, new.Name)
util.WriteResponseCreated(w, obj)
default:
msg := fmt.Sprintf("unknown response from server [%v, %#v]", err, resp)
glog.Warningf("%s:%s - %s", key, new.Name, msg)
util.WriteResponseError(w, util.StatusInternalError(msg, new))
return
}
}
func (h *Handler) IngressOnPatch(w http.ResponseWriter, r *http.Request) {
if r.Method != "PATCH" {
msg := fmt.Sprintf(`Method "%s" not allowed.`, r.Method)
util.WriteResponseError(w, util.StatusMethodNotAllowed(msg, nil))
return
}
params := mux.Vars(r)
namespace, ingressName := params["namespace"], params["name"]
key := fmt.Sprintf("Req-ID=%s, Resource=ingress:%s/%s", r.Header.Get("X-Request-ID"), namespace, ingressName)
glog.V(3).Infof("%s, User-Agent=%s, Method=%s", key, r.Header.Get("User-Agent"), r.Method)
old, errStatus := h.getIngress(namespace, ingressName)
if errStatus != nil {
glog.V(4).Infof("%s - failed retrieving ingress [%s]", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
new, err := old.Copy()
if err != nil {
msg := fmt.Sprintf("failed deep copying obj [%v]", err)
glog.V(3).Infof("%s - %s", key, err)
util.WriteResponseError(w, util.StatusInternalError(msg, nil))
return
}
if err := util.NewDecoder(r.Body, extensionsCodec).Decode(new); err != nil {
msg := fmt.Sprintf("failed decoding request body [%v]", err)
glog.V(3).Infof("%s - %s", key, err)
util.WriteResponseError(w, util.StatusInternalError(msg, nil))
return
}
oldParent := old.GetAnnotation("kolihub.io/parent")
if oldParent.Exists() {
new.SetAnnotation("kolihub.io/parent", oldParent.String())
}
// kolihub.io/domain.tld keys are immutable
for key, value := range old.DomainPrimaryKeys() {
new.SetAnnotation(key, value)
}
// for now, we only care for .spec.rules.http
new.Spec.Backend = old.Spec.Backend
new.Spec.TLS = old.Spec.TLS
if len(new.Spec.Rules) > 1 {
msg := fmt.Sprintf("spec.rules cannot have more than one host, found %d rules", len(new.Spec.Rules))
util.WriteResponseError(w, ruleConstraintError(new.GetObject(), msg))
return
}
if len(old.Spec.Rules) == 1 && len(new.Spec.Rules) <= 0 {
util.WriteResponseError(w, ruleConstraintError(new.GetObject(), "spec.rules cannot be removed"))
return
}
newIngressPaths := map[string]*v1beta1.HTTPIngressPath{}
for _, r := range new.Spec.Rules {
if len(old.Spec.Rules) == 1 && r.Host != old.Spec.Rules[0].Host {
msg := fmt.Sprintf(`cannot change host, from "%s" to "%s"`, old.Spec.Rules[0].Host, r.Host)
util.WriteResponseError(w, changeHostConstraintError(new.GetObject(), msg))
return
}
for _, p := range r.HTTP.Paths {
newIngressPaths[p.Path] = &p
}
}
// Try to identify for additions, ensure that the service exists and it's valid
for newPath, httpIngressPath := range newIngressPaths {
exists := false
for _, r := range old.Spec.Rules {
for _, p := range r.HTTP.Paths {
if p.Path == newPath {
exists = true
break
}
}
}
if !exists {
// The new path doesn't exists in the old resource, means
// it's being added, validate if the service exists before proceed
if errStatus := h.validateService(new, &httpIngressPath.Backend); errStatus != nil {
glog.V(3).Infof("%s - %s", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
}
}
// Try to identify if a path was edited or deleted from the new resource
for _, r := range old.Spec.Rules {
for _, p := range r.HTTP.Paths {
if _, ok := newIngressPaths[p.Path]; !ok {
// An empty path or root one (/) has no distinction in Kong.
// Normalize the path otherwise it will generate a distinct adler hash
pathURI := p.Path
if pathURI == "/" || pathURI == "" {
pathURI = "/"
}
// The path doesn't exists anymore, means it was removed or
// edited to a new path value, in this stage is safe to delete the kong route
if errStatus := h.deleteKongRoute(r.Host, new.Namespace, util.GenAdler32Hash(pathURI)); errStatus != nil {
glog.V(3).Infof("%s - %s", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
}
}
}
// Remove empty keys from map[string]string, it's required because
// a strategic merge is decoded to an object and every directive is lost.
// A directive for removing a key from a map[string]string is converted to
// []byte(`{"metadata": {"labels": "key": ""}}`) and these are not removed
// when reapplying a merge patch.
util.DeleteNullKeysFromObjectMeta(&new.ObjectMeta)
patch, err := util.StrategicMergePatch(extensionsCodec, old.GetObject(), new.GetObject())
if err != nil {
msg := fmt.Sprintf("failed merging patch data [%v]", err)
glog.V(3).Infof("%s - %s", key, err)
util.WriteResponseError(w, util.StatusInternalError(msg, nil))
return
}
glog.V(4).Infof("%s, DIFF: %s", key, string(patch))
resp, err := h.clientset.Extensions().Ingresses(namespace).Patch(ingressName, types.StrategicMergePatchType, patch)
switch e := err.(type) {
case *apierrors.StatusError:
glog.Infof("%s - failed updating ingress [%s]", key, e.ErrStatus.Reason)
util.WriteResponseError(w, &e.ErrStatus)
case nil:
data, err := runtime.Encode(extensionsCodec, resp)
if err != nil {
msg := fmt.Sprintf("failed encoding response [%v]", err)
util.WriteResponseError(w, util.StatusInternalError(msg, resp))
return
}
glog.Infof("%s - request mutate with success", key)
util.WriteResponseSuccess(w, data)
default:
msg := fmt.Sprintf("unknown response from server [%v, %#v]", err, resp)
glog.Warningf("%s - %s", key, msg)
util.WriteResponseError(w, util.StatusInternalError(msg, resp))
return
}
}
func (h *Handler) IngressOnDelete(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
namespace, ingressName := params["namespace"], params["name"]
key := fmt.Sprintf("Req-ID=%s, Resource=ingress:%s/%s", r.Header.Get("X-Request-ID"), namespace, ingressName)
glog.V(3).Infof("%s, User-Agent=%s, Method=%s", key, r.Header.Get("User-Agent"), r.Method)
ing, errStatus := h.getIngress(namespace, ingressName)
if errStatus != nil {
glog.V(4).Infof("%s - failed retrieving ingress [%s]", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
// It's insecure delete domains crossing namespaces, delete
// resources in the same namespace only
if len(ing.Spec.Rules) >= 1 {
domainName := ing.Spec.Rules[0].Host
dom, errStatus := h.searchPrimaryDomainByNamespace(domainName, namespace)
if errStatus != nil {
glog.Infof("%s - %s", key, errStatus.Message)
util.WriteResponseError(w, errStatus)
return
}
if dom != nil {
glog.V(3).Infof("%s - found domain resource %#v for %s", key, dom.Name, domainName)
_, err := h.tprClient.Delete().
Resource("domains").
Namespace(namespace).
Name(dom.Name).
DoRaw()
if err != nil {
msg := fmt.Sprintf("failed removing domain %#v [%v]", dom.Name, err)
util.WriteResponseError(w, util.StatusBadRequest(msg, nil, metav1.StatusReasonBadRequest))
return
}
glog.V(4).Infof("%s - domain %#v deleted successfully", key, dom.Name)
} else {
glog.V(3).Infof("%s - domain %#v not found", key, domainName)
}
}
err := h.clientset.Extensions().Ingresses(namespace).Delete(ing.Name, &metav1.DeleteOptions{})
switch e := err.(type) {
case *apierrors.StatusError:
glog.Infof("%s - failed mutating request [%v]", key, err)
util.WriteResponseError(w, &e.ErrStatus)
case nil:
glog.Infof("%s - request mutate with success!", key)
util.WriteResponseNoContent(w)
default:
msg := fmt.Sprintf("unknown response [%v]", err)
glog.Infof("%s - %s", key, msg)
util.WriteResponseError(w, util.StatusInternalError(msg, nil))
}
}
func (h *Handler) deleteKongRoute(host, ns, encodedPath string) *metav1.Status {
apiName := fmt.Sprintf("%s~%s~%s", host, ns, encodedPath)
glog.V(4).Infof(`removing kong route "%s"`, apiName)
res := h.kongClient.Delete().
Resource("apis").
Name(apiName).
Do()
if res.StatusCode() == http.StatusNotFound {
glog.V(3).Infof(`kong api "%s" doesn't exists`, apiName)
return nil
}
if err := res.Error(); err != nil {
return util.StatusBadRequest(fmt.Sprintf("failed removing kong route [%v]", err), nil, metav1.StatusReasonBadRequest)
}
return nil
}
func (h *Handler) validateService(ing *draft.Ingress, b *v1beta1.IngressBackend) *metav1.Status {
glog.V(4).Infof(`validating service [%#v]`, b)
svc, err := h.clientset.Core().Services(ing.Namespace).Get(b.ServiceName, metav1.GetOptions{})
if err != nil {
return util.StatusBadRequest(fmt.Sprintf("failed retrieving service [%v]", err), nil, metav1.StatusReasonBadRequest)
}
portExists := false
for _, port := range svc.Spec.Ports {
if port.Port == b.ServicePort.IntVal {
portExists = true
break
}
}
if !portExists {
msg := fmt.Sprintf(`the service port "%d" doesn't exists in service "%s", found: %#v`, b.ServicePort.IntVal, svc.Name, svc.Spec.Ports)
return ingressContraintError(ing.GetObject(), msg, "spec.rules[0].http[?].paths[?].backend.servicePort", metav1.CauseTypeFieldValueInvalid)
}
return nil
}
func (h *Handler) getIngress(namespace, ingName string) (*draft.Ingress, *metav1.Status) {
ing, err := h.clientset.Extensions().Ingresses(namespace).Get(ingName, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
msg := fmt.Sprintf(`ingress "%s" not found`, ingName)
return nil, util.StatusNotFound(msg, nil)
}
msg := fmt.Sprintf("failed retrieving ingress [%v]", err)
return nil, util.StatusBadRequest(msg, nil, metav1.StatusReasonBadRequest)
}
return draft.NewIngress(ing), nil
}
func (h *Handler) searchPrimaryDomainByNamespace(domainName, namespace string) (obj *platform.Domain, status *metav1.Status) {
domList := &platform.DomainList{}
err := h.tprClient.Get().
Resource("domains").
Namespace(namespace).
Do().
Into(domList)
if err != nil {
msg := fmt.Sprintf("failed retrieving domain list [%v]", err)
return obj, util.StatusBadRequest(msg, nil, metav1.StatusReasonUnknown)
}
for _, d := range domList.Items {
if !d.IsPrimary() {
continue
}
if d.Spec.PrimaryDomain == domainName {
obj = &d
break
}
}
return
}
func ruleConstraintError(ing *v1beta1.Ingress, msg string) *metav1.Status {
field := fmt.Sprintf("spec.rules[%d].host", len(ing.Spec.Rules))
return ingressContraintError(ing, msg, field, metav1.CauseTypeFieldValueInvalid)
}
func changeHostConstraintError(ing *v1beta1.Ingress, msg string) *metav1.Status {
return ingressContraintError(ing, msg, "spec.rules[0].host", metav1.CauseTypeFieldValueNotSupported)
}
func ingressContraintError(ing *v1beta1.Ingress, msg, field string, cause metav1.CauseType) *metav1.Status {
details := &metav1.StatusDetails{
Name: ing.Name,
Group: ing.GroupVersionKind().Group,
Causes: []metav1.StatusCause{{
Type: cause,
Message: msg,
Field: field,
}},
}
return util.StatusUnprocessableEntity(msg, ing, details)
}
|
/**
深度优先遍历
通过邻接表构建逆邻接表
即s->t的关系是,s依赖于t,
t优先于s执行
*/
package topology
import (
"fmt"
"github.com/kakiezhang/Algo/geekTime/graph"
)
func topoByDfs(g *graph.Graph) {
invert_g := graph.NewGraph(g.Max) // 逆邻接表
for i := 1; i < g.Max; i++ {
if g.Vtx[i] == nil {
continue
}
for j := 0; j < g.Vtx[i].Size(); j++ {
node := g.Vtx[i].Get(j)
if node == nil {
continue
}
k := node.GetData().(*graph.Vertex).GetData().(int)
invert_g.AddOneEdge(k, i, 0)
}
}
visited := make([]bool, g.Max)
for i := 1; i < g.Max; i++ {
if !visited[i] {
visited[i] = true
printDfs(invert_g, i, visited)
}
}
}
func printDfs(invert_g *graph.Graph, i int, visited []bool) {
invert_l := invert_g.Vtx[i]
if invert_l == nil {
fmt.Printf("-> %d ", i)
return
}
for j := 0; j < invert_l.Size(); j++ {
node := invert_l.Get(j)
if node == nil {
continue
}
k := node.GetData().(*graph.Vertex).GetData().(int)
if visited[k] {
continue
}
visited[k] = true
printDfs(invert_g, k, visited)
}
fmt.Printf("-> %d ", i)
}
|
package backend
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"time"
gocontext "context"
"github.com/travis-ci/worker/config"
)
var (
errNoScriptUploaded = fmt.Errorf("no script uploaded")
localHelp = map[string]string{
"SCRIPTS_DIR": "directory where generated scripts will be written",
}
)
func init() {
Register("local", "Local", localHelp, newLocalProvider)
}
type localProvider struct {
cfg *config.ProviderConfig
scriptsDir string
}
func newLocalProvider(cfg *config.ProviderConfig) (Provider, error) {
scriptsDir, _ := os.Getwd()
if cfg.IsSet("SCRIPTS_DIR") {
scriptsDir = cfg.Get("SCRIPTS_DIR")
}
if scriptsDir == "" {
scriptsDir = os.TempDir()
}
return &localProvider{cfg: cfg, scriptsDir: scriptsDir}, nil
}
func (p *localProvider) SupportsProgress() bool {
return false
}
func (p *localProvider) StartWithProgress(ctx gocontext.Context, startAttributes *StartAttributes, _ Progresser) (Instance, error) {
return p.Start(ctx, startAttributes)
}
func (p *localProvider) Start(ctx gocontext.Context, startAttributes *StartAttributes) (Instance, error) {
return newLocalInstance(p)
}
func (p *localProvider) Setup(ctx gocontext.Context) error { return nil }
type localInstance struct {
p *localProvider
scriptPath string
}
func newLocalInstance(p *localProvider) (*localInstance, error) {
return &localInstance{
p: p,
}, nil
}
func (i *localInstance) Warmed() bool {
return false
}
func (i *localInstance) SupportsProgress() bool {
return false
}
func (i *localInstance) UploadScript(ctx gocontext.Context, script []byte) error {
scriptPath := filepath.Join(i.p.scriptsDir, fmt.Sprintf("build-%v.sh", time.Now().UTC().UnixNano()))
f, err := os.Create(scriptPath)
if err != nil {
return err
}
i.scriptPath = scriptPath
scriptBuf := bytes.NewBuffer(script)
_, err = io.Copy(f, scriptBuf)
return err
}
func (i *localInstance) RunScript(ctx gocontext.Context, writer io.Writer) (*RunResult, error) {
if i.scriptPath == "" {
return &RunResult{Completed: false}, errNoScriptUploaded
}
cmd := exec.Command("bash", i.scriptPath)
cmd.Stdout = writer
cmd.Stderr = writer
err := cmd.Start()
if err != nil {
return &RunResult{Completed: false}, err
}
errChan := make(chan error)
go func() {
errChan <- cmd.Wait()
}()
select {
case err := <-errChan:
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
case <-ctx.Done():
err = ctx.Err()
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
}
}
func (i *localInstance) DownloadTrace(ctx gocontext.Context) ([]byte, error) {
return nil, ErrDownloadTraceNotImplemented
}
func (i *localInstance) Stop(ctx gocontext.Context) error {
return nil
}
func (i *localInstance) ID() string {
return fmt.Sprintf("local:%s", i.scriptPath)
}
func (i *localInstance) ImageName() string {
return ""
}
func (i *localInstance) StartupDuration() time.Duration { return zeroDuration }
|
// Copyright 2017 Inca Roads LLC. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"github.com/blues/note-go/notehub"
"github.com/blues/note-go/noteutil"
"io"
"io/ioutil"
"net/http"
"strings"
)
// Add an arg to an URL query string
func addQuery(in string, key string, value string) (out string) {
out = in
if value != "" {
if out == "" {
out += "?"
} else {
out += "&"
}
out += key
out += "=\""
out += value
out += "\""
}
return
}
// Perform an HTTP requet, but do so using structs rather than bytes
func reqHub(hub string, request notehub.HubRequest, requestFile string, filetype string, overwrite bool, secure bool, dropNonJSON bool, outq chan string) (response notehub.HubRequest, err error) {
reqJSON, err2 := json.Marshal(request)
if err2 != nil {
err = err2
return
}
rspJSON, err2 := reqHubJSON(hub, reqJSON, requestFile, filetype, overwrite, secure, dropNonJSON, outq)
if err2 != nil {
err = err2
return
}
err = json.Unmarshal(rspJSON, &response)
return
}
// Perform an HTTP request
func reqHubJSON(hub string, request []byte, requestFile string, filetype string, overwrite bool, secure bool, dropNonJSON bool, outq chan string) (response []byte, err error) {
scheme := "http"
if secure {
scheme = "https"
}
fn := ""
path := strings.Split(requestFile, "/")
if len(path) > 0 {
fn = path[len(path)-1]
}
url := fmt.Sprintf("%s://%s%s", scheme, hub, notehub.DefaultAPITopicReq)
query := addQuery("", "app", noteutil.Config.App)
query = addQuery(query, "device", noteutil.Config.Device)
query = addQuery(query, "upload", fn)
if overwrite {
query = addQuery(query, "overwrite", "true")
}
if filetype != "" {
query = addQuery(query, "type", filetype)
}
url += query
var fileContents []byte
var fileLength int
buffer := bytes.NewBuffer(request)
if requestFile != "" {
fileContents, err = ioutil.ReadFile(requestFile)
if err != nil {
return
}
fileLength = len(fileContents)
buffer = bytes.NewBuffer(fileContents)
}
httpReq, err := http.NewRequest("POST", url, buffer)
if err != nil {
return
}
httpReq.Header.Set("User-Agent", "notehub-client")
if requestFile != "" {
httpReq.Header.Set("Content-Length", fmt.Sprintf("%d", fileLength))
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
httpReq.Header.Set("Content-Type", "application/json")
}
httpClient := &http.Client{}
if secure {
if noteutil.Config.Cert == "" || noteutil.Config.Key == "" {
err = fmt.Errorf("HTTPS client cert (-cert) and key (-key) are required for secure API access")
return
}
clientCert, err2 := tls.LoadX509KeyPair(noteutil.Config.Cert, noteutil.Config.Key)
if err2 != nil {
err = err2
return
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{clientCert},
InsecureSkipVerify: true,
}
if noteutil.Config.Root != "" {
caCert, err2 := ioutil.ReadFile(noteutil.Config.Root)
if err2 != nil {
err = err2
return
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{clientCert},
RootCAs: caCertPool,
}
}
tlsConfig.BuildNameToCertificate()
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
httpClient = &http.Client{
Transport: transport,
}
}
httpRsp, err2 := httpClient.Do(httpReq)
if err2 != nil {
err = err2
return
}
// Note that we must do this with no timeout specified on
// the httpClient, else monitor mode would time out.
b := make([]byte, 2048)
linebuf := []byte{}
for {
n, err2 := httpRsp.Body.Read(b)
if n > 0 {
// Append to result buffer if no outq is specified
if outq == nil {
response = append(response, b[:n]...)
} else {
// Enqueue lines for monitoring
linebuf = append(linebuf, b[:n]...)
for {
// Parse out a full line and queue it, saving the leftover
i := bytes.IndexRune(linebuf, '\n')
if i == -1 {
break
}
line := linebuf[0 : i+1]
linebuf = linebuf[i+1:]
if !dropNonJSON {
outq <- string(line)
} else {
if strings.HasPrefix(string(line), "{") {
outq <- string(line)
}
}
// Remember the very last line as the response, in case it
// was an error and we're about to get an io.EOF
response = line
}
}
}
if err2 != nil {
if err2 != io.EOF {
err = err2
return
}
break
}
}
return
}
|
package source
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
// GoDaddyConfig holds the configuration for the namecheap.com source
type GoDaddyConfig struct {
Key string
Secret string
Enabled bool
}
type goDaddyResponse struct {
Available bool
Domain string
Definitive bool
Price int
Currency string
Period int
Message string
Code string
Name string
}
// GoDaddy handles godaddy.com API requests
type GoDaddy struct {
Source
config *GoDaddyConfig
}
// NewGoDaddy returns a new GoDaddy instance
func NewGoDaddy(config *GoDaddyConfig) Source {
gd := new(GoDaddy)
gd.config = config
return gd
}
// IsAvailable checks if a domain is available
func (gd *GoDaddy) IsAvailable(domain string) (bool, error) {
client := &http.Client{}
v := url.Values{}
v.Set("domain", domain)
req, err := http.NewRequest("GET", "https://api.godaddy.com/v1/domains/available?"+v.Encode(), nil)
req.Header.Add("Authorization", fmt.Sprintf("sso-key %s:%s", gd.config.Key, gd.config.Secret))
resp, err := client.Do(req)
if err != nil {
return false, errors.New("Couldn't connect to API")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, errors.New("Couldn't read API response")
}
var gdResponse goDaddyResponse
if err := json.Unmarshal(body, &gdResponse); err != nil {
return false, errors.New("Couldn't parse API response")
}
if gdResponse.Message != "" {
return false, errors.New(gdResponse.Message)
}
return gdResponse.Available, nil
}
|
// Package gate provides manager all the physical nodes and the virtual nodes.
// CRUD operations
// Contact configuration server && Do dynamic configs
package gate
import (
"errors"
"fmt"
"io/ioutil"
"path/filepath"
"sync"
"time"
// third pkgs
log "github.com/cihub/seelog"
// company pkgs
alg "shadow/agent/algorithm"
cnfPkg "shadow/agent/cnf"
"shadow/agent/cs"
"shadow/agent/redis"
)
// ------------------------------------------
// - App cares about keys. CS above:
// - key : {AppName}__Shadow
// - value : {RingName}
// ------------------------------------------
// ------------------------------------------
// - Ring cares about keys. CS above:
// - key : Shadow.Ring.{RingName}
// - value : string({shadow.{RingName}.yaml})
// ------------------------------------------
const (
APP_CARE_KEYS_FORMAT = "%s__Shadow"
APP_CARE_RING_FORMAT = "Shadow.Ring.%s"
)
var (
ErrAccessDenied = errors.New("No access rights.")
ErrNewRing = errors.New("Fatal: during new ring!")
ErrNoRing = errors.New("Fatal: no ring!")
localGate Gate = Gate{
apps: make(map[string]string),
rings: make(map[string]*ring),
}
)
// expose API to higher layer
type GateActions interface {
Locate(appName, key string) (conn redis.Connection, err error)
}
type Gate struct {
apps map[string]string // App_2_RingName
rings map[string]*ring // RingName_2_Ring. RingName_2_nil: when changing...
mu sync.RWMutex
GateActions
}
// One physical ring consists of N redis(with conns-pool) in the deployment diagram.
type ring struct {
// physical redis connections. Address_2_Pool
pools map[string]*redis.Pool
// ketama algorithm. include basic infos and virtual nodes
hashRing *alg.HashRing
// Mutex
mu sync.RWMutex
}
func init() {
log.Info("Initialize: gate")
asyncGate()
}
// Prepare the environment for running application.
func asyncGate() {
go func() {
// static configuration
initApps()
// dynamic configuration
initListeners()
log.Info("Initialize listeners done")
}()
checkApps()
checkRings()
}
func initApps() {
// configuration
apps := getApps()
if len(apps) < 1 {
log.Info("No apps. Why? Please check the configuration.")
return
}
// A set of ring name . DataStruct: set
for _, app := range apps {
//TODO extension: ACL
ringName, err := getRingName(app)
if err != nil {
log.Error(err)
} else {
localGate.mu.Lock()
if ringName != "" {
log.Info("Get one app: ", app)
localGate.apps[app] = ringName
} else {
log.Info("The ringName is empty content from CS. AppName: ", app)
// Access Denied
delete(localGate.apps, app)
}
localGate.mu.Unlock()
}
}
}
// Do it right now. Add listeners so then app adds pools
func initListeners() {
// add listeners to the CS SDK
// all subscribed keys
dst := make(map[string]string)
for k, v := range localGate.apps {
dst[k] = v
}
if len(dst) < 1 {
log.Info("No ring name set! Please check all of the app!")
return
}
for app, _ := range dst {
addCaredKey(app)
}
// handle the common ring shared by multi apps
subscribeRings := make(map[string]bool)
for _, ringName := range localGate.apps {
subscribeRings[ringName] = true
}
for ringName, _ := range subscribeRings {
addCaredRing(ringName)
}
} // End func
// daemon check local file for a list of app name
func checkApps() {
go func() {
for {
time.Sleep(10 * time.Minute)
apps := getApps()
if len(apps) < 1 {
log.Info("Check apps in daemon, but no apps. Why? Please check the configuration.")
continue
}
var ringName string
var ok bool
for _, app := range apps {
addCaredKey(app)
if ringName, ok = localGate.apps[app]; ok {
time.Sleep(1 * time.Second)
// existed ringName in Gate struct
localGate.mu.RLock()
_, ringOK := localGate.rings[ringName]
localGate.mu.RUnlock()
if !ringOK {
// has new ring struct
addCaredRing(ringName)
}
} else {
// no ringName
// has new app that need to subscribe ring_name
}
}
}
}()
}
// daemon check localGate to remove the redundant pools
func checkRings() {
go func() {
for {
time.Sleep(10 * time.Second)
doCheckRings()
}
}()
}
// primitive operation
func doCheckRings() {
destroyRings := make(map[string]*ring)
// App_2_RingName apps
// RingName_2_Ring rings
for ringNameInRings, ring := range localGate.rings {
exist := false
apps:
for _, ringName := range localGate.apps {
if ringNameInRings == ringName {
exist = true
break apps
}
}
if !exist {
destroyRings[ringNameInRings] = ring
}
}
for ringName, r := range destroyRings {
log.Info("Prepare to destroy ring: ", ringName)
if r != nil {
r.Destroy()
}
localGate.mu.Lock()
delete(localGate.rings, ringName)
localGate.mu.Unlock()
}
}
// Let the Caller handle the error.
func Locate(appName, key string) (conn redis.Connection, err error) {
localGate.mu.RLock()
defer localGate.mu.RUnlock()
ringName, ok := localGate.apps[appName]
if !ok || ringName == "" {
log.Errorf("%s can not access the ring.", appName)
return nil, ErrAccessDenied
}
var r *ring
for i := 0; i < 3 && r == nil; i++ {
if r = localGate.rings[ringName]; r == nil {
time.Sleep(1 * time.Millisecond)
}
}
if r == nil {
return nil, ErrNoRing
}
// Get redis.Connection-Pool by key
addr := r.hashRing.PickMaster(key)
if pool := r.pools[addr]; pool != nil {
if conn, err = pool.Get(); err != nil {
log.Errorf("AppName: %s, Error: %s", appName, err)
}
}
return
}
func (gate *Gate) Close() error {
gate.mu.Lock()
defer gate.mu.Unlock()
has := false
for _, r := range gate.rings {
if len(r.pools) > 0 {
for addr, pool := range r.pools {
err := pool.Close()
if err != nil {
has = true
log.Errorf("When close address: %s, Error: %s", addr, err)
}
}
}
}
if has {
return errors.New("Have errors when close the gate.")
}
return nil
}
// A list of app name. From local file
func getApps() []string {
f := filepath.Join(cnfPkg.CnfBasedir, "apps.yaml")
cnf, err := ioutil.ReadFile(f)
if err != nil {
log.Errorf("Can not get a list of app name. The filepath: %s, Error: %s", f, err)
return nil
}
return DecodeAppsYAML(cnf)
}
// return ring name
func getRingName(app string) (string, error) {
// from CS
key := fmt.Sprintf(APP_CARE_KEYS_FORMAT, app)
cnf, err := cs.Get(key)
if err != nil {
log.Error("AppName: %s, Error: %s", app, err)
return "", err
}
simple, ok := cnf.(*cs.SimpleConfiguration)
if !ok {
log.Error("Key: ", key, ", but the value is wrong, not a simple string.")
return "", err
}
if simple.GetKey() == "" {
// The configuration has been deleted from the CS server.
return "", nil
}
// return only one RingName
return simple.GetValue().(string), nil
}
// Address_2_Weight
func getInstancesFromCS(ring string) map[string]uint32 {
// from CS
key := fmt.Sprintf(APP_CARE_RING_FORMAT, ring)
cnf, err := cs.Get(key)
if err != nil {
log.Error("Getting one ring from CS has one error. Error: ", err)
return nil
}
simple, ok := cnf.(*cs.SimpleConfiguration)
if !ok {
log.Error("Key: ", key, ", get ring info , but the wrong value not a simple string.")
return nil
}
if simple.GetKey() == "" {
// The configuration has been deleted from the CS server.
return nil
}
yaml := simple.GetValue().(string)
return getInstances(ring, yaml)
}
func getInstances(ringName, yaml string) map[string]uint32 {
ringYaml := DecodeRingYAMLByStr(ringName, yaml)
if ringYaml == nil {
log.Error("Get one ring occurs error! Actual: no RingYaml. Please check it!")
return nil
}
return ringYaml.getInstances()
}
// instances: Address_2_Weight , return Address_2_Pool
func newPools(instances map[string]uint32) (map[string]*redis.Pool, error) {
pools := make(map[string]*redis.Pool)
// new pool will be put into the map
for addr, _ := range instances {
pools[addr] = newPool(addr, "")
}
return pools, nil
}
func newPool(server, password string) *redis.Pool {
return &redis.Pool{
MaxActive: 1,
MaxIdle: 1,
IdleTimeout: 600 * time.Second,
Wait: true,
Dial: func() (redis.Connection, error) {
// nc, err := net.DialTimeout("tcp", server, 1*time.Second)
// if err != nil {
// log.Info("Create one connection, a error occurs.", server)
// return nil, err
// }
// tc, ok := nc.(*net.TCPConn)
// if !ok {
// return nil, errors.New("Not TCPConn")
// }
// if err := tc.SetKeepAlive(true); err != nil {
// return nil, err
// }
// if err := tc.SetKeepAlivePeriod(29 * time.Minute); err != nil {
// return nil, err
// }
// readTimeout := 1 * time.Second
// writeTimeout := 1 * time.Second
// c := redis.NewConn(tc, readTimeout, writeTimeout)
timeout := 1 * time.Second
c, err := redis.DialTimeout("tcp", server, timeout, timeout, timeout)
if err != nil {
log.Error("Create one connection, Error: ", server)
return nil, err
}
if password != "" {
log.Info("Need AUTH.")
}
return c, err
},
}
}
func (r *ring) Destroy() {
for _, p := range r.pools {
p.Close()
}
r.pools = nil
r.hashRing = nil
}
func newRing(instances map[string]uint32) (r *ring, err error) {
if len(instances) < 1 {
return nil, ErrNoRing
}
pools, pErr := newPools(instances)
hashRing, hErr := alg.NewRing(instances)
if hErr == nil && pErr == nil {
r = &ring{
pools: pools,
hashRing: hashRing,
}
return
} else {
log.Error("New connection-pooling occurs: ", pErr)
log.Error("New hash-ring occurs: ", hErr)
}
return r, ErrNewRing
}
// add listener
func addCaredKey(app string) {
localGate.mu.Lock()
defer localGate.mu.Unlock()
if app == "" {
log.Error("The AppName is empty!")
return
}
key := fmt.Sprintf(APP_CARE_KEYS_FORMAT, app)
// callback
ringNameFunc := func(cnf cs.Configuration) (err error) {
k := cnf.GetKey()
newRingName := cnf.GetValue().(string)
if key != k {
log.Error("Having subscribed ring_name,Shadow got it. The expected key: ", key, ". Having got the key from CS: ", k)
}
if k == "" {
// Having deleted from CS
localGate.mu.Lock()
delete(localGate.apps, app)
localGate.mu.Unlock()
return
}
localGate.mu.Lock()
localGate.apps[app] = newRingName
localGate.mu.Unlock()
// IF got newRingName is empty, THEN no access privilege!
if newRingName != "" {
localGate.mu.RLock()
_, ok := localGate.rings[newRingName]
localGate.mu.RUnlock()
// cascade
if !ok {
log.Info("Cascade add one new ring. The ring: ", newRingName)
addCaredRing(newRingName)
}
}
return
} // end callback
listener := &cs.DefaultListener{
Key: key,
DurationInSec: 1,
Receive: ringNameFunc,
}
cs.AddListener(listener)
}
// add listener
func addCaredRing(ringName string) {
localGate.mu.Lock()
defer localGate.mu.Unlock()
if ringName == "" {
deleteOldRing(ringName)
log.Error("The RingName is empty!")
return
}
key := fmt.Sprintf(APP_CARE_RING_FORMAT, ringName)
// callback
ringFunc := func(cnf cs.Configuration) (err error) {
k := cnf.GetKey()
yaml := cnf.GetValue().(string)
if key != k {
log.Info("Having subscribe ring instances,Shadow got it. The expected key: ", key, ". Having got the key from CS: ", k)
}
if k == "" {
// Having deleted from CS
deleteOldRing(ringName)
return
}
if yaml == "" {
// one person fatal !
deleteOldRing(ringName)
return
}
// new ->( type ring struct ), to replace the old one or add new one
log.Info("Prepare building the ring: ", ringName)
instances := getInstances(ringName, yaml)
newring, err := newRing(instances)
if length := len(instances); err == nil && length > 0 {
// store the old ring
localGate.mu.RLock()
old := localGate.rings[ringName]
localGate.mu.RUnlock()
if old != nil {
go func() {
old.Destroy()
}()
}
// Replace/Add
localGate.mu.Lock()
localGate.rings[ringName] = newring
localGate.mu.Unlock()
log.Infof("The ring: %s, has %d instances", ringName, length)
} else {
// parse errors
log.Info("The ring: ", ringName, ", has no instances!")
if err != nil {
log.Error("The ring: ", ringName, ". The error: ", err)
}
}
return
} // end callback
listener := &cs.DefaultListener{
Key: key,
DurationInSec: 1,
Receive: ringFunc,
}
cs.AddListener(listener)
}
func deleteOldRing(ringName string) {
localGate.mu.RLock()
old := localGate.rings[ringName]
localGate.mu.RUnlock()
if old != nil {
localGate.mu.Lock()
delete(localGate.rings, ringName)
localGate.mu.Unlock()
old.Destroy()
}
}
func Shutdown() {
localGate.Close()
}
// TODO
func Check() {
}
|
package main
import (
"context"
"fmt"
"log"
"time"
tracker_pb "github.com/mhannig/traack/service/lib/v1/tracker"
"google.golang.org/grpc"
)
func main() {
fmt.Println("traak v1")
// Set up a connection to the server.
conn, err := grpc.Dial("localhost:2344", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// Create client
customers_svc := tracker_pb.NewCustomerServiceClient(conn)
// Make request
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, err := customers_svc.CreateCustomer(ctx, &tracker_pb.CreateCustomerRequest{
Customer: &tracker_pb.Customer{
Name: "Fnordbert.",
},
})
if err != nil {
log.Println(err)
}
fmt.Println("Result:")
fmt.Println(res)
res, err = customers_svc.CreateCustomer(ctx, &tracker_pb.CreateCustomerRequest{
Customer: &tracker_pb.Customer{
Name: "Ft",
},
})
if err != nil {
log.Println(err)
}
fmt.Println("Result:")
fmt.Println(res)
res, err = customers_svc.CreateCustomer(ctx, &tracker_pb.CreateCustomerRequest{
Customer: &tracker_pb.Customer{
Name: "",
},
})
if err != nil {
log.Println(err)
}
fmt.Println("Result:")
fmt.Println(res)
}
|
package main
import (
"context"
"fmt"
"log"
"net"
"strings"
"time"
"github.com/moby/moby/pkg/pubsub"
"example.com/hello/rpc/pubsub/sub"
"google.golang.org/grpc"
)
type PublishServiceImp struct {
sub *pubsub.Publisher
}
func (p *PublishServiceImp) Publish(ctx context.Context, arg *sub.String) (*sub.String, error) {
p.sub.Publish(arg.GetValue())
return &sub.String{}, nil
}
func (p *PublishServiceImp) Subsribe(arg *sub.String, stream sub.PubsubService_SubsribeServer) error {
ch := p.sub.SubscribeTopic(func(v interface{}) bool {
if key, ok := v.(string); ok {
if strings.HasPrefix(key, arg.GetValue()) {
return true
}
}
return false
})
for v := range ch {
if err := stream.Send(&sub.String{Value: v.(string)}); err != nil {
fmt.Println(err)
}
}
return nil
}
func main() {
serv := grpc.NewServer()
sub.RegisterPubsubServiceServer(serv, &PublishServiceImp{pubsub.NewPublisher(time.Millisecond*100, 10)})
lis, err := net.Listen("tcp", ":8004")
if err != nil {
log.Fatal(err)
}
err = serv.Serve(lis)
if err != nil {
log.Fatal(err)
}
}
|
package models
import "github.com/bykof/go-plantuml/test/address/models"
type (
User struct {
FirstName string
LastName string
Age uint8
Address *models.Address
}
)
func (user *User) SetFirstName(firstName string) {
user.FirstName = firstName
}
func PackageFunction() string {
return "Hello World"
}
|
package app
import (
"log"
"net/http"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/gin-gonic/gin"
"github.com/sahlinet/go-tumbo/pkg/app/handler"
"github.com/sahlinet/go-tumbo/pkg/config"
)
type App struct {
Router *gin.Engine
DB *gorm.DB
}
func (a *App) Initialize(config *config.Config) {
// Database
db, err := gorm.Open(sqlite.Open(config.DB.Name), &gorm.Config{})
if err != nil {
log.Fatal("Could not connect database")
}
a.DB = model.DBMigrate(db)
a.Router = gin.Default()
a.setRouters()
}
// Wrap the router for GET method
/*func (a *App) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {
a.Router.HandleFunc(path, f).Methods("GET")
}
*/
/*// Wrap the router for POST method
func (a *App) Post(path string, f func(w http.ResponseWriter, r *http.Request)) {
a.Router.Use(handler.BasicAuth)
a.Router.HandleFunc(path, f).Methods("POST")
}
// Wrap the router for PUT method
func (a *App) Put(path string, f func(w http.ResponseWriter, r *http.Request)) {
a.Router.HandleFunc(path, f).Methods("PUT")
}
// Wrap the router for DELETE method
func (a *App) Delete(path string, f func(w http.ResponseWriter, r *http.Request)) {
a.Router.HandleFunc(path, f).Methods("DELETE")
}
*/
// Set all required routers
func (a *App) setRouters() {
// Routing for handling the projects
a.Router.GET("/workers", a.GetAllWorkers)
//a.Router.GET("/workers", a.CreateWorker)
}
// Handlers to manage workers
func (a *App) GetAllWorkers(c *gin.Context) func(*gin.Context) {
return handler.GetAllWorkers(a.DB, c)
}
func (a *App) CreateWorker(w http.ResponseWriter, r *http.Request) {
handler.CreateWorker(a.DB, w, r)
}
// Run the app on it's router
func (a *App) Run(host string) {
log.Fatal(http.ListenAndServe(host, a.Router))
}
|
package controller
import (
"context"
"fmt"
"github.com/rancher/k3p/pkg/apis/helm.k3s.io/v1alpha1"
helmcontroller "github.com/rancher/k3p/pkg/generated/controllers/helm.k3s.io/v1alpha1"
"github.com/rancher/k3p/types"
batch "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
k8stypes "k8s.io/apimachinery/pkg/types"
)
var (
systemNamespace = "kube-system"
)
func Register(ctx context.Context, rContext *types.Context, insecure bool) error {
apply := rContext.Apply.
WithCacheTypes(
rContext.Batch.Batch().V1().Job(),
rContext.Core.Core().V1().ServiceAccount(),
rContext.RBAC.Rbac().V1().Role(),
rContext.RBAC.Rbac().V1().ClusterRole(),
rContext.RBAC.Rbac().V1().RoleBinding(),
rContext.RBAC.Rbac().V1().ClusterRoleBinding(),
).
WithPatcher(batch.SchemeGroupVersion.WithKind("Job"), func(namespace, name string, pt k8stypes.PatchType, data []byte) (runtime.Object, error) {
err := rContext.Batch.Batch().V1().Job().Delete(namespace, name, &metav1.DeleteOptions{})
if err == nil {
return nil, fmt.Errorf("replace job")
}
return nil, nil
})
h := handler{
insecure: insecure,
}
helmcontroller.RegisterChartGeneratingHandler(
ctx,
rContext.Helm.Helm().V1alpha1().Chart(),
apply,
"ChartJobDeployed",
"k3p-chart",
h.generate,
nil,
)
return nil
}
type handler struct {
insecure bool
}
func serviceAccountName(obj *v1alpha1.Chart) string {
return fmt.Sprintf("%s-sa-install", obj.Name)
}
func roleName(obj *v1alpha1.Chart) string {
return fmt.Sprintf("%s-role-install", obj.Name)
}
func clusterroleName(obj *v1alpha1.Chart) string {
return fmt.Sprintf("%s-clusterrole-install", obj.Name)
}
func (h handler) generate(obj *v1alpha1.Chart, status v1alpha1.ChartStatus) ([]runtime.Object, v1alpha1.ChartStatus, error) {
var result []runtime.Object
result = append(result, h.generateRbacRoles(obj)...)
result = append(result, h.generateServiceAccount(obj)...)
}
func (h handler) generateServiceAccount(obj *v1alpha1.Chart) []runtime.Object {
sa := &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName(obj),
Namespace: obj.Namespace,
},
}
return []runtime.Object{sa}
}
// if controller is set to insecure mode, also create (cluster)roles and (cluster)rolebindings
func (h handler) generateRbacRoles(obj *v1alpha1.Chart) []runtime.Object {
var result []runtime.Object
if h.insecure {
role := obj.Spec.RbacSetting.Roles
role.Name = fmt.Sprintf("%s-role-install", obj.Name)
clusterrole := obj.Spec.RbacSetting.ClusterRoles
clusterrole.Name = fmt.Sprintf("%s-clusterrole-install", obj.Name)
result = append(result, &role, &clusterrole)
}
rolebinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-rolebinding-install"),
Namespace: obj.Namespace,
},
RoleRef: rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Kind: "Role",
Name: roleName(obj),
},
Subjects: []rbacv1.Subject{
{
APIGroup: v1.GroupName,
Name: serviceAccountName(obj),
Namespace: obj.Namespace,
},
},
}
clusterrolebinding := &rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-clusterrolebinding-install"),
Namespace: obj.Namespace,
},
RoleRef: rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Kind: "ClusterRole",
Name: clusterroleName(obj),
},
Subjects: []rbacv1.Subject{
{
APIGroup: v1.GroupName,
Name: serviceAccountName(obj),
Namespace: obj.Namespace,
},
},
}
result = append(result, rolebinding, clusterrolebinding)
return result
}
func (h handler) generateValues(obj *v1alpha1.Chart) []string {
var answerArgs []string
answerArgs = []string{"--value", "/tmp/values/values.yaml"}
for k, v := range obj.Spec.ValueOverride {
answerArgs = append(answerArgs, "--set", fmt.Sprintf("%s=%s", k, v))
}
if obj.Spec.PrivateRegistry.Key != "" && obj.Spec.PrivateRegistry.Value != "" {
answerArgs = append(answerArgs, "--set", fmt.Sprintf("%s=%s", obj.Spec.PrivateRegistry.Key, obj.Spec.PrivateRegistry.Value))
}
return answerArgs
}
func (h handler) generateJob(obj *v1alpha1.Chart) error {
volumeName := "chart-dir"
mountPath := "/tmp/charts"
job := batch.Job{
ObjectMeta: metav1.ObjectMeta{
GenerateName: obj.Name + "-",
Namespace: systemNamespace,
},
Spec: batch.JobSpec{
Template: v1.PodTemplateSpec{
Spec: v1.PodSpec{
ServiceAccountName: serviceAccountName(obj),
Volumes: []v1.Volume{
{
Name: volumeName,
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
},
},
Containers: []v1.Container{
{
Image: "strongmonkey1992/helm-install",
VolumeMounts: []v1.VolumeMount{
{
Name: volumeName,
MountPath: mountPath,
},
},
Args: []string{
"helm",
"install",
""
}
},
},
},
},
},
}
}
|
// Copyright 2020 The gVisor 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 netfilter
import (
"encoding/binary"
"fmt"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/hostarch"
"gvisor.dev/gvisor/pkg/marshal"
"gvisor.dev/gvisor/pkg/syserr"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
// ErrorTargetName is used to mark targets as error targets. Error targets
// shouldn't be reached - an error has occurred if we fall through to one.
const ErrorTargetName = "ERROR"
// RedirectTargetName is used to mark targets as redirect targets. Redirect
// targets should be reached for only NAT and Mangle tables. These targets will
// change the destination port and/or IP for packets.
const RedirectTargetName = "REDIRECT"
// SNATTargetName is used to mark targets as SNAT targets. SNAT targets should
// be reached for only NAT table. These targets will change the source port
// and/or IP for packets.
const SNATTargetName = "SNAT"
func init() {
// Standard targets include ACCEPT, DROP, RETURN, and JUMP.
registerTargetMaker(&standardTargetMaker{
NetworkProtocol: header.IPv4ProtocolNumber,
})
registerTargetMaker(&standardTargetMaker{
NetworkProtocol: header.IPv6ProtocolNumber,
})
// Both user chains and actual errors are represented in iptables by
// error targets.
registerTargetMaker(&errorTargetMaker{
NetworkProtocol: header.IPv4ProtocolNumber,
})
registerTargetMaker(&errorTargetMaker{
NetworkProtocol: header.IPv6ProtocolNumber,
})
registerTargetMaker(&redirectTargetMaker{
NetworkProtocol: header.IPv4ProtocolNumber,
})
registerTargetMaker(&nfNATTargetMaker{
NetworkProtocol: header.IPv6ProtocolNumber,
})
registerTargetMaker(&snatTargetMakerV4{
NetworkProtocol: header.IPv4ProtocolNumber,
})
registerTargetMaker(&snatTargetMakerV6{
NetworkProtocol: header.IPv6ProtocolNumber,
})
}
// The stack package provides some basic, useful targets for us. The following
// types wrap them for compatibility with the extension system.
type acceptTarget struct {
stack.AcceptTarget
}
func (at *acceptTarget) id() targetID {
return targetID{
networkProtocol: at.NetworkProtocol,
}
}
type dropTarget struct {
stack.DropTarget
}
func (dt *dropTarget) id() targetID {
return targetID{
networkProtocol: dt.NetworkProtocol,
}
}
type errorTarget struct {
stack.ErrorTarget
}
func (et *errorTarget) id() targetID {
return targetID{
name: ErrorTargetName,
networkProtocol: et.NetworkProtocol,
}
}
type userChainTarget struct {
stack.UserChainTarget
}
func (uc *userChainTarget) id() targetID {
return targetID{
name: ErrorTargetName,
networkProtocol: uc.NetworkProtocol,
}
}
type returnTarget struct {
stack.ReturnTarget
}
func (rt *returnTarget) id() targetID {
return targetID{
networkProtocol: rt.NetworkProtocol,
}
}
type redirectTarget struct {
stack.RedirectTarget
// addr must be (un)marshalled when reading and writing the target to
// userspace, but does not affect behavior.
addr tcpip.Address
}
func (rt *redirectTarget) id() targetID {
return targetID{
name: RedirectTargetName,
networkProtocol: rt.NetworkProtocol,
}
}
type snatTarget struct {
stack.SNATTarget
}
func (st *snatTarget) id() targetID {
return targetID{
name: SNATTargetName,
networkProtocol: st.NetworkProtocol,
}
}
type standardTargetMaker struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (sm *standardTargetMaker) id() targetID {
// Standard targets have the empty string as a name and no revisions.
return targetID{
networkProtocol: sm.NetworkProtocol,
}
}
func (*standardTargetMaker) marshal(target target) []byte {
// Translate verdicts the same way as the iptables tool.
var verdict int32
switch tg := target.(type) {
case *acceptTarget:
verdict = -linux.NF_ACCEPT - 1
case *dropTarget:
verdict = -linux.NF_DROP - 1
case *returnTarget:
verdict = linux.NF_RETURN
case *JumpTarget:
verdict = int32(tg.Offset)
default:
panic(fmt.Errorf("unknown target of type %T", target))
}
// The target's name will be the empty string.
xt := linux.XTStandardTarget{
Target: linux.XTEntryTarget{
TargetSize: linux.SizeOfXTStandardTarget,
},
Verdict: verdict,
}
return marshal.Marshal(&xt)
}
func (*standardTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if len(buf) != linux.SizeOfXTStandardTarget {
nflog("buf has wrong size for standard target %d", len(buf))
return nil, syserr.ErrInvalidArgument
}
var standardTarget linux.XTStandardTarget
standardTarget.UnmarshalUnsafe(buf)
if standardTarget.Verdict < 0 {
// A Verdict < 0 indicates a non-jump verdict.
return translateToStandardTarget(standardTarget.Verdict, filter.NetworkProtocol())
}
// A verdict >= 0 indicates a jump.
return &JumpTarget{
Offset: uint32(standardTarget.Verdict),
NetworkProtocol: filter.NetworkProtocol(),
}, nil
}
type errorTargetMaker struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (em *errorTargetMaker) id() targetID {
// Error targets have no revision.
return targetID{
name: ErrorTargetName,
networkProtocol: em.NetworkProtocol,
}
}
func (*errorTargetMaker) marshal(target target) []byte {
var errorName string
switch tg := target.(type) {
case *errorTarget:
errorName = ErrorTargetName
case *userChainTarget:
errorName = tg.Name
default:
panic(fmt.Sprintf("errorMakerTarget cannot marshal unknown type %T", target))
}
// This is an error target named error
xt := linux.XTErrorTarget{
Target: linux.XTEntryTarget{
TargetSize: linux.SizeOfXTErrorTarget,
},
}
copy(xt.Name[:], errorName)
copy(xt.Target.Name[:], ErrorTargetName)
return marshal.Marshal(&xt)
}
func (*errorTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if len(buf) != linux.SizeOfXTErrorTarget {
nflog("buf has insufficient size for error target %d", len(buf))
return nil, syserr.ErrInvalidArgument
}
var errTgt linux.XTErrorTarget
errTgt.UnmarshalUnsafe(buf)
// Error targets are used in 2 cases:
// * An actual error case. These rules have an error named
// ErrorTargetName. The last entry of the table is usually an error
// case to catch any packets that somehow fall through every rule.
// * To mark the start of a user defined chain. These
// rules have an error with the name of the chain.
switch name := errTgt.Name.String(); name {
case ErrorTargetName:
return &errorTarget{stack.ErrorTarget{
NetworkProtocol: filter.NetworkProtocol(),
}}, nil
default:
// User defined chain.
return &userChainTarget{stack.UserChainTarget{
Name: name,
NetworkProtocol: filter.NetworkProtocol(),
}}, nil
}
}
type redirectTargetMaker struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (rm *redirectTargetMaker) id() targetID {
return targetID{
name: RedirectTargetName,
networkProtocol: rm.NetworkProtocol,
}
}
func (*redirectTargetMaker) marshal(target target) []byte {
rt := target.(*redirectTarget)
// This is a redirect target named redirect
xt := linux.XTRedirectTarget{
Target: linux.XTEntryTarget{
TargetSize: linux.SizeOfXTRedirectTarget,
},
}
copy(xt.Target.Name[:], RedirectTargetName)
xt.NfRange.RangeSize = 1
xt.NfRange.RangeIPV4.Flags |= linux.NF_NAT_RANGE_PROTO_SPECIFIED
xt.NfRange.RangeIPV4.MinPort = htons(rt.Port)
xt.NfRange.RangeIPV4.MaxPort = xt.NfRange.RangeIPV4.MinPort
return marshal.Marshal(&xt)
}
func (*redirectTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if len(buf) < linux.SizeOfXTRedirectTarget {
nflog("redirectTargetMaker: buf has insufficient size for redirect target %d", len(buf))
return nil, syserr.ErrInvalidArgument
}
if p := filter.Protocol; p != header.TCPProtocolNumber && p != header.UDPProtocolNumber {
nflog("redirectTargetMaker: bad proto %d", p)
return nil, syserr.ErrInvalidArgument
}
var rt linux.XTRedirectTarget
rt.UnmarshalUnsafe(buf)
// Copy linux.XTRedirectTarget to stack.RedirectTarget.
target := redirectTarget{RedirectTarget: stack.RedirectTarget{
NetworkProtocol: filter.NetworkProtocol(),
}}
// RangeSize should be 1.
nfRange := rt.NfRange
if nfRange.RangeSize != 1 {
nflog("redirectTargetMaker: bad rangesize %d", nfRange.RangeSize)
return nil, syserr.ErrInvalidArgument
}
// Also check if we need to map ports or IP.
// For now, redirect target only supports destination port change.
// Port range and IP range are not supported yet.
if nfRange.RangeIPV4.Flags != linux.NF_NAT_RANGE_PROTO_SPECIFIED {
nflog("redirectTargetMaker: invalid range flags %d", nfRange.RangeIPV4.Flags)
return nil, syserr.ErrInvalidArgument
}
if nfRange.RangeIPV4.MinPort != nfRange.RangeIPV4.MaxPort {
nflog("redirectTargetMaker: MinPort != MaxPort (%d, %d)", nfRange.RangeIPV4.MinPort, nfRange.RangeIPV4.MaxPort)
return nil, syserr.ErrInvalidArgument
}
if nfRange.RangeIPV4.MinIP != nfRange.RangeIPV4.MaxIP {
nflog("redirectTargetMaker: MinIP != MaxIP (%d, %d)", nfRange.RangeIPV4.MinPort, nfRange.RangeIPV4.MaxPort)
return nil, syserr.ErrInvalidArgument
}
target.addr = tcpip.AddrFrom4(nfRange.RangeIPV4.MinIP)
target.Port = ntohs(nfRange.RangeIPV4.MinPort)
return &target, nil
}
// +marshal
type nfNATTarget struct {
Target linux.XTEntryTarget
Range linux.NFNATRange
}
const nfNATMarshalledSize = linux.SizeOfXTEntryTarget + linux.SizeOfNFNATRange
type nfNATTargetMaker struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (rm *nfNATTargetMaker) id() targetID {
return targetID{
name: RedirectTargetName,
networkProtocol: rm.NetworkProtocol,
}
}
func (*nfNATTargetMaker) marshal(target target) []byte {
rt := target.(*redirectTarget)
nt := nfNATTarget{
Target: linux.XTEntryTarget{
TargetSize: nfNATMarshalledSize,
},
Range: linux.NFNATRange{
Flags: linux.NF_NAT_RANGE_PROTO_SPECIFIED,
},
}
copy(nt.Target.Name[:], RedirectTargetName)
copy(nt.Range.MinAddr[:], rt.addr.AsSlice())
copy(nt.Range.MaxAddr[:], rt.addr.AsSlice())
nt.Range.MinProto = htons(rt.Port)
nt.Range.MaxProto = nt.Range.MinProto
return marshal.Marshal(&nt)
}
func (*nfNATTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if size := nfNATMarshalledSize; len(buf) < size {
nflog("nfNATTargetMaker: buf has insufficient size (%d) for nfNAT target (%d)", len(buf), size)
return nil, syserr.ErrInvalidArgument
}
if p := filter.Protocol; p != header.TCPProtocolNumber && p != header.UDPProtocolNumber {
nflog("nfNATTargetMaker: bad proto %d", p)
return nil, syserr.ErrInvalidArgument
}
var natRange linux.NFNATRange
natRange.UnmarshalUnsafe(buf[linux.SizeOfXTEntryTarget:])
// We don't support port or address ranges.
if natRange.MinAddr != natRange.MaxAddr {
nflog("nfNATTargetMaker: MinAddr and MaxAddr are different")
return nil, syserr.ErrInvalidArgument
}
if natRange.MinProto != natRange.MaxProto {
nflog("nfNATTargetMaker: MinProto and MaxProto are different")
return nil, syserr.ErrInvalidArgument
}
// For now, redirect target only supports destination change.
if natRange.Flags != linux.NF_NAT_RANGE_PROTO_SPECIFIED {
nflog("nfNATTargetMaker: invalid range flags %d", natRange.Flags)
return nil, syserr.ErrInvalidArgument
}
target := redirectTarget{
RedirectTarget: stack.RedirectTarget{
NetworkProtocol: filter.NetworkProtocol(),
Port: ntohs(natRange.MinProto),
},
addr: tcpip.AddrFrom16(natRange.MinAddr),
}
return &target, nil
}
type snatTargetMakerV4 struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (st *snatTargetMakerV4) id() targetID {
return targetID{
name: SNATTargetName,
networkProtocol: st.NetworkProtocol,
}
}
func (*snatTargetMakerV4) marshal(target target) []byte {
st := target.(*snatTarget)
// This is a snat target named snat.
xt := linux.XTSNATTarget{
Target: linux.XTEntryTarget{
TargetSize: linux.SizeOfXTSNATTarget,
},
}
copy(xt.Target.Name[:], SNATTargetName)
xt.NfRange.RangeSize = 1
xt.NfRange.RangeIPV4.Flags |= linux.NF_NAT_RANGE_MAP_IPS | linux.NF_NAT_RANGE_PROTO_SPECIFIED
xt.NfRange.RangeIPV4.MinPort = htons(st.Port)
xt.NfRange.RangeIPV4.MaxPort = xt.NfRange.RangeIPV4.MinPort
copy(xt.NfRange.RangeIPV4.MinIP[:], st.Addr.AsSlice())
copy(xt.NfRange.RangeIPV4.MaxIP[:], st.Addr.AsSlice())
return marshal.Marshal(&xt)
}
func (*snatTargetMakerV4) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if len(buf) < linux.SizeOfXTSNATTarget {
nflog("snatTargetMakerV4: buf has insufficient size for snat target %d", len(buf))
return nil, syserr.ErrInvalidArgument
}
if p := filter.Protocol; p != header.TCPProtocolNumber && p != header.UDPProtocolNumber {
nflog("snatTargetMakerV4: bad proto %d", p)
return nil, syserr.ErrInvalidArgument
}
var st linux.XTSNATTarget
st.UnmarshalUnsafe(buf)
// Copy linux.XTSNATTarget to stack.SNATTarget.
target := snatTarget{SNATTarget: stack.SNATTarget{
NetworkProtocol: filter.NetworkProtocol(),
}}
// RangeSize should be 1.
nfRange := st.NfRange
if nfRange.RangeSize != 1 {
nflog("snatTargetMakerV4: bad rangesize %d", nfRange.RangeSize)
return nil, syserr.ErrInvalidArgument
}
// TODO(gvisor.dev/issue/5772): If the rule doesn't specify the source port,
// choose one automatically.
if nfRange.RangeIPV4.MinPort == 0 {
nflog("snatTargetMakerV4: snat target needs to specify a non-zero port")
return nil, syserr.ErrInvalidArgument
}
if nfRange.RangeIPV4.MinPort != nfRange.RangeIPV4.MaxPort {
nflog("snatTargetMakerV4: MinPort != MaxPort (%d, %d)", nfRange.RangeIPV4.MinPort, nfRange.RangeIPV4.MaxPort)
return nil, syserr.ErrInvalidArgument
}
if nfRange.RangeIPV4.MinIP != nfRange.RangeIPV4.MaxIP {
nflog("snatTargetMakerV4: MinIP != MaxIP (%d, %d)", nfRange.RangeIPV4.MinPort, nfRange.RangeIPV4.MaxPort)
return nil, syserr.ErrInvalidArgument
}
target.Addr = tcpip.AddrFrom4(nfRange.RangeIPV4.MinIP)
target.Port = ntohs(nfRange.RangeIPV4.MinPort)
return &target, nil
}
type snatTargetMakerV6 struct {
NetworkProtocol tcpip.NetworkProtocolNumber
}
func (st *snatTargetMakerV6) id() targetID {
return targetID{
name: SNATTargetName,
networkProtocol: st.NetworkProtocol,
revision: 1,
}
}
func (*snatTargetMakerV6) marshal(target target) []byte {
st := target.(*snatTarget)
nt := nfNATTarget{
Target: linux.XTEntryTarget{
TargetSize: nfNATMarshalledSize,
},
Range: linux.NFNATRange{
Flags: linux.NF_NAT_RANGE_MAP_IPS | linux.NF_NAT_RANGE_PROTO_SPECIFIED,
},
}
copy(nt.Target.Name[:], SNATTargetName)
copy(nt.Range.MinAddr[:], st.Addr.AsSlice())
copy(nt.Range.MaxAddr[:], st.Addr.AsSlice())
nt.Range.MinProto = htons(st.Port)
nt.Range.MaxProto = nt.Range.MinProto
return marshal.Marshal(&nt)
}
func (*snatTargetMakerV6) unmarshal(buf []byte, filter stack.IPHeaderFilter) (target, *syserr.Error) {
if size := nfNATMarshalledSize; len(buf) < size {
nflog("snatTargetMakerV6: buf has insufficient size (%d) for SNAT V6 target (%d)", len(buf), size)
return nil, syserr.ErrInvalidArgument
}
if p := filter.Protocol; p != header.TCPProtocolNumber && p != header.UDPProtocolNumber {
nflog("snatTargetMakerV6: bad proto %d", p)
return nil, syserr.ErrInvalidArgument
}
var natRange linux.NFNATRange
natRange.UnmarshalUnsafe(buf[linux.SizeOfXTEntryTarget:])
// TODO(gvisor.dev/issue/5697): Support port or address ranges.
if natRange.MinAddr != natRange.MaxAddr {
nflog("snatTargetMakerV6: MinAddr and MaxAddr are different")
return nil, syserr.ErrInvalidArgument
}
if natRange.MinProto != natRange.MaxProto {
nflog("snatTargetMakerV6: MinProto and MaxProto are different")
return nil, syserr.ErrInvalidArgument
}
// TODO(gvisor.dev/issue/5698): Support other NF_NAT_RANGE flags.
if natRange.Flags != linux.NF_NAT_RANGE_MAP_IPS|linux.NF_NAT_RANGE_PROTO_SPECIFIED {
nflog("snatTargetMakerV6: invalid range flags %d", natRange.Flags)
return nil, syserr.ErrInvalidArgument
}
target := snatTarget{
SNATTarget: stack.SNATTarget{
NetworkProtocol: filter.NetworkProtocol(),
Addr: tcpip.AddrFrom16(natRange.MinAddr),
Port: ntohs(natRange.MinProto),
},
}
return &target, nil
}
// translateToStandardTarget translates from the value in a
// linux.XTStandardTarget to an stack.Verdict.
func translateToStandardTarget(val int32, netProto tcpip.NetworkProtocolNumber) (target, *syserr.Error) {
switch val {
case -linux.NF_ACCEPT - 1:
return &acceptTarget{stack.AcceptTarget{
NetworkProtocol: netProto,
}}, nil
case -linux.NF_DROP - 1:
return &dropTarget{stack.DropTarget{
NetworkProtocol: netProto,
}}, nil
case -linux.NF_QUEUE - 1:
nflog("unsupported iptables verdict QUEUE")
return nil, syserr.ErrInvalidArgument
case linux.NF_RETURN:
return &returnTarget{stack.ReturnTarget{
NetworkProtocol: netProto,
}}, nil
default:
nflog("unknown iptables verdict %d", val)
return nil, syserr.ErrInvalidArgument
}
}
// parseTarget parses a target from optVal. optVal should contain only the
// target.
func parseTarget(filter stack.IPHeaderFilter, optVal []byte, ipv6 bool) (stack.Target, *syserr.Error) {
nflog("set entries: parsing target of size %d", len(optVal))
if len(optVal) < linux.SizeOfXTEntryTarget {
nflog("optVal has insufficient size for entry target %d", len(optVal))
return nil, syserr.ErrInvalidArgument
}
var target linux.XTEntryTarget
// Do not advance optVal as targetMake.unmarshal() may unmarshal
// XTEntryTarget again but with some added fields.
target.UnmarshalUnsafe(optVal)
return unmarshalTarget(target, filter, optVal)
}
// JumpTarget implements stack.Target.
type JumpTarget struct {
// Offset is the byte offset of the rule to jump to. It is used for
// marshaling and unmarshaling.
Offset uint32
// RuleNum is the rule to jump to.
RuleNum int
// NetworkProtocol is the network protocol the target is used with.
NetworkProtocol tcpip.NetworkProtocolNumber
}
// ID implements Target.ID.
func (jt *JumpTarget) id() targetID {
return targetID{
networkProtocol: jt.NetworkProtocol,
}
}
// Action implements stack.Target.Action.
func (jt *JumpTarget) Action(stack.PacketBufferPtr, stack.Hook, *stack.Route, stack.AddressableEndpoint) (stack.RuleVerdict, int) {
return stack.RuleJump, jt.RuleNum
}
func ntohs(port uint16) uint16 {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, port)
return hostarch.ByteOrder.Uint16(buf)
}
func htons(port uint16) uint16 {
buf := make([]byte, 2)
hostarch.ByteOrder.PutUint16(buf, port)
return binary.BigEndian.Uint16(buf)
}
|
package main
import "github.com/tobymiller/s3-fast-transfer/cmd"
func main() {
cmd.Execute()
}
|
package helper
import (
"log"
"gopkg.in/mgo.v2"
)
const (
MongoTestingAddr = "127.0.0.1:27017"
)
func MustCreateMongoSession(mongoURL string) *mgo.Session {
session, err := mgo.Dial(mongoURL)
if err != nil {
log.Fatal("mongo server connection failed:", err)
}
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
return session
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"github.com/yeboahnanaosei/go/cval"
)
type e struct {
Msg string `json:"msg"`
Fix string `json:"fix"`
}
type jsonPayload struct {
Ok bool `json:"ok"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
Error e `json:"error,omitempty"`
}
var pretty = flag.Bool("p", false, "Pretty print output")
func sendOutput(payload jsonPayload, dest io.Writer) {
encoder := json.NewEncoder(dest)
if *pretty {
encoder.SetIndent("", " ")
}
encoder.Encode(payload)
}
func main() {
flag.Parse()
filename := flag.Arg(0)
output := run(filename)
sendOutput(output, os.Stdout)
}
func run(filename string) jsonPayload {
out := jsonPayload{}
if filename == "" {
out.Msg = "Exactly one argument expected"
out.Error.Msg = "cvet expects exactly one argument which is the path to the csv file being vetted"
out.Error.Fix = fmt.Sprintf("call cvet with the path to the csv file as the first argument. Eg %s /path/to/csv/file", os.Args[0])
return out
}
csvFile, err := os.Open(filename)
if err != nil {
out.Msg = fmt.Sprintf("Could not open file: %s", filename)
out.Error.Msg = fmt.Sprintf("There was an error trying to open the csv file: %v", err)
out.Error.Fix = "Ensure you provided a valid csv file"
return out
}
defer csvFile.Close()
// Perform the actual parsing of the csv file
validRecords, invalidRecords, err := cval.Validate(csvFile)
if err != nil {
out.Msg = "An internal error occured"
out.Error.Msg = fmt.Sprintf("There was an error trying to process the csv file: %v", err)
out.Error.Fix = "Ensure you provided a valid csv file. If this continues, please wait and try again later. You can also contact support"
return out
}
out.Ok = true
out.Msg = "File vetted successfully"
out.Data = map[string]interface{}{
"validRecords": validRecords,
"invalidRecords": invalidRecords,
}
return out
}
|
// Copyright 2020 apirator.io
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oas
import (
"context"
"github.com/getkin/kin-openapi/openapi3"
"github.com/ghodss/yaml"
"sigs.k8s.io/controller-runtime/pkg/log"
)
func Validate(definition string) error {
doc := &openapi3.Swagger{}
err := yaml.Unmarshal([]byte(definition), doc)
if err != nil {
log.Log.Error(err, "Error to parse yaml to oas")
return err
}
oasErr := doc.Validate(context.TODO())
if oasErr != nil {
log.Log.Error(oasErr, "Open API Specification is invalid")
return err
}
log.Log.Info("Open API Specification is VALID")
return nil
}
|
package message
// ConfigNotFound should be used if devspace.yaml cannot be found
const ConfigNotFound = "Cannot find a devspace.yaml for this project. Please run `devspace init`"
// ServiceNotFound should be used if there are no Kubernetes services resources
const ServiceNotFound = "Cannot find any services in namespace '%s'. Please make sure you have a service that this ingress can connect to. \n\nTo get a list of services in your current namespace, run: kubectl get services"
|
/*
Copyright (C) 2018 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"github.com/gravitational/rigging"
"github.com/gravitational/trace"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// Client is the Kubernetes API client
type Client struct {
*kubernetes.Clientset
restConfig *rest.Config
}
// NewClient returns a new clientset for Kubernetes APIs
func NewClient(kubeConfig string) (*Client, error) {
config, err := GetClientConfig(kubeConfig)
if err != nil {
return nil, trace.Wrap(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, trace.Wrap(err)
}
return &Client{
Clientset: clientset,
restConfig: config,
}, nil
}
// Pods returns pithos pods matching the specified label
func (c *Client) Pods(selector, namespace string) ([]v1.Pod, error) {
labelSelector, err := labels.Parse(selector)
if err != nil {
return nil, trace.Wrap(err, "the provided label selector %s is not valid", selector)
}
podList, err := c.CoreV1().Pods(namespace).List(metav1.ListOptions{LabelSelector: labelSelector.String()})
if err != nil {
return nil, rigging.ConvertError(err)
}
if len(podList.Items) == 0 {
return nil, trace.NotFound("no pods found matching the specified selector %s", labelSelector)
}
return podList.Items, nil
}
// GetSecret returns configmap containing pithos configuration
func (c *Client) GetSecret(secretName, namespace string) (*v1.Secret, error) {
secret, err := c.CoreV1().Secrets(namespace).Get(secretName, metav1.GetOptions{})
if err != nil {
return nil, rigging.ConvertError(err)
}
return secret, nil
}
// NodesMatchingLabel returns nodes matching specific labels
func (c *Client) NodesMatchingLabel(selector string) (*v1.NodeList, error) {
nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
return nil, rigging.ConvertError(err)
}
return nodes, nil
}
// GetClientConfig returns client configuration,
// if KubeConfig is not specified, in-cluster configuration is assumed
func GetClientConfig(kubeConfig string) (*rest.Config, error) {
if kubeConfig != "" {
return clientcmd.BuildConfigFromFlags("", kubeConfig)
}
return rest.InClusterConfig()
}
|
package wasmvm
import "testing"
func TestNewWasmStateMachine(t *testing.T) {
sm := NewWasmStateMachine()
if sm == nil {
t.Fatal("NewWasmStateMachine should return a non nil state machine")
}
if sm.WasmStateReader == nil {
t.Fatal("NewWasmStateMachine should return a non nil state reader")
}
if !sm.Exists("ContractLogDebug") {
t.Error("NewWasmStateMachine should has ContractLogDebug service")
}
if !sm.Exists("ContractLogInfo") {
t.Error("NewWasmStateMachine should has ContractLogInfo service")
}
if !sm.Exists("ContractLogError") {
t.Error("NewWasmStateMachine should has ContractLogError service")
}
}
|
package viewhelpers
import (
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ToTimeMarkdown returns a formatted time as markdown
func ToTimeMarkdown(mt *metav1.Time) string {
if mt == nil {
return ""
}
return mt.Time.Format(time.RFC822)
}
|
package explore
import (
"encoding/json"
"fmt"
"os"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/dolittle/platform-api/pkg/k8s"
platformK8s "github.com/dolittle/platform-api/pkg/platform/k8s"
)
var ingressCMD = &cobra.Command{
Use: "ingress",
Short: "Get ingress data for customer tenants + microservices",
Long: `
go run main.go tools explore ingress
`,
Run: func(cmd *cobra.Command, args []string) {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetOutput(os.Stdout)
logContext := logrus.StandardLogger()
logContext.Info("Hello")
k8sClient, _ := platformK8s.InitKubernetesClient()
k8sRepoV2 := k8s.NewRepo(k8sClient, logContext.WithField("context", "k8s-repo-v2"))
namespaces, err := k8sRepoV2.GetNamespacesWithApplication()
if err != nil {
logContext.WithFields(logrus.Fields{
"error": err,
}).Fatal("Getting namespaces")
}
for _, namespace := range namespaces {
ingresses, err := k8sRepoV2.GetIngresses(namespace.Name)
if err != nil {
logContext.WithFields(logrus.Fields{
"error": err,
}).Fatal("Getting ingresses")
}
for _, ingress := range ingresses {
tenantHeaderAnnotation := ingress.GetObjectMeta().GetAnnotations()["nginx.ingress.kubernetes.io/configuration-snippet"]
customerTenantID := platformK8s.GetCustomerTenantIDFromNginxConfigurationSnippet(tenantHeaderAnnotation)
if customerTenantID == "" {
continue
}
data := map[string]string{
"namesspace": namespace.Name,
"customer_id": ingress.Annotations["dolittle.io/tenant-id"],
"application_id": ingress.Annotations["dolittle.io/application-id"],
"microservice_id": ingress.Annotations["dolittle.io/microservice-id"],
"customer_tenant_id": customerTenantID,
"environent": ingress.Labels["environment"],
"ingress_namee": ingress.Name,
"cmd": fmt.Sprintf(
`kubectl -n %s get ingress %s -oyaml`,
namespace.Name,
ingress.Name,
),
}
for _, rule := range ingress.Spec.Rules {
for _, ingressPath := range rule.HTTP.Paths {
data["path"] = ingressPath.Path
data["host"] = rule.Host
b, _ := json.Marshal(data)
fmt.Println(string(b))
}
}
}
}
},
}
|
package backup
import (
"fmt"
"time"
)
var daysOfWeek = map[string]time.Weekday{
"sunday": time.Sunday,
"monday": time.Monday,
"tuesday": time.Tuesday,
"wednesday": time.Wednesday,
"thursday": time.Thursday,
"friday": time.Friday,
"saturday": time.Saturday,
}
func parseWeekday(v string) (time.Weekday, error) {
if d, ok := daysOfWeek[v]; ok {
return d, nil
}
return time.Sunday, fmt.Errorf("invalid weekday '%s'", v)
}
|
package graph
import (
"encoding/json"
)
// ParseJSON parses a given definition in NoFlo's .JSON and returns
// unified Description structure
func ParseJSON(definition []byte) (*Description, error) {
var graph Description
err := json.Unmarshal(definition, &graph)
if err != nil {
return nil, err
}
return &graph, nil
}
|
package main
import (
"fmt"
"os"
"runtime"
"strconv"
"time"
)
func SetupCPU() {
num := runtime.NumCPU()
runtime.GOMAXPROCS(num)
}
func Date2Time(date string) (time.Time, error) {
const shortForm = "2006-01-02"
t1, err := time.Parse(shortForm, date)
return t1, err
}
func Today() (time.Time, error) {
t3 := time.Now()
today := fmt.Sprintf("%04d-%02d-%02d", t3.Year(), t3.Month(), t3.Day())
return Date2Time(today)
}
func IntToStr(i int) string {
return strconv.Itoa(i)
}
func StrToInt(s string) int {
v, _ := strconv.Atoi(s)
return v
}
func IsFileExist(file string) bool {
_, err := os.Stat(file)
return os.IsExist(err)
}
|
package main
import (
"fmt"
"sort"
"strings"
"testing"
)
type column []int
type columns []column
func (slice columns) Len() int { return len(slice) }
func (slice columns) Less(i, j int) bool {
var k int
for k < len(slice[i])-1 && slice[i][k] == slice[j][k] {
k++
}
return slice[i][k] < slice[j][k]
}
func (slice columns) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] }
func TestSortMatrix(t *testing.T) {
for k, v := range map[string]string{
"-3 29 -3 | -17 69 -17 | 44 3 8": "-3 -3 29 | -17 -17 69 | 8 44 3",
"25 39 -26 -21 | -81 -98 -91 27 | 32 -87 67 98 | -90 -79 18 9": "-26 -21 25 39 | -91 27 -81 -98 | 67 98 32 -87 | 18 9 -90 -79",
"26 -10 39 | -62 66 97 | 22 85 36": "-10 26 39 | 66 -62 97 | 85 22 36"} {
if r := sortMatrix(k); r != v {
t.Errorf("failed: sortMatrix %s is %s, got %s",
k, v, r)
}
}
}
func sortMatrix(q string) string {
var i, j int
s := strings.Split(q, " | ")
n := strings.Count(s[0], " ") + 1
m := make([]column, n)
for i = 0; i < n; i++ {
m[i] = make(column, n)
}
for i = 0; i < n; i++ {
t := strings.Fields(s[i])
for j = 0; j < n; j++ {
fmt.Sscan(t[j], &m[j][i])
}
}
sort.Sort(columns(m))
r, t := make([]string, n), make([]string, n)
for i = 0; i < n; i++ {
for j = 0; j < n; j++ {
t[j] = fmt.Sprint(m[j][i])
}
r[i] = strings.Join(t, " ")
}
return strings.Join(r, " | ")
}
|
package leetcode
func firstUniqChar(s string) byte {
cnt := [26]int{}
for _, ch := range s {
cnt[ch-'a']++
}
for i, ch := range s {
if cnt[ch-'a'] == 1 {
return s[i]
}
}
return ' '
}
|
package gcp
import (
"encoding/json"
compute "google.golang.org/api/compute/v1"
)
// ComputeSubnetworkResource represents a Google Compute Engine subnetwork
type ComputeSubnetworkResource struct {
s *compute.Subnetwork
}
// NewComputeSubnetworkResource returns a new ComputeSubnetworkResource
func NewComputeSubnetworkResource(s *compute.Subnetwork) *ComputeSubnetworkResource {
r := new(ComputeSubnetworkResource)
r.s = s
return r
}
// Name returns the name of the Compute subnetwork
func (r *ComputeSubnetworkResource) Name() string {
return r.s.Name
}
// Region returns the GCP region of the Compute subnetwork
func (r *ComputeSubnetworkResource) Region() string {
return r.s.Region
}
// Marshal returns the underlying resource's JSON representation
func (r *ComputeSubnetworkResource) Marshal() ([]byte, error) {
return json.Marshal(&r.s)
}
// IsPrivateGoogleAccessEnabled returns whether private Google network access is enabled
func (r *ComputeSubnetworkResource) IsPrivateGoogleAccessEnabled() bool {
return r.s.PrivateIpGoogleAccess
}
// IsFlowLogsEnabled returns whether the subnet has VPC flow logs enabled
func (r *ComputeSubnetworkResource) IsFlowLogsEnabled() bool {
return r.s.EnableFlowLogs
}
|
package event
import "github.com/ionous/sashimi/util/ident"
// Proc implements IEvent
type Proc struct {
msg *Message
currentTarget ITarget
phase Phase
cancelled bool
stopMore bool
stopNow bool
path PathList
target ITarget
}
//
func (evt *Proc) sendToTarget(loc ITarget) (err error) {
evt.currentTarget = loc
return evt.currentTarget.TargetDispatch(evt)
}
//
func (evt *Proc) Id() ident.Id {
return evt.msg.Id
}
//
func (evt *Proc) Data() interface{} {
return evt.msg.Data
}
//
func (evt *Proc) Bubbles() bool {
return !evt.msg.CaptureOnly
}
//
func (evt *Proc) Cancelable() bool {
return !evt.msg.CantCancel
}
//
func (evt *Proc) DefaultBlocked() bool {
return evt.cancelled
}
//
func (evt *Proc) Target() ITarget {
return evt.target
}
//
func (evt *Proc) Path() PathList {
return evt.path
}
//
func (evt *Proc) Phase() Phase {
return evt.phase
}
//
func (evt *Proc) CurrentTarget() ITarget {
return evt.currentTarget
}
//
func (evt *Proc) PreventDefault() bool {
if !evt.msg.CantCancel {
evt.cancelled = true
}
return evt.cancelled
}
//
func (evt *Proc) StopPropagation() {
evt.stopMore = true
}
//
func (evt *Proc) StopImmediatePropagation() {
evt.stopNow = true
evt.stopMore = true
}
|
package selfhosted
import (
"context"
"regexp"
"strconv"
"time"
"gopkg.in/mcuadros/go-syslog.v2"
"github.com/pganalyze/collector/util"
)
var logLinePartsRegexp = regexp.MustCompile(`^\[(\d+)-(\d+)\] (.*)`)
var logLineNumberPartsRegexp = regexp.MustCompile(`^\[(\d+)-(\d+)\]$`)
func setupSyslogHandler(ctx context.Context, logSyslogServer string, out chan<- SelfHostedLogStreamItem, prefixedLogger *util.Logger) error {
channel := make(syslog.LogPartsChannel)
handler := syslog.NewChannelHandler(channel)
server := syslog.NewServer()
server.SetFormat(syslog.RFC5424)
server.SetHandler(handler)
err := server.ListenTCP(logSyslogServer)
if err != nil {
return err
}
server.Boot()
go func(ctx context.Context, server *syslog.Server, channel syslog.LogPartsChannel) {
for {
select {
case logParts := <-channel:
item := SelfHostedLogStreamItem{}
item.OccurredAt, _ = logParts["timestamp"].(time.Time)
pidStr, _ := logParts["proc_id"].(string)
if s, err := strconv.ParseInt(pidStr, 10, 32); err == nil {
item.BackendPid = int32(s)
}
logLine, _ := logParts["message"].(string)
logLineParts := logLinePartsRegexp.FindStringSubmatch(logLine)
if len(logLineParts) != 0 {
if s, err := strconv.ParseInt(logLineParts[1], 10, 32); err == nil {
item.LogLineNumber = int32(s)
}
if s, err := strconv.ParseInt(logLineParts[2], 10, 32); err == nil {
item.LogLineNumberChunk = int32(s)
}
item.Line = logLineParts[3]
} else {
item.Line = logLine
logLineNumberStr, _ := logParts["structured_data"].(string)
logLineNumberParts := logLineNumberPartsRegexp.FindStringSubmatch(logLineNumberStr)
if len(logLineNumberParts) != 0 {
if s, err := strconv.ParseInt(logLineNumberParts[1], 10, 32); err == nil {
item.LogLineNumber = int32(s)
}
if s, err := strconv.ParseInt(logLineNumberParts[2], 10, 32); err == nil {
item.LogLineNumberChunk = int32(s)
}
}
}
out <- item
// TODO: Support using the same syslog server for different source Postgres servers,
// and disambiguate based on logParts["client"]
case <-ctx.Done():
server.Kill()
break
}
}
}(ctx, server, channel)
return nil
}
|
package datastore
import "github.com/globalsign/mgo/bson"
func (p *PeopleDAO) FindAll() ([]Person, error) {
var people []Person
err := db.C(COLLECTION).Find(bson.M{}).All(&people)
return people, err
}
func (p *PeopleDAO) FindById(personId string) (Person, error) {
var person Person
err := db.C(COLLECTION).FindId(bson.ObjectIdHex(personId)).One(&person)
return person, err
}
func (p *PeopleDAO) Insert(person Person) error {
err := db.C(COLLECTION).Insert(&person)
return err
}
func (p *PeopleDAO) Delete(personId string) error {
err := db.C(COLLECTION).RemoveId(bson.ObjectIdHex(personId))
return err
}
func (p *PeopleDAO) Update(person Person) error {
err := db.C(COLLECTION).UpdateId(person.ID, &person)
return err
}
|
package service
import (
user_store "github.com/torinos-io/api/store/user_store"
"github.com/torinos-io/api/type/model"
"github.com/torinos-io/api/type/system"
)
// Context holds interfaces of external services
type Context struct {
UserStore user_store.Store
Config *system.Config
}
// Service is an interface for authentication
type Service interface {
Find(req *FindRequest) (*model.User, error)
Save(req *SaveRequest) (*model.User, error)
GetAuthorization() *GetAuthorizationResponse
FindByAccessToken(token string) (*model.User, error)
}
type service struct {
Context
}
// New creates a new service instance from the context
func New(c Context) Service {
return &service{
Context: c,
}
}
|
package wkb
import (
"testing"
"github.com/paulmach/orb"
"github.com/paulmach/orb/encoding/internal/wkbcommon"
)
var (
testPoint = orb.Point{-117.15906619141342, 32.71628524142945}
testPointData = []byte{
//01 02 03 04 05 06 07 08
0x01, 0x01, 0x00, 0x00, 0x00,
0x46, 0x81, 0xF6, 0x23, 0x2E, 0x4A, 0x5D, 0xC0,
0x03, 0x46, 0x1B, 0x3C, 0xAF, 0x5B, 0x40, 0x40,
}
)
func TestPoint(t *testing.T) {
cases := []struct {
name string
data []byte
expected orb.Point
}{
{
name: "point",
data: testPointData,
expected: testPoint,
},
{
name: "little endian",
data: []byte{1, 1, 0, 0, 0, 15, 152, 60, 227, 24, 157, 94, 192, 205, 11, 17, 39, 128, 222, 66, 64},
expected: orb.Point{-122.4546440212, 37.7382859071},
},
{
name: "big endian",
data: []byte{0, 0, 0, 0, 1, 192, 94, 157, 24, 227, 60, 152, 15, 64, 66, 222, 128, 39, 17, 11, 205},
expected: orb.Point{-122.4546440212, 37.7382859071},
},
{
name: "another point",
data: []byte{1, 1, 0, 0, 0, 253, 104, 56, 101, 110, 114, 87, 192, 192, 9, 133, 8, 56, 50, 64, 64},
expected: orb.Point{-93.787988, 32.392335},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
compare(t, tc.expected, tc.data)
})
}
}
func TestPointToHex(t *testing.T) {
cases := []struct {
name string
data orb.Point
expected string
}{
{
name: "point",
data: orb.Point{1, 2},
expected: "0101000000000000000000f03f0000000000000040",
},
{
name: "zero point",
data: orb.Point{0, 0},
expected: "010100000000000000000000000000000000000000",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := MustMarshalToHex(tc.data)
if s != tc.expected {
t.Errorf("incorrect hex: %v", s)
}
})
}
}
var (
testMultiPoint = orb.MultiPoint{{10, 40}, {40, 30}, {20, 20}, {30, 10}}
testMultiPointData = []byte{
0x01, 0x04, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, // Number of Points (4)
0x01, // Byte Order Little
0x01, 0x00, 0x00, 0x00, // Type Point (1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40, // X1 10
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x40, // Y1 40
0x01, // Byte Order Little
0x01, 0x00, 0x00, 0x00, // Type Point (1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x40, // X2 40
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x40, // Y2 30
0x01, // Byte Order Little
0x01, 0x00, 0x00, 0x00, // Type Point (1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x40, // X3 20
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x40, // Y3 20
0x01, // Byte Order Little
0x01, 0x00, 0x00, 0x00, // Type Point (1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x40, // X4 30
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40, // Y4 10
}
testMultiPointSingle = orb.MultiPoint{{10, 40}}
testMultiPointSingleData = []byte{
0x01, 0x04, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, // Number of Points (4)
0x01, // Byte Order Little
0x01, 0x00, 0x00, 0x00, // Type Point (1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40, // X1 10
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x40, // Y1 40
}
)
func TestMultiPoint(t *testing.T) {
large := orb.MultiPoint{}
for i := 0; i < wkbcommon.MaxPointsAlloc+100; i++ {
large = append(large, orb.Point{float64(i), float64(-i)})
}
cases := []struct {
name string
data []byte
expected orb.MultiPoint
}{
{
name: "multi point",
data: testMultiPointData,
expected: testMultiPoint,
},
{
name: "single multi point",
data: testMultiPointSingleData,
expected: testMultiPointSingle,
},
{
name: "large multi point",
data: MustMarshal(large),
expected: large,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
compare(t, tc.expected, tc.data)
})
}
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package rpc_test
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/bitmark-inc/bitmarkd/announce/fingerprint"
"github.com/bitmark-inc/bitmarkd/announce/parameter"
"github.com/bitmark-inc/bitmarkd/announce/rpc"
"github.com/bitmark-inc/bitmarkd/fault"
)
func TestSet(t *testing.T) {
r := rpc.New()
f := fingerprint.Fingerprint{1, 2, 3, 4}
startIndex := uint64(0)
err := r.Set(f, []byte{5, 6, 7, 8})
assert.Nil(t, err, "wrong initialised")
entries, start, err := r.Fetch(startIndex, 10)
assert.Nil(t, err, "wrong fetch")
assert.Equal(t, startIndex+1, start, "wrong start")
assert.Equal(t, 1, len(entries), "wrong entries count")
assert.Equal(t, f, entries[0].Fingerprint, "wrong fingerprint")
}
func TestSetWhenRepeat(t *testing.T) {
r := rpc.New()
f := fingerprint.Fingerprint{1, 2, 3, 4}
err := r.Set(f, []byte{5, 6, 7, 8})
assert.Nil(t, err, "wrong initialised")
err = r.Set(f, []byte{5, 6, 7, 8})
assert.Equal(t, fault.AlreadyInitialised, err, "wrong second initialised")
}
func TestAdd(t *testing.T) {
r := rpc.New()
fp := make([]byte, 32)
fp[0] = 1
b := []byte{6, 7, 8, 9}
startIndex := uint64(0)
added := r.Add(fp, b, uint64(time.Now().Unix()))
assert.True(t, added, "wrong add")
rpcs, start, err := r.Fetch(startIndex, 10)
assert.Nil(t, err, "wrong fetch")
assert.Equal(t, 1, len(rpcs), "wrong list")
assert.Equal(t, startIndex+1, start, "")
assert.Equal(t, fingerprint.Fingerprint{1}, rpcs[0].Fingerprint, "wrong fingerprint")
}
func TestAddWhenExpired(t *testing.T) {
r := rpc.New()
fp := make([]byte, 32)
fp[0] = 1
b := []byte{6, 7, 8, 9}
added := r.Add(fp, b, uint64(0))
assert.False(t, added, "wrong add")
}
func TestAddWhenInvalidFingerprint(t *testing.T) {
r := rpc.New()
fp := make([]byte, 30)
fp[0] = 1
b := []byte{6, 7, 8, 9}
added := r.Add(fp, b, uint64(time.Now().Unix()))
assert.False(t, added, "wrong add")
}
func TestAddWhenInvalidRPC(t *testing.T) {
r := rpc.New()
fp := make([]byte, 32)
fp[0] = 1
b := make([]byte, 200)
b[0] = 5
added := r.Add(fp, b, uint64(time.Now().Unix()))
assert.False(t, added, "wrong add")
}
func TestFetchWhenStartTooLarge(t *testing.T) {
r := rpc.New()
fp := make([]byte, 32)
fp[0] = 1
added := r.Add(fp, []byte{6, 7, 8, 9, 10}, uint64(time.Now().Unix()))
assert.True(t, added, "wrong add")
nodes, start, err := r.Fetch(uint64(5), 10)
assert.Nil(t, err, "wrong fetch")
assert.Equal(t, 0, len(nodes), "wrong list")
assert.Equal(t, uint64(0), start, "wrong start")
}
func TestFetchWhenCountLessZero(t *testing.T) {
r := rpc.New()
fp := make([]byte, 32)
fp[0] = 1
added := r.Add(fp, []byte{6, 7, 8, 9, 10}, uint64(time.Now().Unix()))
assert.True(t, added, "wrong add")
_, _, err := r.Fetch(uint64(5), -1)
assert.Equal(t, fault.InvalidCount, err, "wrong fetch")
}
func TestExpire(t *testing.T) {
r := rpc.New()
fp1 := make([]byte, 32)
fp1[0] = 1
b := []byte{6, 7, 8, 9}
now := time.Now()
startIndex := uint64(0)
_ = r.Add(fp1, b, uint64(now.Unix()))
fp2 := make([]byte, 32)
fp2[0] = 2
expiredTime := now.Add(-1 * (parameter.ExpiryInterval - time.Second))
_ = r.Add(fp2, b, uint64(expiredTime.Unix()))
entries, start, err := r.Fetch(startIndex, 10)
assert.Nil(t, err, "wrong fetch")
assert.Equal(t, 2, len(entries), "wrong entry count")
assert.Equal(t, startIndex+2, start, "wrong start")
time.Sleep(time.Second)
r.Expire()
entries, start, err = r.Fetch(startIndex, 10)
assert.Nil(t, err, "wrong fetch")
assert.Equal(t, 1, len(entries), "wrong entry count")
assert.Equal(t, startIndex+1, start, "wrong start")
}
func TestIsSet(t *testing.T) {
r := rpc.New()
assert.False(t, r.IsInitialised(), "wrong initialised")
err := r.Set(fingerprint.Fingerprint{1, 2, 3, 4}, []byte{5, 6, 7, 8})
assert.Nil(t, err, "wrong initialised")
assert.True(t, r.IsInitialised(), "wrong initialised")
}
func TestSelf(t *testing.T) {
r := rpc.New()
b := []byte{5, 6, 7, 8}
_ = r.Set(fingerprint.Fingerprint{1, 2, 3, 4}, b)
assert.Equal(t, b, r.Self(), "wrong self")
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package arc
import (
"context"
"time"
"chromiumos/tast/common/android/ui"
"chromiumos/tast/errors"
"chromiumos/tast/local/bundles/cros/arc/standardizedtestutil"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
func init() {
testing.AddTest(&testing.Test{
Func: StandardizedTrackpadZoom,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Functional test that installs an app and tests standard trackpad zoom in and zoom out functionality. Tests are only performed in clamshell mode as tablets don't support the trackpad",
Contacts: []string{"davidwelling@google.com", "cros-appcompat-test-team@google.com"},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"chrome", "no_chrome_dcheck"},
Timeout: 10 * time.Minute,
Fixture: "arcBooted",
Params: []testing.Param{
{
Val: standardizedtestutil.GetClamshellTest(runStandardizedTrackpadZoomTest),
ExtraSoftwareDeps: []string{"android_p"},
ExtraHardwareDeps: hwdep.D(standardizedtestutil.ClamshellHardwareDep),
}, {
Name: "vm",
Val: standardizedtestutil.GetClamshellTest(runStandardizedTrackpadZoomTest),
ExtraSoftwareDeps: []string{"android_vm"},
ExtraHardwareDeps: hwdep.D(standardizedtestutil.ClamshellHardwareDep),
}},
})
}
func StandardizedTrackpadZoom(ctx context.Context, s *testing.State) {
const (
apkName = "ArcStandardizedInputTest.apk"
appName = "org.chromium.arc.testapp.arcstandardizedinputtest"
activityName = ".ZoomTestActivity"
)
t := s.Param().(standardizedtestutil.Test)
standardizedtestutil.RunTest(ctx, s, apkName, appName, activityName, t)
}
func runStandardizedTrackpadZoomTest(ctx context.Context, testParameters standardizedtestutil.TestFuncParams) error {
txtZoomID := testParameters.AppPkgName + ":id/txtZoom"
txtZoomSelector := testParameters.Device.Object(ui.ID(txtZoomID))
txtZoomInStateID := testParameters.AppPkgName + ":id/txtZoomInState"
zoomInSuccessLabelSelector := testParameters.Device.Object(ui.ID(txtZoomInStateID), ui.Text("ZOOM IN: COMPLETE"))
txtZoomOutStateID := testParameters.AppPkgName + ":id/txtZoomOutState"
zoomOutSuccessLabelSelector := testParameters.Device.Object(ui.ID(txtZoomOutStateID), ui.Text("ZOOM OUT: COMPLETE"))
trackpad, err := input.Trackpad(ctx)
if err != nil {
return errors.Wrap(err, "failed to initialize the trackpad")
}
defer trackpad.Close()
if err := txtZoomSelector.WaitForExists(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to find the element to zoom in on")
}
// No labels should be in their complete state before the tests begin.
if err := zoomInSuccessLabelSelector.WaitUntilGone(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom in success label does not yet exist")
}
if err := zoomOutSuccessLabelSelector.WaitUntilGone(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom out success label does not yet exist")
}
// After the zoom in, only the zoom in label should be in the success state.
if err := standardizedtestutil.TrackpadZoom(ctx, trackpad, testParameters, txtZoomSelector, standardizedtestutil.ZoomIn); err != nil {
return errors.Wrap(err, "failed to perform the zoom")
}
if err := zoomInSuccessLabelSelector.WaitForExists(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom in success label exists")
}
if err := zoomOutSuccessLabelSelector.WaitUntilGone(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom out success label does not yet exist")
}
// After the zoom out, all zoom labels should be in the success state.
if err := standardizedtestutil.TrackpadZoom(ctx, trackpad, testParameters, txtZoomSelector, standardizedtestutil.ZoomOut); err != nil {
return errors.Wrap(err, "failed to perform the zoom")
}
if err := zoomInSuccessLabelSelector.WaitForExists(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom in success label exists")
}
if err := zoomOutSuccessLabelSelector.WaitForExists(ctx, standardizedtestutil.ShortUITimeout); err != nil {
return errors.Wrap(err, "failed to verify the zoom out success label exists")
}
return nil
}
|
package model
var Configurationins AppConfigs
type AppConfigs struct {
Server struct {
Mode string `yaml:"mode"`
Port string `yaml:"port"`
}
Database struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
Sslmode string `yaml:"sslmode"`
Dbname string `yaml:"dbname"`
Host string `yaml:"host"`
Port string `yaml:"port"`
}
Migration struct {
Sourceurl string `yaml:"sourceurl"`
Databaseurl string `yaml:"databaseurl"`
}
}
|
package session
import (
"context"
"gamesvr/manager"
"shared/protobuf/pb"
"shared/utility/errors"
)
func (s *Session) RPCGuildIsDissolved(ctx context.Context) (*pb.GuildIsDissolvedResp, error) {
resp, err := manager.RPCGuildClient.IsDissolved(ctx, &pb.GuildIsDissolvedReq{
GuildID: s.Guild.GuildID,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildRecommend(ctx context.Context) (*pb.GuildRecommendResp, error) {
resp, err := manager.RPCGuildClient.Recommend(ctx, &pb.GuildRecommendReq{})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildSync(ctx context.Context, status int32) (*pb.GuildSyncResp, error) {
resp, err := manager.RPCGuildClient.Sync(ctx, &pb.GuildSyncReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
LastLoginTime: s.Info.LastLoginTime,
Status: status,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildShowInfo(ctx context.Context, id int64) (*pb.GuildShowInfoResp, error) {
resp, err := manager.RPCGuildClient.ShowInfo(ctx, &pb.GuildShowInfoReq{
GuildID: id,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildInfo(ctx context.Context) (*pb.GuildInfoResp, error) {
req := &pb.GuildInfoReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.Info(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildCreate(ctx context.Context, name string, icon *pb.VOGuildIcon, joinModel int32, title string) (*pb.GuildCreateResp, error) {
req := &pb.GuildCreateReq{
GuildID: 0,
UserID: s.ID,
Name: name,
Icon: icon,
Title: title,
JoinModel: joinModel,
}
resp, err := manager.RPCGuildClient.Create(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildDissolve(ctx context.Context) (*pb.GuildDissolveResp, error) {
req := &pb.GuildDissolveReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.Dissolve(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildCancelDissolve(ctx context.Context) (*pb.GuildCancelDissolveResp, error) {
req := &pb.GuildCancelDissolveReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.CancelDissolve(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildApply(ctx context.Context, guildID int64) (*pb.GuildApplyResp, error) {
// err := manager.RPCGuildClient.SetSinglecastID(ctx, guildID)
// if err != nil {
// return nil, errors.WrapTrace(err)
// }
resp, err := manager.RPCGuildClient.Apply(ctx, &pb.GuildApplyReq{
GuildID: guildID,
UserID: s.ID,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildCancelApply(ctx context.Context, guildID int64) (*pb.GuildCancelApplyResp, error) {
// err := manager.RPCGuildClient.SetSinglecastID(ctx, guildID)
// if err != nil {
// return nil, errors.WrapTrace(err)
// }
resp, err := manager.RPCGuildClient.CancelApply(ctx, &pb.GuildCancelApplyReq{
GuildID: guildID,
UserID: s.ID,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildQuit(ctx context.Context) (*pb.GuildQuitResp, error) {
req := &pb.GuildQuitReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.Quit(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildHandleApplied(ctx context.Context, approve, refuse []int64) (*pb.GuildHandleAppliedResp, error) {
req := &pb.GuildHandleAppliedReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Approve: approve,
Refuse: refuse,
}
resp, err := manager.RPCGuildClient.HandleApplied(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildKick(ctx context.Context, userID int64) (*pb.GuildKickResp, error) {
req := &pb.GuildKickReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
KickedUserID: userID,
}
resp, err := manager.RPCGuildClient.Kick(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildSendGroupMail(ctx context.Context, title, content string) (*pb.GuildSendGroupMailResp, error) {
req := &pb.GuildSendGroupMailReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Title: title,
Content: content,
Sender: s.Name,
}
resp, err := manager.RPCGuildClient.SendGroupMail(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildChat(ctx context.Context, content string) (*pb.GuildChatResp, error) {
req := &pb.GuildChatReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
UserName: s.Name,
Content: content,
Avatar: s.Info.Avatar,
Frame: s.Info.Frame,
}
resp, err := manager.RPCGuildClient.Chat(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildPromotion(ctx context.Context, target int64) (*pb.GuildPromotionResp, error) {
req := &pb.GuildPromotionReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Target: target,
}
resp, err := manager.RPCGuildClient.Promotion(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildGetApplyList(ctx context.Context) (*pb.GuildGetApplyListResp, error) {
req := &pb.GuildGetApplyListReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.GetApplyList(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildDemotion(ctx context.Context, target int64) (*pb.GuildDemotionResp, error) {
req := &pb.GuildDemotionReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Target: target,
}
resp, err := manager.RPCGuildClient.Demotion(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildTransfer(ctx context.Context, target int64) (*pb.GuildTransferResp, error) {
req := &pb.GuildTransferReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Target: target,
}
resp, err := manager.RPCGuildClient.Transfer(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildMembers(ctx context.Context) (*pb.GuildMembersResp, error) {
req := &pb.GuildMembersReq{
GuildID: s.Guild.GuildID,
}
resp, err := manager.RPCGuildClient.Members(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
// ----------------联合建造------------------
func (s *Session) RPCGuildCoBuildGetInfo(ctx context.Context, buildID int32) (*pb.GuildCoBuildGetInfoResp, error) {
req := &pb.GuildCoBuildGetInfoReq{
GuildID: s.Guild.GuildID,
BuildID: buildID,
}
resp, err := manager.RPCGuildClient.CoBuildGetInfo(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildCoBuildImprove(ctx context.Context, buildID int32) (*pb.GuildCoBuildImproveResp, error) {
req := &pb.GuildCoBuildImproveReq{
GuildID: s.Guild.GuildID,
BuildID: buildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.CoBuildImprove(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildCoBuildUse(ctx context.Context, buildID int32) (*pb.GuildCoBuildUseResp, error) {
req := &pb.GuildCoBuildUseReq{
GuildID: s.Guild.GuildID,
BuildID: buildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.CoBuildUse(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
// -------------------派遣---------------------
// todo 调用之前需要判断玩家是否有公会
// func (s *Session) RPCGuildGetDispatchCharac(ctx context.Context, characId int32) (*pb.GuildGetDispatchCharacResp, error) {
// req := &pb.GuildGetDispatchCharacReq{
// GuildID: s.Guild.GuildID,
// CharacterId: characId,
// }
// // fmt.Println("=========guildId, ", s.Guild.GuildID)
// resp, err := manager.RPCGuildClient.GetDispatchCharac(balancer.WithContext(ctx, &balancer.Context{
// ID: s.Guild.GuildID,
// Server: "",
// }), req)
// if err != nil {
// return nil, errors.WrapTrace(err)
// }
// return resp, nil
// }
// -----------------异界问候----------------------
func (s *Session) RPCGuildAddGreetings(ctx context.Context, greetings []*pb.VOGreetings) (*pb.GuildAddGreetingsResp, error) {
resp, err := manager.RPCGuildClient.AddGreetings(ctx, &pb.GuildAddGreetingsReq{
GuildID: s.Guild.GuildID,
UserId: s.GetUserId(),
Greetings: greetings,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildGetGreetings(ctx context.Context) (*pb.GuildGetGreetingsResp, error) {
resp, err := manager.RPCGuildClient.GetGreetings(ctx, &pb.GuildGetGreetingsReq{
GuildID: s.Guild.GuildID,
UserId: s.GetUserId(),
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildUpdateGreetings(ctx context.Context, lastTimestamp int64) (*pb.GuildUpdateGreetingsResp, error) {
resp, err := manager.RPCGuildClient.UpdateGreetingsRecord(ctx, &pb.GuildUpdateGreetingsReq{
GuildID: s.Guild.GuildID,
UserId: s.GetUserId(),
LastTimestamp: lastTimestamp,
})
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
// -----------------公会互助----------------------
func (s *Session) RPCGuildAddGraveyardRequest(ctx context.Context, add *pb.VOAddGraveyardRequest) (*pb.GuildAddGraveyardRequestResp, error) {
req := &pb.GuildAddGraveyardRequestReq{
GuildID: s.Guild.GuildID,
Add: add,
}
resp, err := manager.RPCGuildClient.AddGraveyardRequest(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildGetGraveyardRequests(ctx context.Context) (*pb.GuildGetGraveyardRequestsResp, error) {
req := &pb.GuildGetGraveyardRequestsReq{
GuildID: s.Guild.GuildID,
UserId: s.ID,
}
resp, err := manager.RPCGuildClient.GetGraveyardRequests(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildHelpRequestsHandle(ctx context.Context) (*pb.GuildHelpRequestsHandleResp, error) {
req := &pb.GuildHelpRequestsHandleReq{
GuildID: s.Guild.GuildID,
UserId: s.ID,
DailyAddActivation: s.Graveyard.DailyAddActivationByHelp,
DailyAddGold: s.Graveyard.DailyGuildGoldByHelp,
}
resp, err := manager.RPCGuildClient.HelpRequestsHandle(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildGetElite(ctx context.Context) (*pb.GuildGetElitesResp, error) {
req := &pb.GuildGetElitesReq{
GuildId: s.Guild.GuildID,
}
resp, err := manager.RPCGuildClient.GetElites(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildRecommendInfo(ctx context.Context, guildId int64) (*pb.GuildRecommendInfoResp, error) {
req := &pb.GuildRecommendInfoReq{
GuildId: guildId,
}
resp, err := manager.RPCGuildClient.RecommendInfo(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
// --------------公会任务-------------------
func (s *Session) RPCGuildTaskList(ctx context.Context) (*pb.GuildTaskListResp, error) {
req := &pb.GuildTaskListReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
}
resp, err := manager.RPCGuildClient.GetTaskList(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildTaskRewards(ctx context.Context, taskId int32) (*pb.GuildTaskRewardsResp, error) {
req := &pb.GuildTaskRewardsReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
TaskId: taskId,
}
resp, err := manager.RPCGuildClient.TaskRewards(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildTaskAddProgress(ctx context.Context, tasks []*pb.VOGuildTaskItem) (*pb.GuildTaskAddProgressResp, error) {
req := &pb.GuildTaskAddProgressReq{
GuildID: s.Guild.GuildID,
UserID: s.ID,
Items: tasks,
}
resp, err := manager.RPCGuildClient.TaskAddProgress(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
func (s *Session) RPCGuildModify(ctx context.Context, icon *pb.VOGuildIcon, joinModel int32, title string) (*pb.GuildModifyResp, error) {
req := &pb.GuildModifyReq{
GuildId: s.Guild.GuildID,
UserId: s.ID,
Icon: icon,
JoinModel: joinModel,
Title: title,
}
resp, err := manager.RPCGuildClient.Modify(ctx, req)
if err != nil {
return nil, errors.WrapTrace(err)
}
return resp, nil
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package inputs
import (
"bufio"
"context"
"io"
"io/ioutil"
"math"
"net/http"
"net/http/httptest"
"regexp"
"time"
"chromiumos/tast/common/testexec"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/display"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
const (
slpS0File = "/sys/kernel/debug/pmc_core/slp_s0_residency_usec"
packageCStateFile = "/sys/kernel/debug/pmc_core/package_cstate_show"
)
var (
c10PackageRe = regexp.MustCompile(`C10 : ([A-Za-z0-9]+)`)
suspendFailureRe = regexp.MustCompile("Suspend failures: 0")
firmwareLogErrorRe = regexp.MustCompile("Firmware log errors: 0")
s0ixErrorRe = regexp.MustCompile("s0ix errors: 0")
evtestRe = regexp.MustCompile(`Event.*time.*code\s(\d*)\s\(` + `ABS_MT_POSITION_X` + `\)`)
)
func init() {
testing.AddTest(&testing.Test{
Func: TouchSuspendResume,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Touchscreen: suspend-resume with operation for 10 cycles",
Contacts: []string{"ambalavanan.m.m@intel.com", "intel-chrome-system-automation-team@intel.com"},
SoftwareDeps: []string{"chrome"},
Data: []string{"canvas.html"},
HardwareDeps: hwdep.D(hwdep.TouchScreen(), hwdep.X86()),
Fixture: "chromeLoggedIn",
})
}
func TouchSuspendResume(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(chrome.HasChrome).Chrome()
srv := httptest.NewServer(http.FileServer(s.DataFileSystem()))
defer srv.Close()
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to open Test API connection: ", err)
}
info, err := display.GetInternalInfo(ctx, tconn)
if err != nil {
s.Fatal("Failed to get Internal display info: ", err)
}
cmd, stdout, err := deviceScanner(ctx)
if err != nil {
s.Fatal("Failed to get touchscreen scanner: ", err)
}
defer cmd.Wait()
defer cmd.Kill()
scannerTouchscreen := bufio.NewScanner(stdout)
if err := performEVTest(ctx, info, cr, scannerTouchscreen, srv.URL); err != nil {
s.Fatal("Failed to perform evtest: ", err)
}
cmdOutput := func(file string) string {
out, err := ioutil.ReadFile(file)
if err != nil {
s.Fatalf("Failed to read %q file: %v", file, err)
}
return string(out)
}
slpPreString := cmdOutput(slpS0File)
pkgOpSetOutput := cmdOutput(packageCStateFile)
matchSetPre := c10PackageRe.FindStringSubmatch(pkgOpSetOutput)
if matchSetPre == nil {
s.Fatal("Failed to match pre PkgCstate value: ", pkgOpSetOutput)
}
pkgOpSetPre := matchSetPre[1]
s.Log("Executing suspend_stress_test for 10 cycles")
stressOut, err := testexec.CommandContext(ctx, "suspend_stress_test", "-c", "10").Output()
if err != nil {
s.Fatal("Failed to execute suspend_stress_test command: ", err)
}
suspendErrors := []*regexp.Regexp{suspendFailureRe, firmwareLogErrorRe, s0ixErrorRe}
for _, errmsg := range suspendErrors {
if !(errmsg.MatchString(string(stressOut))) {
s.Fatalf("Failed expected %q, but failures are non-zero", errmsg)
}
}
// re-establishing chrome connection to DUT.
if err := cr.Reconnect(ctx); err != nil {
s.Fatal("Failed to reconnect to the Chrome session: ", err)
}
if err := performEVTest(ctx, info, cr, scannerTouchscreen, srv.URL); err != nil {
s.Fatal("Failed to perform evtest: ", err)
}
if err := assertSLPCounter(slpPreString); err != nil {
s.Fatal("Failed to assert SLP counter: ", err)
}
if err := assertPackageCState(pkgOpSetPre); err != nil {
s.Fatal("Failed to assert package C-State: ", err)
}
}
// performEVTest launches the offline canvas, draw on the canvas using touch and
// monitors the touch events in evtest.
func performEVTest(ctx context.Context, info *display.Info, cr *chrome.Chrome, scanner *bufio.Scanner, testServerURL string) error {
if err := launchCanvas(ctx, cr, testServerURL); err != nil {
return errors.Wrap(err, "failed to launch canvas")
}
if err := drawOnCanvas(ctx, info); err != nil {
return errors.Wrap(err, "failed to draw on canvas")
}
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Monitor touchscreen events using evtest.
if err := evtestMonitor(timeoutCtx, scanner); err != nil {
return errors.Wrap(err, "failed during the evtest for touchscreen")
}
return nil
}
// launchCanvas loads the offline canvas.html in browser.
func launchCanvas(ctx context.Context, cr *chrome.Chrome, testServerURL string) error {
conn, err := cr.NewConn(ctx, testServerURL+"/canvas.html")
if err != nil {
return errors.Wrap(err, "failed to load canvas.html")
}
if err := conn.Close(); err != nil {
return errors.Wrap(err, "failed to close connection to browser tab")
}
return nil
}
// assertSLPCounter asserts the SLP counter value post Resume with SLP counter
// value before Suspend.
func assertSLPCounter(slpPreString string) error {
slpOpSetPost, err := ioutil.ReadFile(slpS0File)
if err != nil {
return errors.Wrapf(err, "failed to read %q file", slpS0File)
}
slpPostString := string(slpOpSetPost)
if slpPreString == slpPostString {
return errors.Errorf("failed SLP counter value must be different than the value %q noted most recently %q", slpPreString, slpPostString)
}
if slpPostString == "0" {
return errors.Errorf("failed SLP counter value must be non-zero, noted is: %q", slpOpSetPost)
}
return nil
}
// assertPackageCState asserts the Package C10 value post Resume with Package
// C10 value before Suspend.
func assertPackageCState(pkgOpSetPre string) error {
pkgOpSetPostOutput, err := ioutil.ReadFile(packageCStateFile)
if err != nil {
return errors.Wrapf(err, "failed to read %q file", packageCStateFile)
}
matchSetPost := c10PackageRe.FindStringSubmatch(string(pkgOpSetPostOutput))
if matchSetPost == nil {
return errors.Errorf("failed to match post PkgCstate value: %q", pkgOpSetPostOutput)
}
pkgOpSetPost := matchSetPost[1]
if pkgOpSetPre == pkgOpSetPost {
return errors.Errorf("failed Package C10 value %q must be different than value %q noted most recently", pkgOpSetPre, pkgOpSetPost)
}
if pkgOpSetPost == "0x0" || pkgOpSetPost == "0" {
return errors.Errorf("failed Package C10 = want non-zero, got %s", pkgOpSetPost)
}
return nil
}
// deviceScanner returns the evtest scanner for the touch screen device.
func deviceScanner(ctx context.Context) (*testexec.Cmd, io.Reader, error) {
foundTS, devPath, err := input.FindPhysicalTouchscreen(ctx)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to find device path for the touch screen")
}
if !foundTS {
return nil, nil, errors.New("failed to find physical touch screen")
}
cmd := testexec.CommandContext(ctx, "evtest", devPath)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, errors.Wrap(err, "failed to create stdout pipe")
}
if err := cmd.Start(); err != nil {
return nil, nil, errors.Wrap(err, "failed to start scanner")
}
return cmd, stdout, nil
}
// evtestMonitor is used to check whether events sent to the devices are picked up by the evtest.
func evtestMonitor(ctx context.Context, scanner *bufio.Scanner) error {
text := make(chan string)
go func() {
for scanner.Scan() {
text <- scanner.Text()
}
close(text)
}()
for {
select {
case <-ctx.Done():
return errors.New("failed to detect events within expected time")
case out := <-text:
if evtestRe.MatchString(out) {
return nil
}
}
}
}
// drawOnCanvas draws on the canvas using TouchEventWriter.
func drawOnCanvas(ctx context.Context, info *display.Info) error {
// It is possible to send raw events to the Touchscreen type. But it is
// recommended to use the Touchscreen.TouchEventWriter struct since it
// already has functions to manipulate Touch events.
tsw, err := input.Touchscreen(ctx)
if err != nil {
return errors.Wrap(err, "failed to open touchscreen device")
}
defer tsw.Close()
// Touchscreen bounds: The size of the touchscreen might not be the same
// as the display size. In fact, might be even up to 4x bigger.
touchWidth := tsw.Width()
touchHeight := tsw.Height()
// Display bounds.
displayWidth := float64(info.Bounds.Width)
displayHeight := float64(info.Bounds.Height)
pixelToTouchFactorX := float64(touchWidth) / displayWidth
pixelToTouchFactorY := float64(touchHeight) / displayHeight
centerX := displayWidth * pixelToTouchFactorX / 2
centerY := displayHeight * pixelToTouchFactorY / 2
stw, err := tsw.NewSingleTouchWriter()
if err != nil {
return errors.Wrap(err, "failed to get a new TouchEventWriter")
}
defer stw.Close()
// Draw a dotted line:
// SingleTouchEventWriter is being reused for the 15 dots. The event is "ended" after each touch.
// "End" is equivalent as lifting the finger from the touchscreen.
// Thus generating a "dotted" line, instead of continuous one.
for i := 0; i < 15; i++ {
// Values must be in "touchscreen coordinates", not pixel coordinates.
if err := stw.Move(input.TouchCoord(centerX+float64(i)*50.0), input.TouchCoord(centerY+float64(i)*50.0)); err != nil {
return errors.Wrap(err, "failed to move touch event")
}
if err := stw.End(); err != nil {
return errors.Wrap(err, "failed to end touch event")
}
if err := testing.Sleep(ctx, 100*time.Millisecond); err != nil {
return errors.Wrap(err, "failed to sleep")
}
}
// Draw a circle:
// Draws a circle with 120 touch events. The touch event is moved to
// 120 different locations generating a continuous circle.
const (
radius = 200 // circle radius in pixels
segments = 120 // segments used for the circle
)
for i := 0; i < segments; i++ {
rads := 2.0*math.Pi*(float64(i)/segments) + math.Pi
x := radius * pixelToTouchFactorX * math.Cos(rads)
y := radius * pixelToTouchFactorY * math.Sin(rads)
if err := stw.Move(input.TouchCoord(centerX+x), input.TouchCoord(centerY+y)); err != nil {
return errors.Wrap(err, "failed to move the touch event")
}
if err := testing.Sleep(ctx, 15*time.Millisecond); err != nil {
return errors.Wrap(err, "failed to sleep")
}
}
// And finally "end" (lift the finger) the line.
if err := stw.End(); err != nil {
return errors.Wrap(err, "failed to finish the touch event")
}
// Swipe test:
// Draw a box around the circle using 4 swipes.
const boxSize = radius * 2 // box size in pixels
for _, d := range []struct {
x0, y0, x1, y1 float64
}{
{-1, 1, -1, -1}, // swipe up from bottom-left.
{-1, -1, 1, -1}, // swipe right from top-left.
{1, -1, 1, 1}, // swipe down from top-right.
{1, 1, -1, 1}, // swipe left from bottom-right.
} {
x0 := input.TouchCoord(centerX + boxSize/2*d.x0*pixelToTouchFactorX)
y0 := input.TouchCoord(centerY + boxSize/2*d.y0*pixelToTouchFactorY)
x1 := input.TouchCoord(centerX + boxSize/2*d.x1*pixelToTouchFactorX)
y1 := input.TouchCoord(centerY + boxSize/2*d.y1*pixelToTouchFactorY)
if err := stw.Swipe(ctx, x0, y0, x1, y1, 500*time.Millisecond); err != nil {
return errors.Wrap(err, "failed to run Swipe")
}
}
if err := stw.End(); err != nil {
return errors.Wrap(err, "failed to finish the swipe gesture")
}
return nil
}
|
package cmd
import (
ui "github.com/ernoaapa/eliot/pkg/cmd/ui"
"github.com/ernoaapa/eliot/pkg/progress"
)
// ShowDownloadProgress prints UI "downloading" lines and updates until
// the progress channel closes
func ShowDownloadProgress(progressc <-chan []*progress.ImageFetch) {
lines := map[string]ui.Line{}
for fetches := range progressc {
for _, fetch := range fetches {
if _, ok := lines[fetch.Image]; !ok {
lines[fetch.Image] = ui.NewLine().Loadingf("Download %s", fetch.Image)
}
if fetch.IsDone() {
if fetch.Failed {
lines[fetch.Image].Errorf("Failed %s", fetch.Image)
} else {
lines[fetch.Image].Donef("Downloaded %s", fetch.Image)
}
} else {
current, total := fetch.GetProgress()
lines[fetch.Image].WithProgress(current, total)
}
}
}
for image, line := range lines {
line.Donef("Completed %s", image)
}
}
|
/*
Package json-store reads/writes data to json flat files
Given a top level directory, `Get`, `Put`, and `Del` json encoded flat files of
a given name.
*/
package jsonstore
import (
"encoding/json"
"os"
)
// default dir/file permission
const PERM = 0755
// var MISS = errors.New("File Not Found")
// Bucket holds the name of the directory to which the files are written and
// has all the attached methods
type Bucket struct {
prefix string
}
// NewConnection creates our root data dir
func Open(dir string) (*Bucket, error) {
if len(dir) == 0 {
return &Bucket{""}, nil
}
if dir[len(dir)-1:] == "/" {
dir = dir[:len(dir)-1]
}
if err := os.MkdirAll(dir, PERM); err != nil {
return nil, err
}
return &Bucket{dir}, nil
}
// Get retrieves the contents of the given file and unmarshals it to the given interface.
// To determine if `Get` couldn't find a file use `os.IsNotExist`
func (b Bucket) Get(key string, v interface{}) error {
fh, err := os.Open(b.mkkey(key))
defer fh.Close()
if err != nil {
return err
}
err = json.NewDecoder(fh).Decode(v)
if err != nil {
return err
}
return nil
}
// Put marshals and writes the contents of the given interface to the given file
func (b Bucket) Put(key string, v interface{}) error {
fh, err := os.Create(b.mkkey(key))
defer fh.Close()
if err != nil {
return err
}
err = json.NewEncoder(fh).Encode(v)
if err != nil {
return err
}
return nil
}
// PutRaw assumes the given value is valid JSON and writes it to the given file
func (b Bucket) PutRaw(key string, v []byte) error {
fh, err := os.Create(b.mkkey(key))
defer fh.Close()
_, err = fh.Write(v)
if err != nil {
return err
}
return nil
}
// Del deletes the given file
func (b Bucket) Del(key string) error {
err := os.Remove(b.mkkey(key))
if err != nil {
return err
}
return nil
}
// DellAll deletes the top level data dir
func (b Bucket) DelAll() error {
err := os.RemoveAll(b.prefix)
if err != nil {
return err
}
return nil
}
// mkkey creates the full path to the file given the prefix and the key.
// Assumes you do NOT want to write to "/"
func (b Bucket) mkkey(key string) string {
if len(b.prefix) > 0 {
b.prefix += "/"
}
return b.prefix + key
}
|
package artifactory
import (
"errors"
"sync"
)
// AlreadyPresentInSetErrorMessage is the message returned for AlreadyPresentInSetError errors
const AlreadyPresentInSetErrorMessage = "resource with given path already present in set"
/*
ResourceSet is a thread-safe hash map of resource values. Resources may be added
and their artifacts will be available upon request
*/
type ResourceSet struct {
resources map[string]*Resource
lock sync.RWMutex // for adding new resource objects
}
// NewResourceSet creates a fully initialized ResourceSet
func NewResourceSet() *ResourceSet {
return &ResourceSet{
resources: map[string]*Resource{},
}
}
/*
Add adds resource r to the set. If a resource is already present with the same
path (r.Path), Add will return an IsIsPresentInSetError
*/
func (set *ResourceSet) Add(r *Resource) error {
set.lock.Lock()
defer set.lock.Unlock()
if set.resources[r.Path()] == nil {
set.resources[r.Path()] = r
} else {
return newAlreadyPresentInSetError()
}
return nil
}
// Get returns the resource that exists at path (or nil)
func (set *ResourceSet) Get(path string) *Resource {
set.lock.RLock()
defer set.lock.RUnlock()
return set.resources[path]
}
// AlreadyPresentInSetError is returned on an unsuccessful call to Add()
type AlreadyPresentInSetError error
func newAlreadyPresentInSetError() AlreadyPresentInSetError {
return errors.New(AlreadyPresentInSetErrorMessage)
}
// IsAlreadyPresentInSetError checks if error e is of the type AlreadyPresentInSetError
func IsAlreadyPresentInSetError(e error) bool {
if e == nil {
return false
}
switch e.(type) {
case AlreadyPresentInSetError:
return true
default:
return e.Error() == AlreadyPresentInSetErrorMessage
}
}
// Each iterates over each resource in the set in a threadsafe manner, yielding
// each one to function resourceFunc. If resourceFunc returns an error, that
// error is passed to the subseqwuent invocation.
func (set *ResourceSet) Each(resourceFunc func(r *Resource, error error) error) error {
set.lock.RLock()
defer set.lock.RUnlock()
var err error
for _, resource := range set.resources {
err = resourceFunc(resource, err)
}
return nil
}
|
package typrls
import "github.com/typical-go/typical-go/pkg/typgo"
type (
// Releaser responsible to release (put file to release folder)
Releaser interface {
Release(*Context) error
}
// Releasers for composite release
Releasers []Releaser
// ReleaseFn release function
NewReleaser func(*Context) error
// Context contain data for release
Context struct {
*typgo.Context
Alpha bool
TagName string
ReleaseFolder string
Summary string
}
)
//
// NewReleaser
//
var _ Releaser = (NewReleaser)(nil)
func (r NewReleaser) Release(c *Context) error {
return r(c)
}
//
// Releaser
//
var _ Releaser = (Releasers)(nil)
// Release the releasers
func (r Releasers) Release(c *Context) (err error) {
for _, releaser := range r {
if err = releaser.Release(c); err != nil {
return
}
}
return
}
|
package main
import "fmt"
// docs: https://blog.golang.org/go-maps-in-action
/*
python sample
x = {"A":1, "B":2 }
*/
/*
This variable m is a map of string keys to int values:
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:
m = make(map[string]int)
Maps are not safe for concurrent use
Iteration order is not guaranteed. Go 1 randomized iteration order
*/
func main() {
m := map[string]int {
"ATK":250,
"DEF":200,
}
m["DEX"] = 250
fmt.Println("Basic access ------------- ")
atk, ok := m["ATK"]
fmt.Println(atk,ok)
i, ok := m["SPD"]
fmt.Println(i,ok, ok == false)
//You cannot take the address of a map value because map values are not addressable.
//This restriction is in place because the map implementation may have to move values
// between hash map buckets, so callers must be prevented from taking the address of a map's value.
//p_atk :=&m["ATK"] // error錯誤
fmt.Println("Interation ------------- ")
for key, value := range m {
fmt.Println("Key:", key, "Value:", value)
}
}
|
// Copyright (C) 2017 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.
package stash
import (
"context"
"io"
"os"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/file"
)
type (
// Client is a wrapper over a Service to provice extended client functionality.
Client struct {
Service
}
// Uploadable is the interface used by the UploadStream helper.
// It is a standard io reader with the ability to reset to the start.
Uploadable interface {
io.Reader
Reset() error
}
)
// UploadStream is a helper used to upload a stream to the stash.
// It will return an error if the upload fails, otherwise it will return the stash
// id for the bytes.
func (c *Client) UploadStream(ctx context.Context, info Upload, r Uploadable) (string, error) {
return uploadStream(ctx, c, info, r)
}
// UploadSeekable is a helper used to upload a single seekable stream.
// It will return an error if either the stream cannot be read, or the upload fails, otherwise
// it will return the stash id for the file.
func (c *Client) UploadSeekable(ctx context.Context, info Upload, r io.ReadSeeker) (string, error) {
return uploadStream(ctx, c, info, seekadapter{r})
}
// UploadBytes is a helper used to upload a byte array.
// It will return an error if the upload fails, otherwise it will return the stash id for the file.
func (c *Client) UploadBytes(ctx context.Context, info Upload, data []byte) (string, error) {
return uploadStream(ctx, c, info, &bytesAdapter{data: data})
}
// UploadString is a helper used to upload a string.
// It will return an error if the upload fails, otherwise it will return the stash id for the file.
func (c *Client) UploadString(ctx context.Context, info Upload, content string) (string, error) {
return uploadStream(ctx, c, info, &bytesAdapter{data: ([]byte)(content)})
}
// UploadFile is a helper used to upload a single file to the stash.
// It will return an error if either the file cannot be read, or the upload fails, otherwise
// it will return the stash id for the file.
func (c *Client) UploadFile(ctx context.Context, filename file.Path) (string, error) {
file, err := os.Open(filename.System())
if err != nil {
return "", err
}
defer file.Close()
stat, _ := file.Stat()
info := Upload{
Name: []string{filename.Basename()},
Executable: stat.Mode()&0111 != 0,
}
return uploadStream(ctx, c, info, seekadapter{file})
}
// GetFile retrieves the data for an entity in the given Store and
// saves it to a file.
func (c *Client) GetFile(ctx context.Context, id string, filename file.Path) error {
entity, err := c.Lookup(ctx, id)
if err != nil || entity == nil {
return nil
}
if err := file.Mkdir(filename.Parent()); err != nil {
return log.Err(ctx, err, "file.Path.Mkdir failed")
}
mode := os.FileMode(0644)
if entity.Upload.Executable {
mode = 0755
}
f, err := os.OpenFile(filename.System(), os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
defer f.Close()
r, err := c.Open(ctx, id)
if err != nil {
return err
}
if _, err := io.Copy(f, r); err != nil {
return log.Err(ctx, err, "io.Copy failed")
}
return nil
}
|
package main
import (
"flag"
"fmt"
"net/url"
"os"
"sync"
"github.com/influxdb/influxdb/client"
"github.com/op/go-logging"
)
var log = logging.MustGetLogger("postcache")
func main() {
initLogging()
log.Info("Starting AlertD")
confPath := flag.String("p", "conf.json", "path to config file")
flag.Parse()
var wg sync.WaitGroup
wg.Add(1)
load(*confPath)
wg.Wait()
}
func getInfluxClient(URL string) *client.Client {
url, err := url.Parse(URL)
if err != nil {
log.Fatal(fmt.Sprintf("failed to parse url : %s", err))
}
var clientConf = client.Config{
URL: *url,
}
var influxClient, clientErr = client.NewClient(clientConf)
if clientErr != nil {
log.Fatal(fmt.Sprintf("failed to create influxdb Client : %s", clientErr))
}
return influxClient
}
func initLogging() {
backend := logging.NewLogBackend(os.Stdout, "", 0)
format := logging.MustStringFormatter(
"%{color}%{time:15:04:05.000} >> %{level:.4s} %{color:reset} %{message}",
)
backendFormatter := logging.NewBackendFormatter(backend, format)
logging.SetBackend(backendFormatter)
}
|
package iofiles
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"nidavellir/libs"
)
// Opens a new LogFile instance for general logging purposes.
func NewLogFile(appFolder string, sourceId, jobId int, readonly bool) (*LogFile, error) {
folder, err := createFolder(appFolder, "jobs", strconv.Itoa(sourceId), strconv.Itoa(jobId))
if err != nil {
return nil, err
}
file, err := openFile(readonly, folder, "logs.txt")
if err != nil {
return nil, err
}
return &LogFile{file: file, readonly: readonly}, nil
}
// Opens a new LogFile instance for docker image build logging purposes.
func NewImageLogFile(appFolder string, sourceId, jobId int, readonly bool) (*LogFile, error) {
folder, err := createFolder(appFolder, "jobs", strconv.Itoa(sourceId), strconv.Itoa(jobId))
if err != nil {
return nil, err
}
file, err := openFile(readonly, folder, "image.txt")
if err != nil {
return nil, err
}
return &LogFile{file: file, readonly: readonly}, nil
}
// LogFile helper instance for reading and writing log data
type LogFile struct {
file *os.File
readonly bool
}
// Writes the error or logs into the log file and into the standard output
func (l *LogFile) Write(content interface{}) error {
if l.readonly {
return errors.New("cannot append content when file is readonly")
}
mw := io.MultiWriter(os.Stdout, l.file)
logger := log.New()
logger.SetOutput(mw)
logger.Printf("%s", content)
return nil
}
// Closes the LogFile, rendering it unusable anymore
func (l *LogFile) Close() {
_ = l.file.Close()
}
// Reads all the file content
func (l *LogFile) Read() (string, error) {
content, err := ioutil.ReadAll(l.file)
if err != nil {
return "", errors.Wrap(err, "could not read log file content")
}
return string(content), nil
}
// Creates the folder from the path element if it does not exist
func createFolder(elem ...string) (string, error) {
folder := filepath.Join(elem...)
if !libs.PathExists(folder) {
err := os.MkdirAll(folder, 0777)
if err != nil {
return "", errors.Wrap(err, "could not create folder path to store logs")
}
}
return folder, nil
}
func openFile(readonly bool, pathElem ...string) (*os.File, error) {
path := filepath.Join(pathElem...)
var flags int
if readonly {
flags = os.O_RDONLY
} else {
flags = os.O_CREATE | os.O_RDWR | os.O_APPEND
}
file, err := os.OpenFile(path, flags, 0666)
if err != nil {
return nil, err
}
return file, nil
}
|
package sqlstorage
/*
Docker postgres run:
docker run --name golang-postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -d -p 5432:5432 postgres:alpine
docker exec -ti golang-postgres psql -U postgres
*/
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
storage "github.com/ezhk/golang-learning/hw12_13_14_15_calendar/internal/storage"
utils "github.com/ezhk/golang-learning/hw12_13_14_15_calendar/internal/utils"
// use pgx as a database/sql compatible driver.
_ "github.com/jackc/pgx/stdlib"
"github.com/jmoiron/sqlx"
)
type SQLDatabase struct {
database *sqlx.DB
ctx context.Context
cancel context.CancelFunc
}
func NewDatatabase() storage.ClientInterface {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
return &SQLDatabase{
ctx: ctx,
cancel: cancel,
}
}
func (d *SQLDatabase) Connect(dsn string) error {
db, err := sqlx.Open("pgx", dsn)
if err != nil {
return fmt.Errorf("failed to load driver: %w", err)
}
d.database = db
return nil
}
func (d *SQLDatabase) Close() error {
d.cancel()
return d.database.Close()
}
func (d *SQLDatabase) GetUserByEmail(email string) (storage.User, error) {
query := `SELECT *
FROM users
WHERE email = $1`
var user storage.User
err := d.database.QueryRowxContext(d.ctx, query, email).StructScan(&user)
switch {
case errors.Is(err, sql.ErrNoRows):
return storage.User{}, storage.ErrUserDoesNotExist
case err != nil:
return storage.User{}, fmt.Errorf("get user by email error: %w", err)
}
return user, nil
}
func (d *SQLDatabase) CreateUser(email string, firstName string, lastName string) (storage.User, error) {
existUser, _ := d.GetUserByEmail(email)
if v := existUser.ID; v > 0 {
return existUser, storage.ErrUserExists
}
user := storage.User{
Email: email,
FirstName: firstName,
LastName: lastName,
}
var insertID int64
query := `INSERT INTO users(
email,
first_name,
last_name
) VALUES (
:email,
:first_name,
:last_name
) RETURNING id`
// Prepare named request.
nstmt, err := d.database.PrepareNamedContext(d.ctx, query)
if err != nil {
return storage.User{}, fmt.Errorf("prepare create user error: %w", err)
}
// Execute and waiting for returning ID.
err = nstmt.Get(&insertID, &user)
if err != nil {
return storage.User{}, fmt.Errorf("create user error: %w", err)
}
user.ID = insertID
return user, nil
}
func (d *SQLDatabase) UpdateUser(user storage.User) error {
query := `UPDATE users
SET email = :email,
first_name = :first_name,
last_name = :last_name
WHERE id = :id`
_, err := d.database.NamedExecContext(d.ctx, query, &user)
if err != nil {
return fmt.Errorf("update user error: %w", err)
}
return nil
}
func (d *SQLDatabase) DeleteUser(user storage.User) error {
query := `DELETE FROM users
WHERE id = $1`
_, err := d.database.ExecContext(d.ctx, query, user.ID)
if err != nil {
return fmt.Errorf("delete user error: %w", err)
}
return nil
}
func (d *SQLDatabase) GetEventsByUserID(userID int64) ([]storage.Event, error) {
query := `SELECT *
FROM events
WHERE user_id = $1`
var events []storage.Event
err := d.database.SelectContext(d.ctx, &events, query, userID)
if err != nil {
return nil, fmt.Errorf("select events by user ID error: %w", err)
}
return events, nil
}
func (d *SQLDatabase) getEventsByDateRange(userID int64, fromDate, toDate time.Time) ([]storage.Event, error) {
query := `SELECT *
FROM events
WHERE user_id = $1
AND (
date_from >= $2 AND date_from < $3
OR date_to >= $2 AND date_to < $3
)`
var events []storage.Event
err := d.database.SelectContext(d.ctx, &events, query, userID, fromDate, toDate)
if err != nil {
return nil, fmt.Errorf("select events by date range error: %w", err)
}
return events, nil
}
func (d *SQLDatabase) CreateEvent(userID int64, title, content string, dateFrom, dateTo time.Time) (storage.Event, error) {
event := storage.Event{
UserID: userID,
Title: title,
Content: content,
DateFrom: dateFrom,
DateTo: dateTo,
}
var insertID int64
query := `INSERT INTO events(
user_id,
title,
content,
date_from,
date_to
) VALUES (
:user_id,
:title,
:content,
:date_from,
:date_to
) RETURNING id`
// Prepare named request.
nstmt, err := d.database.PrepareNamedContext(d.ctx, query)
if err != nil {
return storage.Event{}, fmt.Errorf("prepare create event error: %w", err)
}
// Execute and waiting for returning ID.
err = nstmt.Get(&insertID, &event)
if err != nil {
return storage.Event{}, fmt.Errorf("create event error: %w", err)
}
event.ID = insertID
return event, nil
}
func (d *SQLDatabase) UpdateEvent(event storage.Event) error {
query := `UPDATE events
SET user_id = :user_id,
title = :title,
content = :content,
date_from = :date_from,
date_to = :date_to,
notified = :notified
WHERE id = :id`
_, err := d.database.NamedExecContext(d.ctx, query, &event)
if err != nil {
return fmt.Errorf("update event error: %w", err)
}
return nil
}
func (d *SQLDatabase) DeleteEvent(event storage.Event) error {
query := `DELETE
FROM events
WHERE id = $1`
_, err := d.database.ExecContext(d.ctx, query, event.ID)
if err != nil {
return fmt.Errorf("delete event error: %w", err)
}
return nil
}
func (d *SQLDatabase) DailyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartDay(date)
toDate := utils.EndDay(date)
return d.getEventsByDateRange(userID, fromDate, toDate)
}
func (d *SQLDatabase) WeeklyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartWeek(date)
toDate := utils.EndWeek(date)
return d.getEventsByDateRange(userID, fromDate, toDate)
}
func (d *SQLDatabase) MonthlyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartMonth(date)
toDate := utils.EndMonth(date)
return d.getEventsByDateRange(userID, fromDate, toDate)
}
func (d *SQLDatabase) GetNotifyReadyEvents() ([]storage.Event, error) {
query := `SELECT *
FROM events
WHERE notified = FALSE
AND date_from <= $1`
twoWeekLeft := time.Now().Add(2 * time.Hour * 24 * 7)
var events []storage.Event
err := d.database.SelectContext(d.ctx, &events, query, twoWeekLeft)
if err != nil {
return nil, fmt.Errorf("get notify ready events error: %w", err)
}
return events, nil
}
func (d *SQLDatabase) MarkEventAsNotified(event *storage.Event) error {
query := `UPDATE events
SET notified = TRUE
WHERE id = $1`
_, err := d.database.ExecContext(d.ctx, query, event.ID)
if err != nil {
return fmt.Errorf("update events error: %w", err)
}
event.Notified = true
return nil
}
|
package main
import "fmt"
func main()
{
mapka := map[slice]slice{
"Owner 1": "BWM"
"Owner 2": "Mercedes"
}
}
|
package antlr
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/hyperjumptech/grule-rule-engine/antlr/parser"
"github.com/hyperjumptech/grule-rule-engine/model"
"github.com/sirupsen/logrus"
"io/ioutil"
"reflect"
"testing"
"time"
)
func TestLexer(t *testing.T) {
data, err := ioutil.ReadFile("./sample2.grl")
if err != nil {
t.Fatal(err)
} else {
is := antlr.NewInputStream(string(data))
// Create the Lexer
lexer := parser.NewgruleLexer(is)
//lexer := parser.NewLdifParserLexer(is)
// Read all tokens
for {
nt := lexer.NextToken()
if nt.GetTokenType() == antlr.TokenEOF {
break
}
fmt.Println(nt.GetText())
}
}
}
func TestParser(t *testing.T) {
logrus.SetLevel(logrus.TraceLevel)
data, err := ioutil.ReadFile("./sample2.grl")
if err != nil {
t.Fatal(err)
} else {
sdata := string(data)
is := antlr.NewInputStream(sdata)
lexer := parser.NewgruleLexer(is)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
var parseError error
reteConf := NewReteConfig(true, true, true, false, true)
listener := NewGruleParserListener(model.NewKnowledgeBase("Test", "0.1.1"), reteConf, func(e error) {
parseError = e
})
psr := parser.NewgruleParser(stream)
psr.BuildParseTrees = true
antlr.ParseTreeWalkerDefault.Walk(listener, psr.Root())
if parseError != nil {
t.Log(parseError)
t.FailNow()
}
}
}
func TestTimeKind(t *testing.T) {
n := time.Now()
nt := reflect.TypeOf(n)
fmt.Println(nt.String())
}
|
package vault
import (
"errors"
"net/http"
"net/url"
vault "github.com/hashicorp/vault/api"
"github.com/mlowicki/rhythm/conf"
tlsutils "github.com/mlowicki/rhythm/tls"
log "github.com/sirupsen/logrus"
)
// Client implements Vault client reading secrets with specified prefix.
type Client struct {
c *vault.Client
root string
}
func (c *Client) Read(path string) (string, error) {
secret, err := c.c.Logical().Read(c.root + path)
if err != nil {
return "", err
}
if secret == nil {
return "", errors.New("secret not found")
}
if value, ok := secret.Data["value"]; ok {
switch v := value.(type) {
case string:
return v, nil
default:
return "", errors.New("secret's value is not string")
}
} else {
return "", errors.New("secret's value not found")
}
}
// New creates fresh instance of Vault client.
func New(c *conf.SecretsVault) (*Client, error) {
url, err := url.Parse(c.Addr)
if err != nil {
return nil, err
}
if url.Scheme != "https" {
log.Warnf("Address uses HTTP scheme which is insecure. It's recommended to use HTTPS instead.")
}
vc := vault.DefaultConfig()
vc.Address = c.Addr
vc.Timeout = c.Timeout
if c.CACert != "" {
pool, err := tlsutils.BuildCertPool(c.CACert)
if err != nil {
return nil, err
}
tlsConf := vc.HttpClient.Transport.(*http.Transport).TLSClientConfig
tlsConf.RootCAs = pool
}
cli, err := vault.NewClient(vc)
if err != nil {
return nil, err
}
cli.SetToken(c.Token)
wrapper := &Client{c: cli, root: c.Root}
return wrapper, nil
}
|
// Package s3manager provides utilities to upload and download objects from
// S3 concurrently. Helpful for when working with large objects.
package s3manager
//Added a line for testing
//Adding another line for Git event testing part 2
//Adding another line for Git event testing part 2.1
//Adding another line for Git event testing part 2.2
|
package auditlog
// Account actions
const (
Banned Action = "banned"
CodeSent Action = "code_sent"
ConfirmSent Action = "confirm_sent"
Confirmed Action = "confirmed"
Deleted Action = "deleted"
Signup Action = "signup"
)
// System actions
const (
Startup Action = "startup"
Shutdown Action = "shutdown"
)
// Token actions
const (
Granted Action = "granted"
Refreshed Action = "refreshed"
Revoked Action = "revoked"
RevokedAll Action = "revoked_all"
)
// User actions
const (
ChangeRole Action = "change_role"
Email Action = "email"
Linked Action = "linked"
Login Action = "login"
Logout Action = "logout"
Password Action = "password"
Updated Action = "updated"
)
// Action is action captured by the log entry.
type Action string
// Type returns the type for the action.
func (a Action) Type() Type {
switch a {
// System actions
case Startup:
return System
case Shutdown:
return System
// Account actions
case Signup:
return Account
case CodeSent:
return Account
case ConfirmSent:
return Account
case Confirmed:
return Account
case Banned:
return Account
case Deleted:
return Account
// Token actions
case Granted:
return Token
case Refreshed:
return Token
case Revoked:
return Token
case RevokedAll:
return Token
// User actions
case Linked:
return User
case Login:
return User
case Logout:
return User
case Password:
return User
case Email:
return User
case Updated:
return User
case ChangeRole:
return User
// Unknown action
default:
return Unknown
}
}
func (a Action) String() string {
return string(a)
}
|
package producer
import (
"fmt"
"time"
"github.com/couchbase/eventing/logging"
"github.com/couchbase/eventing/util"
"github.com/couchbase/gocb"
"github.com/couchbase/gomemcached"
)
var gocbConnectMetaBucketCallback = func(args ...interface{}) error {
p := args[0].(*Producer)
connStr := fmt.Sprintf("couchbase://%s", p.KvHostPorts()[0])
cluster, err := gocb.Connect(connStr)
if err != nil {
logging.Errorf("PRDR[%s:%d] GOCB Connect to cluster %s failed, err: %v",
p.appName, p.LenRunningConsumers(), connStr, err)
return err
}
var user, password string
util.Retry(util.NewFixedBackoff(time.Second), getMemcachedServiceAuth, p, p.KvHostPorts()[0], &user, &password)
err = cluster.Authenticate(gocb.PasswordAuthenticator{
Username: user,
Password: password,
})
if err != nil {
logging.Errorf("PRDR[%s:%d] GOCB Failed to authenticate to the cluster %s failed, err: %v",
p.appName, p.LenRunningConsumers(), connStr, err)
return err
}
p.metadataBucketHandle, err = cluster.OpenBucket(p.metadatabucket, "")
if err != nil {
logging.Errorf("PRDR[%s:%d] GOCB Failed to connect to bucket %s failed, err: %v",
p.appName, p.LenRunningConsumers(), p.metadatabucket, err)
return err
}
return nil
}
var setOpCallback = func(args ...interface{}) error {
p := args[0].(*Producer)
key := args[1].(string)
blob := args[2]
_, err := p.metadataBucketHandle.Upsert(key, blob, 0)
if err != nil {
logging.Errorf("PRDR[%s:%d] Bucket set failed for key: %v , err: %v", p.appName, p.LenRunningConsumers(), key, err)
}
return err
}
var getOpCallback = func(args ...interface{}) error {
p := args[0].(*Producer)
key := args[1].(string)
blob := args[2]
_, err := p.metadataBucketHandle.Get(key, blob)
if err != nil {
logging.Errorf("PRDR[%s:%d] Bucket set failed for key: %v , err: %v", p.appName, p.LenRunningConsumers(), key, err)
}
return err
}
var deleteOpCallback = func(args ...interface{}) error {
p := args[0].(*Producer)
key := args[1].(string)
_, err := p.metadataBucketHandle.Remove(key, 0)
if gomemcached.KEY_ENOENT == util.MemcachedErrCode(err) {
logging.Errorf("PRDR[%s:%d] Key: %v doesn't exist, err: %v",
p.appName, p.LenRunningConsumers(), key, err)
return nil
} else if err != nil {
logging.Errorf("PRDR[%s:%d] Bucket delete failed for key: %v, err: %v",
p.appName, p.LenRunningConsumers(), key, err)
}
return err
}
|
package main
import (
"fmt"
"net"
"time"
)
func CheckError(err error) {
if err != nil {
fmt.Println("Error: " , err)
}
}
func main() {
ServerAddr,err := net.ResolveUDPAddr("udp","129.241.187.255:20003")
CheckError(err)
Conn, err := net.DialUDP("udp", nil, ServerAddr)
CheckError(err)
defer Conn.Close()
for {
_,err := Conn.Write([]byte("Hello here we are\x00"))
if err != nil {
fmt.Println(err)
}
time.Sleep(time.Second * 1)
}
}
|
package main
import (
"testing"
)
func TestCode(t *testing.T) {
var tests = []struct {
array []int
index int
paid int
output int
}{
{[]int{3, 10, 2, 9}, 1, 12, 5},
{[]int{3, 10, 2, 9}, 1, 7, 0},
}
for _, test := range tests {
if got := bonAppetit(test.array, test.index, test.paid); got != test.output {
t.Errorf(
"Given Array %v, Index %v, Paid %v\n; Expected %v; Got %v",
test.array, test.index, test.paid, test.output, got,
)
}
}
}
|
package person
import "time"
const Collection string = "people"
// Person represents a user, whether he's seeking or
// offering.
type Person struct {
ID string `json:"id" bson:"_id,omitempty"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email"`
Phone string `json:"phone"`
DOB string `json:"dob"`
Bio string `json:"bio"`
RegistrationDate time.Time `json:"registrationDate"`
}
// People represents a list of Person structs
type People []Person
// PeopleListQuery Represents a query for People. Assits pagination
type PeopleListQuery struct {
LastID string
Limit int
}
// PeopleQueryResult represents the result of a query for People.
type PeopleQueryResult struct {
People *People
LastID string
}
|
package global
import "github.com/BurntSushi/toml"
func GetSysConfig() (sysConfig SysConfig,err error){
_,err = toml.DecodeFile("config.toml",&sysConfig)
return
}
|
package main
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/csv"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"os/exec"
"os/signal"
"runtime"
"strconv"
"strings"
"text/tabwriter"
"time"
log "github.com/Sirupsen/logrus"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize"
redis "gopkg.in/redis.v3"
)
var (
// discordgo session
discord *discordgo.Session
// Redis client connection (used for stats)
rcli *redis.Client
// Map of Guild id's to *Play channels, used for queuing and rate-limiting guilds
queues = make(map[string]chan *Play)
skipped = make(map[string]bool)
caching = make(map[string]bool)
// gifPosting toggle for gifPost
gifPosting = make(map[string]bool)
memeTimeout = make(map[string]time.Duration)
lastMeme = make(map[string]time.Time)
memeVoice = make(map[string]bool)
// BITRATE - Bitrate
BITRATE = 128
// MAXQSIZE - Max queue size
MAXQSIZE = 9999
// YTAPIKEY - Youtube API Key
YTAPIKEY string
// OWNER - Owner
OWNER string
)
const (
// SUCCESS - success
SUCCESS = "success"
)
// Play represents an individual use of the !airhorn command
type Play struct {
GuildID string
ChannelID string
UserID string
Sound *Sound
// The next play to occur after this, only used for chaining sounds like anotha
Next *Play
// If true, this was a forced play using a specific airhorn sound name
Forced bool
}
// SoundCollection - Collection of sounds
type SoundCollection struct {
Prefix string
Commands []string
Sounds []*Sound
ChainWith *SoundCollection
soundRange int
}
// Sound represents a sound clip
type Sound struct {
Name string
// Weight adjust how likely it is this song will play, higher = more likely
Weight int
// Delay (in milliseconds) for the bot to wait before sending the disconnect request
PartDelay int
// Buffer to store encoded PCM packets
buffer [][]byte
}
// AIRHORN - Array of all the sounds we have
var AIRHORN = &SoundCollection{
Prefix: "airhorn",
Commands: []string{
"!airhorn",
},
Sounds: []*Sound{
createSound("default", 1000, 250),
createSound("reverb", 800, 250),
createSound("spam", 800, 0),
createSound("tripletap", 800, 250),
createSound("fourtap", 800, 250),
createSound("distant", 500, 250),
createSound("echo", 500, 250),
createSound("clownfull", 250, 250),
createSound("clownshort", 250, 250),
createSound("clownspam", 250, 0),
createSound("highfartlong", 200, 250),
createSound("highfartshort", 200, 250),
createSound("midshort", 100, 250),
createSound("truck", 10, 250),
},
}
// KHALED - DJ Khaled
var KHALED = &SoundCollection{
Prefix: "another",
ChainWith: AIRHORN,
Commands: []string{
"!anotha",
"!anothaone",
},
Sounds: []*Sound{
createSound("one", 1, 250),
createSound("one_classic", 1, 250),
createSound("one_echo", 1, 250),
},
}
// CENA - JOHN CENA!!!!!
var CENA = &SoundCollection{
Prefix: "jc",
Commands: []string{
"!johncena",
"!cena",
},
Sounds: []*Sound{
createSound("airhorn", 1, 250),
createSound("echo", 1, 250),
createSound("full", 1, 250),
createSound("jc", 1, 250),
createSound("nameis", 1, 250),
createSound("spam", 1, 250),
},
}
// ETHAN - H3H3
var ETHAN = &SoundCollection{
Prefix: "ethan",
Commands: []string{
"!ethan",
"!eb",
"!ethanbradberry",
"!h3h3",
},
Sounds: []*Sound{
createSound("areyou_classic", 100, 250),
createSound("areyou_condensed", 100, 250),
createSound("areyou_crazy", 100, 250),
createSound("areyou_ethan", 100, 250),
createSound("classic", 100, 250),
createSound("echo", 100, 250),
createSound("high", 100, 250),
createSound("slowandlow", 100, 250),
createSound("cuts", 30, 250),
createSound("beat", 30, 250),
createSound("sodiepop", 1, 250),
},
}
// COW GOES MOO
var COW = &SoundCollection{
Prefix: "cow",
Commands: []string{
"!stan",
"!stanislav",
},
Sounds: []*Sound{
createSound("herd", 10, 250),
createSound("moo", 10, 250),
createSound("x3", 1, 250),
},
}
// BIRTHDAY - HAPPY BIRTHDAY TO YOU
var BIRTHDAY = &SoundCollection{
Prefix: "birthday",
Commands: []string{
"!birthday",
"!bday",
},
Sounds: []*Sound{
createSound("horn", 50, 250),
createSound("horn3", 30, 250),
createSound("sadhorn", 25, 250),
createSound("weakhorn", 25, 250),
},
}
// WOW - WOW
var WOW = &SoundCollection{
Prefix: "wow",
Commands: []string{
"!wowthatscool",
"!wtc",
"!wow",
},
Sounds: []*Sound{
createSound("thatscool", 50, 250),
createSound("wow", 100, 250),
},
}
// BEES BEES, THEY'RE EVERYWHERE
var BEES = &SoundCollection{
Prefix: "bees",
Commands: []string{
"!bees",
},
Sounds: []*Sound{
createSound("bees", 100, 250),
createSound("remastered", 100, 250),
createSound("beedrills", 10, 250),
createSound("temmie", 10, 250),
createSound("too", 50, 250),
createSound("junkie", 25, 250),
createSound("dammit", 25, 250),
},
}
// NGAHHH - Angry Fish
var NGAHHH = &SoundCollection{
Prefix: "ngah",
Commands: []string{
"!ngahhh",
"!ngah",
"ngahhh",
},
Sounds: []*Sound{
createSound("normal", 100, 250),
createSound("evil", 10, 250),
createSound("evil_slide", 10, 250),
createSound("fast", 50, 250),
createSound("faster", 50, 250),
createSound("turbo", 40, 250),
createSound("turboer", 30, 250),
createSound("turboest", 20, 250),
createSound("slow", 40, 250),
createSound("turboester", 15, 250),
createSound("turbostar", 10, 250),
createSound("full", 1, 250),
createSound("soj", 1, 250),
},
}
// CANCER - LET'S GET RIGHT INTO THE CANCER
var CANCER = &SoundCollection{
Prefix: "meme",
Commands: []string{
"!cancer",
"!memes",
"!dankmemes",
"!maymays",
"!dankmaymays",
},
Sounds: []*Sound{
createSound("everythingnomegalo", 10, 250),
createSound("everything", 10, 250),
createSound("news", 100, 250),
createSound("illegal", 100, 250),
createSound("banestar", 10, 250),
createSound("keemstar", 10, 250),
createSound("allstar", 10, 250),
createSound("noneblackhole", 10, 250),
createSound("stopcoming", 10, 250),
},
}
func createEmptySC() *SoundCollection {
return &SoundCollection{}
}
// COLLECTIONS - Set of collections
var COLLECTIONS = []*SoundCollection{
AIRHORN,
KHALED,
CENA,
ETHAN,
COW,
BIRTHDAY,
WOW,
BEES,
NGAHHH,
CANCER,
}
// Create a Sound struct
func createSound(Name string, Weight int, PartDelay int) *Sound {
return &Sound{
Name: Name,
Weight: Weight,
PartDelay: PartDelay,
buffer: make([][]byte, 0),
}
}
// Load entire collection
func (sc *SoundCollection) Load() {
for _, sound := range sc.Sounds {
sc.soundRange += sound.Weight
sound.Load(sc)
}
}
// Random sound from this collection
func (sc *SoundCollection) Random() *Sound {
var (
i int
number = randomRange(0, sc.soundRange)
)
for _, sound := range sc.Sounds {
i += sound.Weight
if number < i {
return sound
}
}
return nil
}
// LoadNow - Modification of Load
func (s *Sound) LoadNow() error {
path := fmt.Sprintf("audio/%v", s.Name)
file, err := os.Open(path)
if err != nil {
fmt.Println("error opening dca file :", err)
return err
}
var opuslen int16
for {
// read opus frame length from dca file
err = binary.Read(file, binary.LittleEndian, &opuslen)
// If this is the end of the file, just return
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil
}
if err != nil {
fmt.Println("error reading from dca file :", err)
return err
}
// read encoded pcm from dca file
InBuf := make([]byte, opuslen)
err = binary.Read(file, binary.LittleEndian, &InBuf)
// Should not be any end of file errors
if err != nil {
fmt.Println("error reading from dca file :", err)
return err
}
// append encoded pcm data to the buffer
s.buffer = append(s.buffer, InBuf)
}
}
// Unload this sound
func (s *Sound) Unload() {
s.buffer = nil
}
func (s *Sound) isLoaded() bool {
if len(s.buffer) != 0 {
return true
}
return false
}
// Load this sound
func (s *Sound) Load(c *SoundCollection) error {
path := fmt.Sprintf("audio/%v_%v.dca", c.Prefix, s.Name)
file, err := os.Open(path)
if err != nil {
fmt.Println("error opening dca file :", err)
return err
}
var opuslen int16
for {
// read opus frame length from dca file
err = binary.Read(file, binary.LittleEndian, &opuslen)
// If this is the end of the file, just return
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil
}
if err != nil {
fmt.Println("error reading from dca file :", err)
return err
}
// read encoded pcm from dca file
InBuf := make([]byte, opuslen)
err = binary.Read(file, binary.LittleEndian, &InBuf)
// Should not be any end of file errors
if err != nil {
fmt.Println("error reading from dca file :", err)
return err
}
// append encoded pcm data to the buffer
s.buffer = append(s.buffer, InBuf)
}
}
// PlayFile - Plays file
func (s *Sound) PlayFile(vc *discordgo.VoiceConnection, file string) {
ffmpeg := exec.Command("ffmpeg", "-i", "audio/"+file, "-f", "s16le", "-ar", "48000", "-ac", "2", "pipe:1")
ffmpegout, err := ffmpeg.StdoutPipe()
if err != nil {
log.Println("ffmpeg StdoutPipe err:", err)
return
}
ffmpegbuf := bufio.NewReaderSize(ffmpegout, 16384)
dca := exec.Command("dca", "-raw", "-i", "pipe:0")
dca.Stdin = ffmpegbuf
dcaout, err := dca.StdoutPipe()
if err != nil {
log.Println("dca StdoutPipe err:", err)
return
}
dcabuf := bufio.NewReaderSize(dcaout, 16384)
err = ffmpeg.Start()
if err != nil {
log.Println("ffmpeg Start err:", err)
return
}
defer func() {
go ffmpeg.Wait()
}()
err = dca.Start()
if err != nil {
log.Println("dca Start err:", err)
return
}
defer func() {
go dca.Wait()
}()
// header "buffer"
var opuslen int16
// Send "speaking" packet over the voice websocket
vc.Speaking(true)
// Send not "speaking" packet over the websocket when we finish
defer vc.Speaking(false)
for {
// read dca opus length header
err = binary.Read(dcabuf, binary.LittleEndian, &opuslen)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
if err != nil {
log.Println("read opus length from dca err:", err)
return
}
// read opus data from dca
opus := make([]byte, opuslen)
err = binary.Read(dcabuf, binary.LittleEndian, &opus)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
if err != nil {
log.Println("read opus from dca err:", err)
return
}
if skipped[vc.GuildID] {
ffmpeg.Process.Kill()
dca.Process.Kill()
return
}
// Send received PCM to the sendPCM channel
vc.OpusSend <- opus
}
}
// PlayStream - Plays stream
func (s *Sound) PlayStream(vc *discordgo.VoiceConnection, stream string) {
log.Info(stream)
if caching[vc.GuildID] {
go streamDownload(stream)
}
format := "bestaudio"
if strings.Contains(stream, "youtube.com") || strings.Contains(stream, "youtu.be") {
format = "mp4"
}
ytdl := exec.Command("youtube-dl", "-v", "-f", format, "-o", "-", stream)
ytdlout, err := ytdl.StdoutPipe()
if err != nil {
log.Println("ytdl StdoutPipe err:", err)
return
}
ytdlbuf := bufio.NewReaderSize(ytdlout, 16384)
ffmpeg := exec.Command("ffmpeg", "-i", "pipe:0", "-f", "s16le", "-ar", "48000", "-ac", "2", "pipe:1")
ffmpeg.Stdin = ytdlbuf
ffmpegout, err := ffmpeg.StdoutPipe()
if err != nil {
log.Println("ffmpeg StdoutPipe err:", err)
return
}
ffmpegbuf := bufio.NewReaderSize(ffmpegout, 16384)
dca := exec.Command("dca", "-raw", "-i", "pipe:0")
dca.Stdin = ffmpegbuf
dcaout, err := dca.StdoutPipe()
if err != nil {
log.Println("dca StdoutPipe err:", err)
return
}
dcabuf := bufio.NewReaderSize(dcaout, 16384)
err = ytdl.Start()
if err != nil {
log.Println("ytdl Start err:", err)
return
}
defer func() {
go ytdl.Wait()
}()
err = ffmpeg.Start()
if err != nil {
log.Println("ffmpeg Start err:", err)
return
}
defer func() {
go ffmpeg.Wait()
}()
err = dca.Start()
if err != nil {
log.Println("dca Start err:", err)
return
}
defer func() {
go dca.Wait()
}()
// header "buffer"
var opuslen int16
// Send "speaking" packet over the voice websocket
vc.Speaking(true)
// Send not "speaking" packet over the websocket when we finish
defer vc.Speaking(false)
for {
// read dca opus length header
err = binary.Read(dcabuf, binary.LittleEndian, &opuslen)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
if err != nil {
log.Println("read opus length from dca err:", err)
return
}
// read opus data from dca
opus := make([]byte, opuslen)
err = binary.Read(dcabuf, binary.LittleEndian, &opus)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
if err != nil {
log.Println("read opus from dca err:", err)
return
}
if skipped[vc.GuildID] {
ytdl.Process.Kill()
ffmpeg.Process.Kill()
dca.Process.Kill()
return
}
// Send received PCM to the sendPCM channel
vc.OpusSend <- opus
}
}
func streamDownload(stream string, name ...string) string {
id, err := getIDFromLink(stream)
log.Info(stream)
if err != nil {
return "Invalid link"
}
if isLive(id) {
return "Video is live"
}
var dcaName string
if name != nil {
dcaName = name[0]
} else {
dcaName = getDCAfromLink(stream)
}
format := "bestaudio"
if strings.Contains(stream, "youtube.com") || strings.Contains(stream, "youtu.be") {
format = "mp4"
}
ytdl := exec.Command("youtube-dl", "-v", "-f", format, "-o", "-", stream)
ytdlout, err := ytdl.StdoutPipe()
if err != nil {
log.Println("ytdl StdoutPipe err:", err)
return "youtube-dl StdoutPipe error"
}
ytdlbuf := bufio.NewReaderSize(ytdlout, 16384)
ffmpeg := exec.Command("ffmpeg", "-i", "pipe:0", "-f", "s16le", "-ar", "48000", "-ac", "2", "pipe:1")
ffmpeg.Stdin = ytdlbuf
ffmpegout, err := ffmpeg.StdoutPipe()
if err != nil {
log.Println("ffmpeg StdoutPipe err:", err)
return "ffmpeg StdoutPipe error"
}
ffmpegbuf := bufio.NewReaderSize(ffmpegout, 16384)
dca := exec.Command("dca", "-raw", "-i", "pipe:0")
dca.Stdin = ffmpegbuf
outfile, err := os.Create("audio/" + dcaName)
if err != nil {
log.Println("file creation err:", err)
return "file creation error"
}
defer outfile.Close()
dca.Stdout = outfile
err = ytdl.Start()
if err != nil {
log.Println("ytdl Start err:", err)
return "youtube-dl error"
}
defer func() {
go ytdl.Wait()
}()
err = ffmpeg.Start()
if err != nil {
log.Println("ffmpeg Start err:", err)
return "ffmpeg error"
}
defer func() {
go ffmpeg.Wait()
}()
err = dca.Start()
if err != nil {
log.Println("dca Start err:", err)
return "dca error"
}
defer dca.Wait()
return SUCCESS
}
// Play this sound over the specified VoiceConnection
func (s *Sound) Play(vc *discordgo.VoiceConnection) {
nameType := strings.Split(s.Name, "@")
if len(nameType) > 1 {
if nameType[1] == "stream" {
s.PlayStream(vc, nameType[0])
return
} else if nameType[1] == "file" {
s.PlayFile(vc, nameType[0])
return
}
}
vc.Speaking(true)
defer vc.Speaking(false)
for _, buff := range s.buffer {
if skipped[vc.GuildID] {
return
}
vc.OpusSend <- buff
}
}
// NEVER RENAME THIS FUNCTION, EVER.
// IF WE WANT TO PROCESS VOTES MAKE A NEW FUNCTION
// CALL IT votes OR SOMETHING
func skip(g *discordgo.Guild) {
skipped[g.ID] = true
}
// Attempts to find the current users voice channel inside a given guild
func getCurrentVoiceChannel(user *discordgo.User, guild *discordgo.Guild) *discordgo.Channel {
for _, vs := range guild.VoiceStates {
if vs.UserID == user.ID {
channel, _ := discord.State.Channel(vs.ChannelID)
return channel
}
}
return nil
}
// Returns a random integer between min and max
func randomRange(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max-min) + min
}
// Prepares a play
func createPlay(user *discordgo.User, guild *discordgo.Guild, coll *SoundCollection, sound *Sound) *Play {
// Grab the users voice channel
channel := getCurrentVoiceChannel(user, guild)
if channel == nil {
log.WithFields(log.Fields{
"user": user.ID,
"guild": guild.ID,
}).Warning("Failed to find channel to play sound in")
return nil
}
// Create the play
play := &Play{
GuildID: guild.ID,
ChannelID: channel.ID,
UserID: user.ID,
Sound: sound,
Forced: true,
}
// If we didn't get passed a manual sound, generate a random one
if play.Sound == nil {
play.Sound = coll.Random()
play.Forced = false
}
// If the collection is a chained one, set the next sound
if coll.ChainWith != nil {
play.Next = &Play{
GuildID: play.GuildID,
ChannelID: play.ChannelID,
UserID: play.UserID,
Sound: coll.ChainWith.Random(),
Forced: play.Forced,
}
}
return play
}
func listQueue(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild) {
_, exists := queues[g.ID]
if exists {
s.ChannelMessageSend(m.ChannelID, strconv.Itoa(len(queues[g.ID])))
}
}
// Prepares and enqueues a play into the ratelimit/buffer guild queue
func enqueuePlay(user *discordgo.User, guild *discordgo.Guild, coll *SoundCollection, sound *Sound, s ...*discordgo.Session) {
play := createPlay(user, guild, coll, sound)
if play == nil {
return
}
// Check if we already have a connection to this guild
// yes, this isn't threadsafe, but its "OK" 99% of the time
_, exists := queues[guild.ID]
if exists {
if len(queues[guild.ID]) < MAXQSIZE {
queues[guild.ID] <- play
}
} else {
queues[guild.ID] = make(chan *Play, MAXQSIZE)
if s != nil {
playSound(play, nil, s[0])
} else {
playSound(play, nil)
}
}
}
func trackSoundStats(play *Play) {
if rcli == nil {
return
}
_, err := rcli.Pipelined(func(pipe *redis.Pipeline) error {
var baseChar string
if play.Forced {
baseChar = "f"
} else {
baseChar = "a"
}
base := fmt.Sprintf("airhorn:%s", baseChar)
pipe.Incr("airhorn:total")
pipe.Incr(fmt.Sprintf("%s:total", base))
pipe.Incr(fmt.Sprintf("%s:sound:%s", base, play.Sound.Name))
pipe.Incr(fmt.Sprintf("%s:user:%s:sound:%s", base, play.UserID, play.Sound.Name))
pipe.Incr(fmt.Sprintf("%s:guild:%s:sound:%s", base, play.GuildID, play.Sound.Name))
pipe.Incr(fmt.Sprintf("%s:guild:%s:chan:%s:sound:%s", base, play.GuildID, play.ChannelID, play.Sound.Name))
pipe.SAdd(fmt.Sprintf("%s:users", base), play.UserID)
pipe.SAdd(fmt.Sprintf("%s:guilds", base), play.GuildID)
pipe.SAdd(fmt.Sprintf("%s:channels", base), play.ChannelID)
return nil
})
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Warning("Failed to track stats in redis")
}
}
func ytDCAtoLink(ytDCA string) string {
split := strings.SplitN(ytDCA, "_", 2)
if split[0] != "yt" {
return ""
}
idsplit := strings.Split(split[1], ".")
return "youtu.be/" + idsplit[0]
}
// Play a sound
func playSound(play *Play, vc *discordgo.VoiceConnection, s ...*discordgo.Session) (err error) {
log.WithFields(log.Fields{
"play": play,
}).Info("Playing sound")
skipped[play.GuildID] = false
loaded := play.Sound.isLoaded()
if vc == nil {
vc, err = discord.ChannelVoiceJoin(play.GuildID, play.ChannelID, false, false)
// vc.Receive = false
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Failed to play sound")
delete(queues, play.GuildID)
return err
}
}
// If we need to change channels, do that now
if vc.ChannelID != play.ChannelID {
vc.ChangeChannel(play.ChannelID, false, false)
time.Sleep(time.Millisecond * 125)
}
// Track stats for this play in redis
go trackSoundStats(play)
// Sleep for a specified amount of time before playing the sound
time.Sleep(time.Millisecond * 32)
// Play the sound
if len(s) > 0 {
link := ytDCAtoLink(play.Sound.Name)
if link != "" {
s[0].UpdateStatus(0, link)
} else {
s[0].UpdateStatus(0, play.Sound.Name)
}
}
if !loaded {
play.Sound.LoadNow()
}
play.Sound.Play(vc)
//Will wait till next song is done to do this shit
log.Info("Played song, advance queue")
//Put shit here to advance the "fake" queue text
//vc.GuildID
advanceQueueList(vc.GuildID)
if !loaded {
play.Sound.Unload()
}
// If this is chained, play the chained sound
if play.Next != nil {
playSound(play.Next, vc)
}
// If there is another song in the queue, recurse and play that
if len(queues[play.GuildID]) > 0 {
nextPlay := <-queues[play.GuildID]
if s != nil {
playSound(nextPlay, vc, s[0])
} else {
playSound(nextPlay, vc)
}
return nil
}
// If the queue is empty, delete it
time.Sleep(time.Millisecond * time.Duration(play.Sound.PartDelay))
delete(queues, play.GuildID)
vc.Disconnect()
if len(s) > 0 {
s[0].UpdateStatus(0, "Nothing")
}
return nil
}
func onReady(s *discordgo.Session, event *discordgo.Ready) {
log.Info("Recieved READY payload")
s.UpdateStatus(0, "Nothing")
}
func onGuildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
if event.Guild.Unavailable || queues[event.Guild.ID] == nil {
return
}
initServerSettings(event.Guild.ID)
for _, channel := range event.Guild.Channels {
if channel.ID == event.Guild.ID {
s.ChannelMessageSend(channel.ID, "**AIRGOAT READY TO BEES. TYPE `!BEES` WHILE IN A VOICE CHANNEL TO BEES**")
}
}
}
func scontains(key string, options ...string) bool {
for _, item := range options {
if item == key {
return true
}
}
return false
}
func calculateAirhornsPerSecond(cid string) {
current, _ := strconv.Atoi(rcli.Get("airhorn:a:total").Val())
time.Sleep(time.Second * 10)
latest, _ := strconv.Atoi(rcli.Get("airhorn:a:total").Val())
discord.ChannelMessageSend(cid, fmt.Sprintf("Current APS: %v", (float64(latest-current))/10.0))
}
func displayBotStats(cid string) {
stats := runtime.MemStats{}
runtime.ReadMemStats(&stats)
users := 0
for _, guild := range discord.State.Ready.Guilds {
users += len(guild.Members)
}
w := &tabwriter.Writer{}
buf := &bytes.Buffer{}
w.Init(buf, 0, 4, 0, ' ', 0)
fmt.Fprintf(w, "```\n")
fmt.Fprintf(w, "Discordgo: \t%s\n", discordgo.VERSION)
fmt.Fprintf(w, "Go: \t%s\n", runtime.Version())
fmt.Fprintf(w, "Memory: \t%s / %s (%s total allocated)\n", humanize.Bytes(stats.Alloc), humanize.Bytes(stats.Sys), humanize.Bytes(stats.TotalAlloc))
fmt.Fprintf(w, "Tasks: \t%d\n", runtime.NumGoroutine())
fmt.Fprintf(w, "Servers: \t%d\n", len(discord.State.Ready.Guilds))
fmt.Fprintf(w, "Users: \t%d\n", users)
fmt.Fprintf(w, "```\n")
w.Flush()
discord.ChannelMessageSend(cid, buf.String())
}
func utilSumRedisKeys(keys []string) int {
//results := make([]*redis.StringCmd, 0) linting says this is a good change but don't know for sure
var results []*redis.StringCmd
rcli.Pipelined(func(pipe *redis.Pipeline) error {
for _, key := range keys {
results = append(results, pipe.Get(key))
}
return nil
})
var total int
for _, i := range results {
t, _ := strconv.Atoi(i.Val())
total += t
}
return total
}
func displayUserStats(cid, uid string) {
keys, err := rcli.Keys(fmt.Sprintf("airhorn:*:user:%s:sound:*", uid)).Result()
if err != nil {
return
}
totalAirhorns := utilSumRedisKeys(keys)
discord.ChannelMessageSend(cid, fmt.Sprintf("Total Airhorns: %v", totalAirhorns))
}
func displayServerStats(cid, sid string) {
keys, err := rcli.Keys(fmt.Sprintf("airhorn:*:guild:%s:sound:*", sid)).Result()
if err != nil {
return
}
totalAirhorns := utilSumRedisKeys(keys)
discord.ChannelMessageSend(cid, fmt.Sprintf("Total Airhorns: %v", totalAirhorns))
}
func utilGetMentioned(s *discordgo.Session, m *discordgo.MessageCreate) *discordgo.User {
for _, mention := range m.Mentions {
if mention.ID != s.State.Ready.User.ID {
return mention
}
}
return nil
}
func getYtIDFromLink(link string) (string, error) {
id := ""
if strings.Contains(link, "youtube.com/watch?v=") {
splitlink := strings.SplitAfter(link, "=")
after := splitlink[1]
splitafter := strings.Split(after, "&")
id = splitafter[0]
} else if strings.Contains(link, "youtu.be/") {
splitlink := strings.SplitAfter(link, "/")
var after string
if strings.Contains(link, "://") {
after = splitlink[3]
} else {
after = splitlink[1]
}
splitafter := strings.Split(after, "&")
id = splitafter[0]
}
if len(id) > 11 {
id = id[0:11]
}
return id, nil
}
func getIDFromLink(link string) (string, error) {
if strings.Contains(link, "youtube.com/watch?v=") || strings.Contains(link, "youtu.be/") {
return getYtIDFromLink(link)
}
_, id, _, _, err := getInfoFromLink(link)
if err != nil {
return "", err
}
return id, nil
}
//func for getting specific info from video link
//this is in order of retrieval
//0 = title
//1 = id
//2 = duration
//3 = latency
func getInfoPartFromLink(link string, part int) (string, error) {
if part == 1 {
return getIDFromLink(link)
}
title, _, duration, latency, err := getInfoFromLink(link)
if err != nil {
return "", err
}
switch part {
case 0:
return title, nil
case 2:
return duration, nil
case 3:
return latency, nil
default:
return "", errors.New("Invalid part")
}
}
//this function uses the YouTube API to find the information rather than using youtube-dl
func getYtInfoFromLink(link string) (title, id, duration, latency string, err error) {
start := time.Now()
id, err = getIDFromLink(link)
if err != nil {
return "", "", "", "", err
}
apiPage := urlToString(ytIDtoAPIurl(id) + "&fields=items(snippet(title),contentDetails(duration))&part=snippet,contentDetails")
title, err = filterYtAPIresponse(apiPage, "title")
if err != nil {
return "", "", "", "", err
}
duration, err = filterYtAPIresponse(apiPage, "duration")
if err != nil {
return "", "", "", "", err
}
return title, id, duration, time.Since(start).String(), nil
}
//REALLY SLOW
//fetches video information using youtube-dl in this order
//0 = title
//1 = id
//2 = duration
//3 = latency
func getInfoFromLink(link string) (title, id, duration, latency string, err error) {
if strings.Contains(link, "youtube.com/watch?v=") || strings.Contains(link, "youtu.be/") && YTAPIKEY != "" {
return getYtInfoFromLink(link)
}
start := time.Now()
//info := []string{"Name", "Id", "Duration", "Lat"}
cmd := exec.Command("youtube-dl", "--get-title", "--get-id", "--get-duration", link)
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
return "", "", "", "", err
}
info := strings.Split(out.String(), "\n")
return info[0], info[1], info[2], time.Since(start).String(), nil
}
func returnStringOrError(s string, err error) string {
if err != nil {
return err.Error()
}
return s
}
func playDCA(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, dca string, silent bool) {
qm := "Queued: " + dca
link := ytDCAtoLink(dca)
dcaSplit := strings.SplitN(dca, "_", 2)
if link != "" {
qm = "Queued: " + returnStringOrError(getInfoPartFromLink(link, 0))
} else if dcaSplit[0] == "tag" {
dcaSplit = strings.Split(dcaSplit[1], ".")
qm = "Queued tag: " + dcaSplit[0]
}
if !silent {
s.ChannelMessageSend(m.ChannelID, qm)
}
go enqueuePlay(m.Author, g, createEmptySC(), createSound(dca, 1, 250), s)
}
func isDCA(possDCA string) bool {
split := strings.Split(possDCA, ".")
if len(split) == 2 && split[1] == "dca" {
return true
}
return false
}
func play(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, toPlay string, silent bool) {
if isDCA(toPlay) {
playDCA(s, m, g, toPlay, silent)
return
}
if !silent {
go s.ChannelMessageSend(m.ChannelID, "Queued: "+returnStringOrError(getInfoPartFromLink(toPlay, 0)))
}
go enqueuePlay(m.Author, g, createEmptySC(), createSound(toPlay+"@stream", 1, 250), s)
}
func playFile(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, file string) {
go enqueuePlay(m.Author, g, createEmptySC(), createSound(file, 1, 250), s)
}
func getDCAfromLink(link string) string {
return getPrefixFromLink(link) + returnStringOrError(getIDFromLink(link)) + ".dca"
}
func getPrefixFromLink(link string) string {
prefix := "url_"
if strings.Contains(link, "youtube.com") || strings.Contains(link, "youtu.be") {
prefix = "yt_"
} else if strings.Contains(link, "soundcloud.com") {
prefix = "sc_"
}
return prefix
}
func ytTimeFormat(time string) string {
w := ""
d := ""
h := ""
m := ""
s := ""
curr := strings.Split(time, "P")
curr = strings.Split(curr[1], "T")
p := curr[0]
t := curr[1]
if p != "" {
if strings.Contains(p, "W") {
wp := strings.Split(p, "W")
w = wp[0] + "w "
p = wp[1]
}
if strings.Contains(p, "D") {
dp := strings.Split(p, "D")
d = dp[0] + "d "
//p = dp[1]
}
}
if strings.Contains(t, "H") {
hp := strings.Split(t, "H")
h = hp[0] + "h "
t = hp[1]
}
if strings.Contains(t, "M") {
mp := strings.Split(t, "M")
m = mp[0] + "m "
t = mp[1]
}
if strings.Contains(t, "S") {
sp := strings.Split(t, "S")
s = sp[0] + "s"
//t = sp[1]
}
return w + d + h + m + s
}
func timeFormat(time string) string {
if strings.Contains(time, "P") {
return ytTimeFormat(time)
}
// Hours : Minutes : Seconds
var timeformat string
//timed := []string{"00", "00", "00"}
timed := strings.Split(time, ":")
switch count := strings.Count(time, ":"); count {
case 0:
timeformat = timed[0] + "s"
case 1:
timeformat = timed[0] + "m " + timed[1] + "s"
case 2:
timeformat = timed[0] + "h " + timed[1] + "m"
default:
timeformat = "YT Timer Parse Error"
}
return timeformat
}
func fileExists(fileName string) bool {
path := fmt.Sprintf("audio/%v", fileName)
if _, err := os.Stat(path); err == nil {
return true
}
return false
}
func delDCA(DCA string) string {
if !fileExists(DCA) {
return "File doesn't exist"
}
rmerr := os.Remove("audio/" + DCA)
if rmerr != nil {
log.Info(rmerr)
return "The file is a persistant bastard."
}
return "File removed"
}
func delTag(tag string) string {
return delDCA("tag_" + tag + ".dca")
}
func delLink(link string) string {
return delDCA(getDCAfromLink(link))
}
func playTag(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, tag string) {
tagDCA := "tag_" + tag + ".dca"
if fileExists(tagDCA) {
playDCA(s, m, g, tagDCA, false)
return
}
s.ChannelMessageSend(m.ChannelID, tag+" doesn't exist")
}
func tagLink(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, tag string, link string) {
tagDCA := "tag_" + tag + ".dca"
if fileExists(tagDCA) {
s.ChannelMessageSend(m.ChannelID, tag+" already exists")
return
}
s.ChannelMessageSend(m.ChannelID, "Downloading tag: "+tag)
result := streamDownload(link, tagDCA)
if result != SUCCESS {
s.ChannelMessageSend(m.ChannelID, "Failed to create tag, error: "+result)
} else {
s.ChannelMessageSend(m.ChannelID, tag+" created")
}
}
func cleanYTLink(link string) string {
if strings.Contains(link, "youtube.com") || strings.Contains(link, "youtu.be") {
return "youtu.be/" + returnStringOrError(getYtIDFromLink(link))
}
return link
}
func playLink(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, link string, silent bool) {
//addToQueueList(g.ID, link)
link = cleanYTLink(link)
linkDCA := getDCAfromLink(link)
if fileExists(linkDCA) {
playDCA(s, m, g, linkDCA, silent)
} else {
play(s, m, g, link, silent)
}
}
// TODO: This should be refactored to be faster/nicer
func readln(r *bufio.Reader) (string, error) {
var (
isPrefix = true
err error
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln), err
}
func playList(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, qLink string) {
url := ""
if strings.Contains(qLink, "youtube.com") || strings.Contains(qLink, "youtu.be") {
url = "youtu.be/"
} else if strings.Contains(qLink, "soundcloud.com") {
url = "api.soundcloud.com/tracks/"
}
ytdl := exec.Command("youtube-dl", "-i", "--get-id", qLink)
ytdlout, err := ytdl.StdoutPipe()
if err != nil {
log.Println("ytdl StdoutPipe err:", err)
return
}
r := bufio.NewReaderSize(ytdlout, 1024)
if err = ytdl.Start(); err != nil {
log.Println("ytdl Start err:", err)
return
}
qCount := 0
message, _ := s.ChannelMessageSend(m.ChannelID, "Queuing "+qLink+" Playlist"+strings.Repeat(".", (qCount%3)+1)+" Length: "+strconv.Itoa(qCount))
// TODO: Replace with something faster/nicer
id, err := readln(r)
for err == nil {
vidLink := url + id
fmt.Println(vidLink)
playLink(s, m, g, vidLink, true)
qCount++
id, err = readln(r)
s.ChannelMessageEdit(m.ChannelID, message.ID, "Queuing "+qLink+" Playlist"+strings.Repeat(".", (qCount%3)+1)+" Length: "+strconv.Itoa(qCount))
}
s.ChannelMessageEdit(m.ChannelID, message.ID, "Queuing "+qLink+" Playlist! Length: "+strconv.Itoa(qCount))
}
func bytesToString(byteString []byte) string {
return string(byteString[:])
}
func urlToString(url string) string {
res, err := http.Get(url)
if err != nil {
log.Info(err)
return "ERROR: HTTP GET BORK"
}
urlstring, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Info(err)
return "ERROR: HTTP TO STRING BORK"
}
return bytesToString(urlstring)
}
func filterYtAPIresponse(apiResponse, contentName string) (string, error) {
if !strings.Contains(apiResponse, contentName) {
return "", errors.New("Content not in API Response")
}
split := strings.SplitAfterN(apiResponse, contentName, 2)
split = strings.SplitAfterN(split[1], "\": \"", 2)
split = strings.SplitN(split[1], "\",", 2)
split = strings.SplitN(split[0], "\"\n", 2)
return split[0], nil
}
func ytIDtoAPIurl(id string) string {
return "https://www.googleapis.com/youtube/v3/videos?id=" + id + "&key=" + YTAPIKEY
}
func isLive(ytID string) bool {
if ytID == "" || YTAPIKEY == "" {
return false
}
apiResponse, err := filterYtAPIresponse(urlToString(ytIDtoAPIurl(ytID)+"&fields=items(snippet(liveBroadcastContent))&part=snippet"), "liveBroadcastContent")
if err != nil {
log.Info(err)
return false
}
if apiResponse == "live" {
return true
}
return false
}
func cleanLink(link string) string {
link = strings.Replace(link, "\n", "", -1)
return strings.Replace(link, "\t", "", -1)
}
func sayGuilds(s *discordgo.Session, m *discordgo.MessageCreate) {
guilds, _ := s.UserGuilds()
for _, g := range guilds {
s.ChannelMessageSend(m.ChannelID, g.ID)
}
}
func deleteMessageIn(s *discordgo.Session, m *discordgo.Message, timeout time.Duration) {
time.Sleep(time.Second * timeout)
s.ChannelMessageDelete(m.ChannelID, m.ID)
}
// Handles bot operator messages, should be refactored (lmao)
func handleBotControlMessages(s *discordgo.Session, m *discordgo.MessageCreate, parts []string, g *discordgo.Guild, perm ...int) {
perms, _ := discord.State.UserChannelPermissions(discord.State.User.ID, m.ChannelID)
if perms&discordgo.PermissionSendMessages == 0 {
log.Info("I don't have the permission to post")
if m.Author.ID != OWNER {
log.Info("...but it's the owner, so I don't care")
return
}
}
accessLevel := -1
if perm != nil {
accessLevel = perm[0]
}
var message *discordgo.Message
var merr error
if len(parts) == 1 {
message, merr = s.ChannelMessageSend(m.ChannelID, "What you want?")
} else if scontains("q", parts[1]) && len(parts) == 3 {
playLink(s, m, g, cleanLink(parts[2]), false)
} else if scontains("q", parts[1]) && len(parts) > 3 {
var link string
link, parts = parts[len(parts)-1], parts[:len(parts)-1]
//log.Info("Testing: " + link)
defer playLink(s, m, g, cleanLink(link), false)
handleBotControlMessages(s, m, parts, g)
} else if scontains("pl", parts[1]) && len(parts) == 3 {
playList(s, m, g, cleanLink(parts[2]))
} else if scontains("pl", parts[1]) && len(parts) > 3 {
var link string
link, parts = parts[len(parts)-1], parts[:len(parts)-1]
defer playList(s, m, g, cleanLink(link))
handleBotControlMessages(s, m, parts, g)
} else if (scontains("syt", parts[1]) || scontains("s", parts[1])) && len(parts) > 2 {
term := strings.Join(parts[2:], " ")
link := searchYtForPlay(s, m, g, term)
log.Info("YT search term: \"" + term + "\" and found " + link)
playLink(s, m, g, cleanLink(link), false)
} else if scontains("ssc", parts[1]) && len(parts) > 2 {
term := strings.Join(parts[2:], " ")
link := searchScForPlay(s, m, g, term)
log.Info("SC search term: \"" + term + "\" and found " + link)
playLink(s, m, g, cleanLink(link), false)
} else if (scontains("sytm", parts[1]) || scontains("sm", parts[1])) && len(parts) > 3 {
//var allLinks string
num, err := strconv.Atoi(parts[2])
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error: "+err.Error())
log.Info(err)
return
}
links := searchYtForMutliPlay(s, m, g, strings.Join(parts[3:], " "), num)
for _, link := range links {
playLink(s, m, g, cleanLink(link), false)
}
} else if scontains("lq", parts[1]) {
listQueue(s, m, g)
} else if scontains("live", parts[1]) && len(parts) == 3 {
id, err := getIDFromLink(parts[2])
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error: "+err.Error())
return
}
if isLive(id) {
message, merr = s.ChannelMessageSend(m.ChannelID, "That video is live")
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "Nah mate, not live")
}
} else if scontains("skip", parts[1]) {
skip(g)
message, merr = s.ChannelMessageSend(m.ChannelID, "<@"+m.Author.ID+"> skipped")
log.Info(m.Author.ID + " skipped")
} else if scontains("t", parts[1]) && len(parts) >= 3 {
playTag(s, m, g, strings.Join(parts[2:], "_"))
} else if scontains("ct", parts[1]) && len(parts) >= 4 {
tagLink(s, m, g, strings.Join(parts[2:len(parts)-1], "_"), parts[len(parts)-1])
} else if scontains("mt", parts[1]) && len(parts) < 3 {
//catch case for mt
} else if scontains("mt", parts[1]) && len(parts) >= 3 {
var tag string
tag, parts = parts[len(parts)-1], parts[:len(parts)-1]
defer playTag(s, m, g, tag)
handleBotControlMessages(s, m, parts, g)
} else if scontains("master", parts[0]) && m.Author.ID == OWNER {
message, merr = s.ChannelMessageSend(m.ChannelID, "Yes, Master <@"+OWNER+">.")
parts = append(parts[:0], parts[1:]...)
go handleBotControlMessages(s, m, parts, g, 1)
} else if scontains("del", parts[1]) && len(parts) == 3 && accessLevel >= 0 {
result := delDCA(parts[2])
message, merr = s.ChannelMessageSend(m.ChannelID, result)
} else if scontains("delTag", parts[1]) && len(parts) >= 3 && accessLevel >= 0 {
result := delTag(strings.Join(parts[2:], "_"))
message, merr = s.ChannelMessageSend(m.ChannelID, result)
} else if scontains("delLink", parts[1]) && len(parts) == 3 && accessLevel >= 0 {
result := delLink(parts[2])
message, merr = s.ChannelMessageSend(m.ChannelID, result)
} else if scontains("pf", parts[1]) && len(parts) == 3 && accessLevel >= 0 {
playFile(s, m, g, parts[2])
} else if scontains("memepost", parts[1]) && len(parts) == 2 && accessLevel >= 0 {
gifPosting[g.ID] = !gifPosting[g.ID]
if gifPosting[g.ID] {
message, merr = s.ChannelMessageSend(m.ChannelID, "MEMEPOSTING ENGAGED")
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "The cancer has stopped...\nat least for now...")
}
saveServerSettings(g.ID)
} else if scontains("memevoice", parts[1]) && len(parts) == 2 && accessLevel >= 0 {
memeVoice[g.ID] = !memeVoice[g.ID]
if memeVoice[g.ID] {
message, merr = s.ChannelMessageSend(m.ChannelID, "MEMEVOICE ENGAGED, !BEES TO FUCK SHIT UP")
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "The cancer voice has stopped...\nat least for now...")
}
saveServerSettings(g.ID)
} else if scontains("ytdlupdate", parts[1]) && len(parts) == 2 && accessLevel >= 0 {
updateMessage := updateYTDL(s, m, g)
s.ChannelMessageSend(m.ChannelID, updateMessage)
} else if scontains("ytdlver", parts[1]) && len(parts) == 2 && accessLevel >= 0 {
verMessage := verCheckYTDL(s, m, g)
s.ChannelMessageSend(m.ChannelID, verMessage)
} else if scontains("cache", parts[1]) && len(parts) == 2 && accessLevel >= 0 {
caching[g.ID] = !caching[g.ID]
if caching[g.ID] {
message, merr = s.ChannelMessageSend(m.ChannelID, "Caching enabled")
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "Caching disabled")
}
saveServerSettings(g.ID)
} else if scontains("memetimeout", parts[1]) && len(parts) == 3 && accessLevel >= 0 {
newTimeout, err := time.ParseDuration(parts[2])
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error: "+err.Error())
log.Info(err)
return
}
memeTimeout[g.ID] = newTimeout
saveServerSettings(g.ID)
} else if scontains("servers", parts[1]) && accessLevel == 1 {
sayGuilds(s, m)
} else if scontains("leave", parts[1]) && accessLevel == 1 {
err := s.GuildLeave(parts[2])
if err == nil {
message, merr = s.ChannelMessageSend(m.ChannelID, "I've left "+parts[2])
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "Unable to leave due to error")
log.Info(err)
}
} else if scontains("status", parts[1]) {
displayBotStats(m.ChannelID)
} else if scontains("stats", parts[1]) {
if len(m.Mentions) >= 2 {
displayUserStats(m.ChannelID, utilGetMentioned(s, m).ID)
} else if len(parts) >= 3 {
displayUserStats(m.ChannelID, parts[2])
} else {
displayServerStats(m.ChannelID, g.ID)
}
} else if scontains("aps", parts[1]) {
message, merr = s.ChannelMessageSend(m.ChannelID, ":ok_hand: give me a sec m8")
go calculateAirhornsPerSecond(m.ChannelID)
} else if scontains("id", parts[1]) && len(parts) == 3 {
id, err := getIDFromLink(parts[2])
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error: "+err.Error())
return
}
message, merr = s.ChannelMessageSend(m.ChannelID, "Link ID: `"+id+"`")
} else if scontains("info", parts[1]) && len(parts) == 3 {
title, id, duration, latency, err := getInfoFromLink(parts[2])
if err != nil {
s.ChannelMessageSend(m.ChannelID, "Error: "+err.Error())
log.Info(err)
return
}
message, merr = s.ChannelMessageSend(m.ChannelID, "Name: `"+title+"`\nID: `"+id+"`\nDuration: `"+timeFormat(duration)+"`\nLatency:`"+latency+"`")
} else if scontains("help", parts[1]) {
s.ChannelMessageSend(m.ChannelID, "`@AirGoat cmd`")
s.ChannelMessageSend(m.ChannelID, "Command list: `q` - Queues a YouTube or SoundCloud link\n`pl` - Queues a YouTube or SoundCloud playlist\n`t` - Queues a tag\n`ct` - Creates a tag\n`mt` - Queues multiple tags\n`skip` - Skips current song\n`help` - This")
//s.ChannelMessageSend(m.ChannelID, "`master @AirGoat cmd`")
//s.ChannelMessageSend(m.ChannelID, "Command list: `del` `delTag` `delLink` `pf` `gifpost` `cache` `servers` `leave`")
} else {
message, merr = s.ChannelMessageSend(m.ChannelID, "Stop.")
}
if merr != nil {
log.Info("Message send error: " + merr.Error())
} else if message != nil {
go deleteMessageIn(s, message, 5)
}
}
func gifPost(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild) {
if time.Now().Before(lastMeme[g.ID].Add(memeTimeout[g.ID])) {
log.Info("too soon")
return
}
f, err := os.Open("memes.csv")
if err != nil {
log.Info(err)
return
}
defer f.Close()
r := csv.NewReader(f)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Info(err)
return
}
if len(record) < 2 {
continue
}
if len(m.Content) >= 1 && strings.Contains(strings.ToLower(m.Content), record[0]) {
meme := strings.Replace(record[1], "\\n", "\n", -1)
s.ChannelMessageSend(m.ChannelID, meme)
}
}
lastMeme[g.ID] = time.Now()
}
func onMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == "129329923595829248" {
s.ChannelMessageDelete(m.ChannelID, m.ID)
return
}
channel, _ := discord.State.Channel(m.ChannelID)
if channel == nil {
log.WithFields(log.Fields{
"channel": m.ChannelID,
"message": m.ID,
}).Warning("Failed to grab channel")
return
}
guild, _ := discord.State.Guild(channel.GuildID)
if guild == nil {
log.WithFields(log.Fields{
"guild": channel.GuildID,
"channel": channel,
"message": m.ID,
}).Warning("Failed to grab guild")
return
}
if gifPosting[guild.ID] && m.Author.ID != s.State.User.ID {
go gifPost(s, m, guild)
}
if len(m.Content) <= 0 || (m.Content[0] != '!' && len(m.Mentions) < 1) {
return
}
msg := strings.Replace(m.ContentWithMentionsReplaced(), s.State.Ready.User.Username, "username", 1)
parts := strings.Split(msg, " ")
// If this is a mention, it should come from the owner (otherwise we don't care)
if len(m.Mentions) > 0 && len(parts) > 0 {
mentioned := false
for _, mention := range m.Mentions {
mentioned = (mention.ID == s.State.Ready.User.ID)
if mentioned {
break
}
}
if mentioned {
handleBotControlMessages(s, m, parts, guild)
}
return
}
// Find the collection for the command we got
for _, coll := range COLLECTIONS {
if scontains(parts[0], coll.Commands...) && memeVoice[guild.ID] == true {
// If they passed a specific sound effect, find and select that (otherwise play nothing)
var sound *Sound
if len(parts) > 1 {
for _, s := range coll.Sounds {
if parts[1] == s.Name {
sound = s
}
}
if sound == nil {
return
}
}
go enqueuePlay(m.Author, guild, coll, sound)
return
}
}
}
//Pray to the gods this works how I want it to, hell, thinking about it, it really shouldn't work
func makeQueueList(guildID string) {
f, err := os.Create("squeues/" + guildID + ".csv")
if err != nil {
log.Println("file creation err:", err)
return
}
f.Close()
}
func advanceQueueList(guildID string) {
csvFile := "squeues/" + guildID + ".csv"
f, err := os.Open(csvFile)
if err != nil {
if err.Error() == "open "+csvFile+": The system cannot find the file specified." || err.Error() == "open "+csvFile+": no such file or directory" {
f.Close()
log.Info("making queue file for ", guildID)
makeQueueList(guildID)
} else {
log.Info("queue load err: ", err)
}
return
}
defer f.Close()
r := csv.NewReader(f)
for {
record, err := r.Read()
if err == io.EOF {
break
}
recordlen := len(record)
log.Info(recordlen, " _ ", record)
if recordlen >= 1 {
log.Info("First queue for " + guildID + " is " + record[0])
for i := 1; i < recordlen; i++ {
record[i-1] = record[i]
}
log.Info("For guildID " + guildID + " first queue is now" + record[0])
}
}
}
func addToQueueList(guildID string, link string) bool {
file := "squeues/" + guildID + ".csv"
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0777)
if err.Error() == "open "+file+": The system cannot find the file specified." || err.Error() == "open "+file+": no such file or directory" {
f.Close()
log.Info("Could not load, making file, err: ", err)
makeQueueList(guildID)
f, err = os.OpenFile("squeues/"+guildID+".csv", os.O_APPEND|os.O_WRONLY, 0777)
if err != nil {
log.Info("Cannot open file still, err: ", err)
}
} else if err != nil {
log.Info("Queue file err: ", err)
return false
}
defer f.Close()
if _, err = f.WriteString("\"" + link + "\","); err != nil {
log.Info(err)
return false
}
log.Info(err)
return true
}
func saveServerSettings(guildID string) {
err := os.Truncate("sconfigs/"+guildID+".csv", 0)
if err != nil {
log.Info("error emptying file: ", err)
return
}
f, err := os.OpenFile("sconfigs/"+guildID+".csv", os.O_WRONLY|os.O_APPEND, 0777)
if err != nil {
log.Info("server settings save err: ", err)
return
}
n, err := f.WriteString(toCSV(strconv.FormatBool(gifPosting[guildID]), strconv.FormatBool(caching[guildID]), memeTimeout[guildID].String(), strconv.FormatBool(memeVoice[guildID])))
log.Info(n, err)
f.Sync()
f.Close()
}
func toCSV(args ...string) string {
csValue := []string{"\"", "", "\""}
for i, arg := range args {
csValue[1] = arg
args[i] = strings.Join(csValue, "")
}
return strings.Join(args, ",")
}
func initServerSettings(guildID string) {
gifPosting[guildID] = false
caching[guildID] = false
memeTimeout[guildID], _ = time.ParseDuration("0s")
memeVoice[guildID] = true
f, err := os.Create("sconfigs/" + guildID + ".csv")
if err != nil {
log.Println("file creation err:", err)
return
}
f.Close()
/*
f, err = os.Create("squeues/" + guildID + ".csv")
if err != nil {
log.Println("file creation err:", err)
return
}
f.Close()
*/
saveServerSettings(guildID)
}
func loadServerSettings(guildID string) {
csvFile := "sconfigs/" + guildID + ".csv"
f, err := os.Open(csvFile)
if err != nil {
if err.Error() == "open "+csvFile+": The system cannot find the file specified." || err.Error() == "open "+csvFile+": no such file or directory" {
f.Close()
log.Info("creating server settings")
initServerSettings(guildID)
} else {
log.Info("server setting load err: ", err)
}
return
}
defer f.Close()
r := csv.NewReader(f)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Info(err)
return
}
if len(record) < 4 {
log.Info("invalid settings length")
return
}
gifPosting[guildID], err = strconv.ParseBool(record[0])
if err != nil {
gifPosting[guildID] = false
log.Info(err)
}
caching[guildID], err = strconv.ParseBool(record[1])
if err != nil {
caching[guildID] = false
log.Info(err)
}
memeTimeout[guildID], err = time.ParseDuration(record[2])
if err != nil {
memeTimeout[guildID], _ = time.ParseDuration("0s")
log.Info(err)
}
memeVoice[guildID], err = strconv.ParseBool(record[3])
if err != nil {
memeVoice[guildID] = true
log.Info(err)
}
}
}
/*func getCurrentVoiceChannel(user *discordgo.User, guild *discordgo.Guild) *discordgo.Channel {
for _, vs := range guild.VoiceStates {
if vs.UserID == user.ID {
channel, _ := discord.State.Channel(vs.ChannelID)
return channel
}
}
return nil
}*/
func searchYtForPlay(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, thingsToFind string) string {
log.Info("searching using: " + thingsToFind)
cmd := exec.Command("youtube-dl", "ytsearch1:"+thingsToFind, "--get-id")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Info(err)
return "Not Found"
}
return "http://youtu.be/" + strings.Split(out.String(), "\n")[0]
}
func searchScForPlay(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, thingsToFind string) string {
cmd := exec.Command("youtube-dl", "scsearch1:"+thingsToFind, "--get-url")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Info(err)
return "Not Found"
}
//SCinfo := getScInfoFromId(info[0])
return strings.Split(out.String(), "\n")[0]
}
func searchYtForMutliPlay(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild, thingsToFind string, numberOfthings int) []string {
cmd := exec.Command("youtube-dl", "ytsearch"+strconv.Itoa(numberOfthings)+":"+thingsToFind, "--get-id")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Info(err)
return nil
}
IDs := strings.Split(out.String(), "\n")
var links []string
for _, ID := range IDs[:len(IDs)-1] {
links = append(links, "http://youtu.be/"+ID)
}
return links
}
func updateYTDL(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild) string {
cmd := exec.Command("youtube-dl", "-U")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Info(err)
return "YTDL cmd Error"
}
return strings.Replace(out.String(), "\n", " ", -1)
}
func verCheckYTDL(s *discordgo.Session, m *discordgo.MessageCreate, g *discordgo.Guild) string {
cmd := exec.Command("youtube-dl", "--version")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Info(err)
return "YTDL cmd Error"
}
return strings.Replace(out.String(), "\n", " ", -1)
}
func main() {
var (
Token = flag.String("t", "", "Discord Authentication Token")
Redis = flag.String("r", "", "Redis Connection String")
Shard = flag.String("s", "", "Shard ID")
ShardCount = flag.String("c", "", "Number of shards")
Owner = flag.String("o", "", "Owner ID")
YtAPIKey = flag.String("y", "", "Youtube API Key")
err error
)
flag.Parse()
if *Owner != "" {
OWNER = *Owner
}
if *YtAPIKey != "" {
YTAPIKEY = *YtAPIKey
} else {
log.Info("WARNING! You have not provided a YouTube API Key .. @AirGoat live function will not work correctly .. Caching is dangerous as Live YouTube videos are not checked")
}
// Preload all the sounds
log.Info("Preloading sounds...")
for _, coll := range COLLECTIONS {
coll.Load()
}
// If we got passed a redis server, try to connect
if *Redis != "" {
log.Info("Connecting to redis...")
rcli = redis.NewClient(&redis.Options{Addr: *Redis, DB: 0})
_, err = rcli.Ping().Result()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to connect to redis")
return
}
}
// Create a discord session
log.Info("Starting discord session...")
discord, err = discordgo.New(*Token)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to create discord session")
return
}
// Set sharding info
discord.ShardID, _ = strconv.Atoi(*Shard)
discord.ShardCount, _ = strconv.Atoi(*ShardCount)
if discord.ShardCount <= 0 {
discord.ShardCount = 1
}
guilds, _ := discord.UserGuilds()
for _, g := range guilds {
loadServerSettings(g.ID)
}
discord.AddHandler(onReady)
discord.AddHandler(onGuildCreate)
discord.AddHandler(onMessageCreate)
err = discord.Open()
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to create discord websocket connection")
return
}
// We're running!
log.Info("AIRGOAT is ready to BEES.")
// Wait for a signal to quit
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
<-c
}
|
package dao
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type DAO interface {
ChallengeStore
}
type dao struct {
connectionString string
connection *sql.DB
}
type PostgresBuilder struct {
dao
}
func (pb PostgresBuilder) SetConnectionString(connectionString string) PostgresBuilder {
a := pb
a.connectionString = connectionString
return a
}
func (pb PostgresBuilder) Build() *dao {
var err error
psqlInfo := fmt.Sprintf("%s", pb.connectionString)
pb.connection, err = sql.Open("postgres", psqlInfo)
if err != nil {
fmt.Println("error opening connection: ", err)
panic(err) //TODO: either import logger into DAO as well, or do something better than panic!
}
return &pb.dao
}
|
package db
import (
"github.com/chadweimer/gomp/models"
"github.com/jmoiron/sqlx"
)
type sqlNoteDriver struct {
Db *sqlx.DB
}
func (d *sqlNoteDriver) Create(note *models.Note) error {
return tx(d.Db, func(db sqlx.Ext) error {
return d.createImpl(note, db)
})
}
func (*sqlNoteDriver) createImpl(note *models.Note, db sqlx.Queryer) error {
stmt := "INSERT INTO recipe_note (recipe_id, note) " +
"VALUES ($1, $2) RETURNING id"
return sqlx.Get(db, note, stmt, note.RecipeId, note.Text)
}
func (d *sqlNoteDriver) Update(note *models.Note) error {
return tx(d.Db, func(db sqlx.Ext) error {
return d.updateImpl(note, db)
})
}
func (*sqlNoteDriver) updateImpl(note *models.Note, db sqlx.Execer) error {
_, err := db.Exec("UPDATE recipe_note SET note = $1 WHERE ID = $2 AND recipe_id = $3",
note.Text, note.Id, note.RecipeId)
return err
}
func (d *sqlNoteDriver) Delete(recipeId, noteId int64) error {
return tx(d.Db, func(db sqlx.Ext) error {
return d.deleteImpl(recipeId, noteId, db)
})
}
func (*sqlNoteDriver) deleteImpl(recipeId, noteId int64, db sqlx.Execer) error {
_, err := db.Exec("DELETE FROM recipe_note WHERE id = $1 AND recipe_id = $2", noteId, recipeId)
return err
}
func (d *sqlNoteDriver) DeleteAll(recipeId int64) error {
return tx(d.Db, func(db sqlx.Ext) error {
return d.deleteAllImpl(recipeId, db)
})
}
func (*sqlNoteDriver) deleteAllImpl(recipeId int64, db sqlx.Execer) error {
_, err := db.Exec(
"DELETE FROM recipe_note WHERE recipe_id = $1",
recipeId)
return err
}
func (d *sqlNoteDriver) List(recipeId int64) (*[]models.Note, error) {
return get(d.Db, func(db sqlx.Queryer) (*[]models.Note, error) {
var notes []models.Note
if err := sqlx.Select(db, ¬es, "SELECT * FROM recipe_note WHERE recipe_id = $1 ORDER BY created_at DESC", recipeId); err != nil {
return nil, err
}
return ¬es, nil
})
}
|
package conf
import (
"gopkg.in/yaml.v2"
"testing"
)
var f = `
#
# Gw framework configurations.
#
# -----------------------
# Common configurations
# -----------------------
version: 1.0
server:
listenAddr: ":8090"
TLS:
enabled: false
certificate:
key: "tls/app.key"
cert: "tls/app.crt"
format: file # base64/file
# -----------------------
# Service configurations
# -----------------------
service:
name: "My App"
prefix: "/api/v1"
version: "Version 1.0"
remarks: "User Account Platform Services."
serviceDiscovery:
disabled: True
registryCenter:
addr: ""
configration:
auth:
user:
password:
configuration:
heathCheck:
proto: http
url: https://xx.
# --------------------------------
# Backend Store Configuration
# --------------------------------
backend:
db:
- name: primary
driver: mysql
addr: 127.0.0.1
port: "3306"
user: gw
password: gw@123
database: gwdb
ssl_mode: on
ssl_cert: ap
args:
charset: utf8
parseTime: True
cache:
- name: primary
driver: redis
addr: 127.0.0.1
port: "6379"
type: redis
auth:
disable: True
user: ocean
database: "1"
password: oceanho
# -------------------------------
# Service Security Configuration
# -------------------------------
security:
crypto:
hash:
alg: "sha256" # md5 / sha1 / sha256
salt: "cvMC33eY7o9YKarcUr7VCf9XLFmHXKWJ"
protect:
alg: "aes" # aes / 3des / rsa
secret: "sPJF7yVnCvgctCJJ9scdTjwqzeenKnHH"
cert:
privateKey: "config/etc/gw.key"
publicKey: "config/etc/gw.pem"
isFile: True # true/false. The key,cert can be base64 string or A file path.
auth:
trustSidKey: "x-gw-trust-sid" # 如果配置这项,请务必确保您发送到后端节点的 http header -> <trustSidKey> 是可信的.
paramKey:
passport: "email"
secret: "password"
verifyCode: "verifyCode"
paramPattern:
passport: '^\S{5,64}$'
secret: '^\S{5,64}$'
verifyCode: '^[0-9]{0,8}$'
session:
defaultStore:
name: primary
prefix: gw-sid
permission:
defaultStore:
type: db # db/cache
name: primary
cookie:
key: "_gid"
domain: "" # xxx.com / xxx.net
path: "/"
maxAge: "{{ .settings.expirationTimeControl.session }}"
httpOnly: False
secure: False
allowUrls:
- name: auth
urls:
- "POST:{{ .service.prefix }}/ucp/account/login"
- "POST:{{ .service.prefix }}/ucp/account/login"
ips:
- 127.0.0.1/32
- 192.168.0.0/24
- name: gw-generator
urls:
- "GET:{{ .service.prefix }}/gw/generator/create-js"
ips: []
authServer:
addr: https://auth.gw-framework.com
enableAuthServe: True # Enable(True)/Disable(False) Auth features.
login:
url: "{{ .service.prefix }}/gw/auth/login"
authTypes:
- basicAuth
- credentials
- accessKeySecret
methods:
- "Get"
- "Post"
logout:
url: "{{ .service.prefix }}/gw/auth/logout"
methods:
- "Get"
limit:
pagination:
minPageSize: "20"
maxPageSize: "2000"
# -------------------------------
# Service Settings Configuration
# -------------------------------
settings:
gw:
printRouterInfo:
disabled: False # enable/disable Print gw router info.
title: "Router Information"
headerKey:
requestIdKey: "X-Request-Id"
timeoutControl: # Timeout control, units is millisecond
redis: "1000"
database: "2000"
mongo: "2000"
http: "2000"
expirationTimeControl:
session: "7200"
# Any Your custom configuration item at here.
# More: https://github.com/oceanho/gw/master/docs/configuration#custom
custom:
gwpro:
user: OceanHo
tags:
- body
- programmer
mystruct:
a: hello
b: 18
`
var bf = `
version: 1.0
configProvider: localfs
configuration:
path: "config/app.yaml"
`
func TestLoadBootFromBytes_ShouldBe_OK(t *testing.T) {
bsc := NewBootConfigFromBytes("yaml", []byte(bf))
t.Logf("%v", bsc)
}
func TestLoadConfig_ShouldBe_OK(t *testing.T) {
bsc := NewBootConfigFromBytes("yaml", []byte(bf))
t.Logf("%v", bsc)
}
func TestApplicationConfig_ParseCustomPathTo(t *testing.T) {
var appcnf ApplicationConfig
yaml.Unmarshal([]byte(f), &appcnf)
s := struct {
User string `json:"user" toml:"user" yaml:"user"`
Tags []string `json:"tags" toml:"tags" yaml:"tags"`
MyStruct struct {
A string `json:"a" toml:"a" yaml:"a"`
B int64 `json:"b" toml:"b" yaml:"b"`
} `json:"mystruct" toml:"mystruct" yaml:"mystruct"`
}{}
_ = appcnf.ParseCustomPathTo("gwpro", &s)
}
|
/*
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 v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ScanRequestStatusType is status type of scan request
type ScanRequestStatusType string
const (
ScanRequestSuccess ScanRequestStatusType = "Success"
ScanRequestFail ScanRequestStatusType = "Fail"
ScanRequestPending ScanRequestStatusType = "Pending"
ScanRequestProcessing ScanRequestStatusType = "Processing"
// ScanRequestError is scan request is failed
ScanRequestError ScanRequestStatusType = "Error"
)
// ScanTarget is a target setting to scan images
type ScanTarget struct {
// Registry URL (example: docker.io)
RegistryURL string `json:"registryUrl"`
// Image path (example: library/alpine:3)
Images []string `json:"images"`
// The name of certificate secret for private registry.
CertificateSecret string `json:"certificateSecret,omitempty"`
// The name of secret containing login credential of registry
ImagePullSecret string `json:"imagePullSecret,omitempty"`
}
// ScanResult is result of scanning an image
type ScanResult struct {
//Scan summary
Summary map[string]int `json:"summary,omitempty"`
//Scan fatal message
Fatal []string `json:"fatal,omitempty"`
//Scan vulnerabilities
Vulnerabilities map[string]Vulnerabilities `json:"vulnerabilities,omitempty"`
}
// Vulnerability is the information of the vulnerability found.
type Vulnerability struct {
// Severity name
Name string `json:"Name,omitempty"`
// Severity namespace
NamespaceName string `json:"NamespaceName,omitempty"`
// Description for severity
Description string `json:"Description,omitempty"`
// Description link
Link string `json:"Link,omitempty"`
// Severity degree
Severity string `json:"Severity,omitempty"`
// Metadata
//Metadata runtime.RawExtension `json:"Metadata,omitempty"`
// Fixed version
FixedBy string `json:"FixedBy,omitempty"`
}
// Vulnerabilities is a set of Vulnerability instances
type Vulnerabilities []Vulnerability
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// ImageScanRequestSpec defines the desired state of ImageScanRequest
type ImageScanRequestSpec struct {
ScanTargets []ScanTarget `json:"scanTargets"`
// Do not verify registry server's certificate
Insecure bool `json:"insecure,omitempty"`
// The number of fixable issues allowable
MaxFixable int `json:"maxFixable,omitempty"`
// Whether to send result to report server
SendReport bool `json:"sendReport,omitempty"`
}
// ImageScanRequestStatus defines the observed state of ImageScanRequest
type ImageScanRequestStatus struct {
//Scan message for status
Message string `json:"message,omitempty"`
//Scan error reason
Reason string `json:"reason,omitempty"`
//Scan status
Status ScanRequestStatusType `json:"status,omitempty"`
//Scna results {docker.io/library/alpine:3: {summary : {"Low" : 1, "Medium" : 2, ...}}
Results map[string]ScanResult `json:"results,omitempty"`
}
// ImageScanRequestESReport is a report to send the result to Elastic Search
type ImageScanRequestESReport struct {
Image string `json:"image,omitempty"`
//Scna results {docker.io/library/alpine:3: {summary : {"Low" : 1, "Medium" : 2, ...}}
Result ScanResult `json:"result,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:shortName=icr
// +kubebuilder:printcolumn:name="STATUS",type=string,JSONPath=`.status.status`
// +kubebuilder:printcolumn:name="AGE",type=date,JSONPath=`.metadata.creationTimestamp`
// ImageScanRequest is the Schema for the imagescanrequests API
type ImageScanRequest struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ImageScanRequestSpec `json:"spec,omitempty"`
Status ImageScanRequestStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// ImageScanRequestList contains a list of ImageScanRequest
type ImageScanRequestList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ImageScanRequest `json:"items"`
}
func init() {
SchemeBuilder.Register(&ImageScanRequest{}, &ImageScanRequestList{})
}
|
package main
import (
// "context"
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
camundaclientgo "github.com/citilinkru/camunda-client-go/v2"
"github.com/citilinkru/camunda-client-go/v2/processor"
// "github.com/robfig/cron/v3"
"gopkg.in/yaml.v2"
)
// DictatorPayload is the incoming payload from Slack
type DictatorPayload struct {
Token string `json:"token"`
TeamID string `json:"team_id"`
TeamDomain string `json:"team_domain"`
ChannelID string `json:"channel_id"`
ChannelName string `json:"channel_name"`
UserID string `json:"user_id"`
UserName string `json:"user_name"`
Command string `json:"text"`
APIAppID string `json:"api_app_id"`
IsEnterpriseInstall string `json:"is_enterprise_install"`
ResponseURL string `json:"response_url"`
TriggerID string `json:"trigger_id"`
}
var config DictatorConfig
// DictatorConfig is the entire configuration for the Bot
type DictatorConfig struct {
DictatorVersion int `yaml:"Dictator_version"`
CamundaHost []struct {
Name string `yaml:"name"`
Port int `yaml:"port"`
Protocol string `yaml:"protocol"`
Host string `yaml:"host"`
} `yaml:"Camunda Host"`
SlackListener []struct {
Name string `yaml:"name"`
Port int `yaml:"port"`
Protocol string `yaml:"protocol"`
Host string `yaml:"host"`
} `yaml:"Slack Listener"`
AuthorizedSenders []struct {
Name string `yaml:"name"`
Username string `yaml:"username"`
IsOnCall bool `yaml:"is-on-call"`
Order int `yaml:"order,omitempty"`
} `yaml:"Authorized senders"`
CurrentOnCall string `yaml:"Current On Call"`
OnCallIndex int `yaml:"On Call Index"`
SlackSecret string `yaml:"Slack Secret"`
TotalOnCall int `yaml:"Total On Call"`
ResponseURL string `yaml:"Response Url"`
ResponseToken string `yaml:"Response Token"`
AppID string `yaml:"AppID"`
ChannelID string `yaml:"Channel ID"`
}
// WriteDictators outputs the entire config file
func WriteDictator() {
taters, err := yaml.Marshal(config)
err = ioutil.WriteFile("./dictator.yaml", taters, 0644)
if err != nil {
panic(err)
}
}
// init_dictators reads the config file and sets up the config struct
func init_dictator(){
dat, err := ioutil.ReadFile("./dictator.yaml")
if err != nil {
log.Fatal("No startup file: ", err)
}
err = yaml.Unmarshal(dat, &config)
if err != nil {
log.Fatal(err)
}
}
// these are all the dictators that can run this command
func getDictators() []string { // test written
var taters []string = make([]string, len(config.AuthorizedSenders))
for x := 0; x < len(config.AuthorizedSenders); x++ {
taters[x] = config.AuthorizedSenders[x].Username
}
return taters
}
func SendDirect(msg_type string) bool { //test written
if msg_type == "directmessage" {
return true
}
return false
}
func getDictatorString() string { // test written
var retValue strings.Builder
retValue.WriteString("*Currently Authorized Benevolent Dictators are:*\n")
for x := 0; x < len(config.AuthorizedSenders); x++ {
retValue.WriteString("• " + config.AuthorizedSenders[x].Name + " (" + config.AuthorizedSenders[x].Username + ")\n")
}
return retValue.String()
}
// this is the rotation order
func getRotation() []string { // test written
var taters []string = make([]string, config.TotalOnCall)
for x := 0; x < len(config.AuthorizedSenders); x++ {
if config.AuthorizedSenders[x].IsOnCall {
taters[config.AuthorizedSenders[x].Order-1] = config.AuthorizedSenders[x].Username
}
}
return taters
}
func getRotationString() string { // test written
var retValue strings.Builder
taters := getRotation()
for x := 0; x < len(taters); x++ {
retValue.WriteString(taters[x])
retValue.WriteString("-->")
}
return strings.TrimRight(retValue.String(), "-->")
}
// this returns who is on-call now from the rotation
func getOnCall() string { // test written
return getRotation()[config.OnCallIndex]
}
func getNextOnCall() string { // test written
if config.OnCallIndex > len(getRotation()) {
return getRotation()[0]
}
return getRotation()[config.OnCallIndex+1]
}
// this returns the index of who is on-call
func getOnCallIndex(newTater string) int { //Test Written
oc := getRotation()
for x := 0; x < len(oc); x++ {
if oc[x] == newTater {
return x
}
}
return config.OnCallIndex
}
// rotates the on-call person index. Returns new on-call person
func rotateOnCallIndex(newTater int) string { // test written
if newTater >= len(getRotation()) {
config.OnCallIndex = 0
} else {
config.OnCallIndex = newTater
}
config.CurrentOnCall = getRotation()[config.OnCallIndex]
return getRotation()[config.OnCallIndex]
}
// rotates the on-call person based on the new name
func rotateOnCall(newTater string) string { // test written
ind := getOnCallIndex(newTater)
config.OnCallIndex = ind
return rotateOnCallIndex(getOnCallIndex(newTater))
}
func checkHeader(key string, data string) bool { // Test Written
// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(sha256.New, []byte(config.SlackSecret))
// Write Data to it
h.Write([]byte(data))
// Get result and encode as hexadecimal string
sha := hex.EncodeToString(h.Sum(nil))
comp := fmt.Sprintf("v0=%s", sha)
return comp == key
}
func validateDictator(newVars map[string]camundaclientgo.Variable, contx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", contx.Task.Id, contx.Task.WorkerId, contx.Task.TopicName)
varb := contx.Task.Variables
// cmd, err := url.QueryUnescape(fmt.Sprintf("%v", newVars["command"].Value))
// if err != nil {
// WriteDictator()
// log.Fatal(err)
// return err
// }
// fmt.Println("validate_dictator Command:", cmd)
// fmt.Println("Sender: ", varb["sender"].Value)
senderOk := isValueInList(fmt.Sprintf("%v", varb["sender"].Value), getDictators())
if varb["sender"].Value == "dictatorbot" {
senderOk = true
}
vars := make(map[string]camundaclientgo.Variable)
//stat := camundaclientgo.Variable{Value: "true", Type: "boolean"}
//com :=
vars["senderOk"] = camundaclientgo.Variable{Value: senderOk, Type: "boolean"}
vars["status"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
if !senderOk {
vars["message_type"] = camundaclientgo.Variable{Value: "failure", Type: "string"}
} else {
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
}
err := contx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
WriteDictator()
return err
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
}
func startCamundaProcess(data DictatorPayload) {
opts := camundaclientgo.ClientOptions{}
opts.ApiPassword = "demo"
opts.ApiUser = "demo"
opts.EndpointUrl = config.CamundaHost[0].Protocol + "://" + config.CamundaHost[0].Host + ":" + fmt.Sprint(config.CamundaHost[0].Port) + "/engine-rest"
// camundaclientgo.ClientOptions{
// // this should use values from the config file
// EndpointUrl: config.CamundaHost[0].Protocol + "://" + config.CamundaHost[0].Host + ":" + fmt.Sprint(config.CamundaHost[0].Port) + "/engine-rest", //"https://davidgs.com:8443/engine-rest",
// ApiUser: "demo",
// ApiPassword: "demo",
// Timeout: time.Second * 10,
// })
messageName := "Query_dictator"
processKey := "DictatorBot"
variables := map[string]camundaclientgo.Variable{
"command": {Value: strings.TrimSpace(data.Command), Type: "string"},
"sender": {Value: data.UserName, Type: "string"},
"token": {Value: data.Token, Type: "string"},
"channel_id": {Value: data.ChannelID, Type: "string"},
"channel_name": {Value: data.ChannelName, Type: "string"},
"response_url": {Value: data.ResponseURL, Type: "string"},
"user_id": {Value: data.UserID, Type: "string"},
"api_app_id": {Value: data.APIAppID, Type: "string"},
}
client := camundaclientgo.NewClient(opts)
reqMessage := camundaclientgo.ReqMessage{}
reqMessage.MessageName = messageName
reqMessage.BusinessKey = processKey
reqMessage.ProcessVariables = &variables
err := client.Message.SendMessage(&reqMessage)
// _, err := client.ProcessDefinition.StartInstance(
// camundaclientgo.QueryProcessDefinitionBy{Key: &processKey},
// camundaclientgo.ReqStartInstance{Variables: &variables},
// )
if err != nil {
log.Printf("Error starting process: %s\n", err)
return
}
}
// Handles all the incomming https requests
func dictator(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
// log.Println("GET Method Not Supported")
http.Error(w, "GET Method not supported", 400)
} else {
key := r.Header.Get("X-Slack-Signature")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
timestamp := r.Header.Get("X-Slack-Request-Timestamp")
step1 := strings.ReplaceAll(string(body), "&", "\", \"")
step2 := strings.ReplaceAll(step1, "=", "\": \"")
step1 = fmt.Sprintf("{\"%s\"}", step2)
var t DictatorPayload
err = json.Unmarshal([]byte(step1), &t)
if err != nil {
panic(err)
}
signedData := fmt.Sprintf("v0:%s:%s", timestamp, string(body))
if err != nil {
WriteDictator()
log.Fatal(err)
}
if !checkHeader(key, signedData) {
w.WriteHeader(400)
return
}
// log.Println(t.Command)
w.WriteHeader(200)
startCamundaProcess(t)
}
}
// is a value in the array?
func isValueInList(value string, list []string) bool { // Test Written
for _, v := range list {
if v == value {
return true
}
}
return false
}
func RunEverySecond() {
var data DictatorPayload = DictatorPayload{}
data.Command = "update"
data.UserID = "dictatorbot"
data.UserName = "dictatorbot"
data.ChannelID = config.ChannelID
data.Token = config.ResponseToken
data.ChannelID = config.ChannelID
data.ResponseURL = config.ResponseURL
data.APIAppID = config.AppID
startCamundaProcess(data)
// fmt.Println("Every minute")
}
func main() {
init_dictator()
fmt.Println("Starting up ... ")
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
WriteDictator()
os.Exit(1)
}()
// cro := cron.New()
// cro.AddFunc("0 12 * * MON", func() {
// RunEverySecond()
// })
// cro.Start()
client := camundaclientgo.NewClient(camundaclientgo.ClientOptions{
EndpointUrl: config.CamundaHost[0].Protocol + "://" + config.CamundaHost[0].Host + ":" + fmt.Sprint(config.CamundaHost[0].Port) + "/engine-rest",
// ApiUser: "demo",
// ApiPassword: "demo",
// RESET to 10
Timeout: time.Second * 10,
})
logger := func(err error) {
fmt.Println(err.Error())
}
proc := processor.NewProcessor(client, &processor.ProcessorOptions{
WorkerId: "dictatorBot",
LockDuration: time.Second * 5,
MaxTasks: 10,
MaxParallelTaskPerHandler: 100,
LongPollingTimeout: 5 * time.Second,
}, logger)
proc.AddHandler( // validate proper sender validate_dictator
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "validate_dictator"},
},
func(ctx *processor.Context) error {
return validateDictator(ctx.Task.Variables, ctx)
},
)
proc.AddHandler( // get authorized users sender get_auth
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "get_auth"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
vars := make(map[string]camundaclientgo.Variable)
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
vars["message"] = camundaclientgo.Variable{Value: getDictatorString(), Type: "string"}
err := ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
},
)
proc.AddHandler( // see who is on call whos_oncall
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "whos_oncall"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
vars := make(map[string]camundaclientgo.Variable)
body := fmt.Sprintf("<@%s> is the person on-call this week.", getOnCall())
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
vars["on-call"] = camundaclientgo.Variable{Value: getOnCall(), Type: "string"}
vars["message"] = camundaclientgo.Variable{Value: body, Type: "string"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
},
)
proc.AddHandler( // get the entire rotation scheme get_rotation
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "get_rotation"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
msg := fmt.Sprintf("The on-call rotation schedule is:\n *%s* \nand *%s* is the on-call Dictator", getRotationString(), getOnCall())
vars := make(map[string]camundaclientgo.Variable)
vars["message"] = camundaclientgo.Variable{Value: msg, Type: "string"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
},
)
proc.AddHandler( // get who is next in the rotation get_next
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "get_next"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
vars := make(map[string]camundaclientgo.Variable)
msg := fmt.Sprintf("The next person on-call is <@%s>", getNextOnCall())
vars["message"] = camundaclientgo.Variable{Value: msg, Type: "string"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
},
)
proc.AddHandler( // make sure that the updated dictator is allowed check_new_oncall
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "check_new_oncall"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
varb := ctx.Task.Variables
text := fmt.Sprintf("%v", varb["command"].Value)
text, err = url.QueryUnescape(text)
if err != nil {
WriteDictator()
log.Fatal(err)
}
newTater := strings.TrimLeft(text, "@")
vars := make(map[string]camundaclientgo.Variable)
if !isValueInList(newTater, getRotation()) {
//if getOnCallIndex(config, newTater) < 0 {
vars["onCallOK"] = camundaclientgo.Variable{Value: "false", Type: "boolean"}
vars["message_type"] = camundaclientgo.Variable{Value: "failure", Type: "string"}
} else {
vars["onCallOK"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
}
if newTater == "update" {
thisTater := getOnCallIndex(getOnCall())
rotateOnCallIndex(thisTater+1)
vars["onCallOK"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
// fmt.Printf("Task %s completed\nTask Command: %s\nTask Result: %s", ctx.Task.Id, text, getOnCall())
return nil
},
)
proc.AddHandler( // set the new on-call dictator update_oncall
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "update_oncall"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
varb := ctx.Task.Variables
var timer string
if varb["command"].Value == nil {
timer = "timer"
}
if timer == "timer" {
// fmt.Println("Timer event fired!")
vars := make(map[string]camundaclientgo.Variable)
lastTater := getOnCall()
if config.OnCallIndex+1 >= len(getRotation()) {
rotateOnCallIndex(0)
} else {
rotateOnCallIndex(config.OnCallIndex+1)
}
thisTater := getOnCall()
msg := fmt.Sprintf("<@%s> has been relieved of duty and <@%s> is now the on-call person", lastTater, thisTater)
vars["message"] = camundaclientgo.Variable{Value: msg, Type: "string"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
vars["command"] = camundaclientgo.Variable{Value: "update", Type: "string"}
vars["senderOk"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
vars["onCallOK"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
fmt.Println(msg)
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
// fmt.Printf("Task %s completed\nTask Command: %s\nTask Result: %s", ctx.Task.Id, "Timer Event", getOnCall())
return nil
} else {
text := fmt.Sprintf("%v", varb["command"].Value)
fmt.Printf("Get Auth: %v\n", varb["command"].Value)
newTater, err := url.QueryUnescape(text)
if err != nil {
WriteDictator()
log.Fatal(err)
}
newTater = strings.TrimLeft(newTater, "@")
newTater = rotateOnCall(newTater)
vars := make(map[string]camundaclientgo.Variable)
lastTater := fmt.Sprintf("%v", varb["sender"].Value)
msg := fmt.Sprintf("<@%s> has made a change and <@%s> is now the on-call person", lastTater, newTater)
vars["message"] = camundaclientgo.Variable{Value: msg, Type: "string"}
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
// fmt.Printf("Task %s completed\nTask Command: %s\nTask Result: %s\n", ctx.Task.Id, text, getOnCall())
return nil
}
},
)
proc.AddHandler( // format a message format_message
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "format_message"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
varb := ctx.Task.Variables
var body string
vars := make(map[string]camundaclientgo.Variable)
if varb["senderOk"].Value != nil {
if varb["senderOk"].Value == "false" {
body = ":X: Nice try, but only Benevolent Dictators (Moderators) may use this bot."
vars["message_type"] = camundaclientgo.Variable{Value: "failure", Type: "string"}
vars["message"] = camundaclientgo.Variable{Value: body, Type: "string"}
}
if varb["onCallOK"].Value != nil {
if varb["onCallOK"].Value == false {
comm := fmt.Sprintf("%v", varb["command"].Value)
comm, err := url.QueryUnescape(comm)
if err != nil {
WriteDictator()
log.Fatal(err)
}
comm = strings.TrimLeft(comm, "@")
body = fmt.Sprintf("You cannot nominate <@%s> because they are not a Benevolent Dictator!", comm)
vars["message_type"] = camundaclientgo.Variable{Value: "failure", Type: "string"}
vars["message"] = camundaclientgo.Variable{Value: body, Type: "string"}
}
}
} else {
body = fmt.Sprintf("%v", varb["message"])
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
}
err := ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
// fmt.Printf("Task %s completed\nTask Command: %s\nTask Result: %s", ctx.Task.Id, text, getOnCall())
return nil
},
)
proc.AddHandler( // send the message send_message
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "send_message"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
varb := ctx.Task.Variables
msg_type := fmt.Sprintf("%v", varb["message_type"].Value)
var final_msg string
if msg_type == "failure" {
final_msg = fmt.Sprintf(":X: %v %s", varb["message"].Value, ":unamused:")
} else {
final_msg = fmt.Sprintf(":white_check_mark: %v ", varb["message"].Value)
}
var err error
reply_url := fmt.Sprintf("%v", varb["response_url"].Value)
response_type := fmt.Sprintf("%v", varb["channel_name"].Value)
if varb["channel_name"].Value == nil {
response_type = "channel"
}
var channel_id string
if varb["channel_id"].Value == nil {
channel_id = "C01TA9C0FJL" // "G0A7K9GPN"
} else {
channel_id = fmt.Sprintf("%v", varb["channel_id"].Value)
}
command := fmt.Sprintf("%v", varb["command"].Value)
command, err = url.QueryUnescape(command)
if err != nil {
WriteDictator()
log.Fatal(err)
}
if SendDirect(response_type) {
reply_url, err = url.QueryUnescape(reply_url)
if err != nil {
WriteDictator()
log.Fatal(err)
}
reqBody, err := json.Marshal(map[string]string{
"response_type": "message",
"replace_original": "false",
"text": final_msg,
})
if err != nil {
WriteDictator()
log.Fatal(err)
}
resp, err := http.Post(reply_url, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
WriteDictator()
log.Fatal(err)
}
defer resp.Body.Close()
} else {
reply_url = config.ResponseURL + "?token=" + config.ResponseToken + "&channel=" + channel_id + "&text=" + url.QueryEscape(final_msg)
resp, err := http.Get(reply_url)
if err != nil {
WriteDictator()
log.Fatal(err)
}
defer resp.Body.Close()
}
vars := make(map[string]camundaclientgo.Variable)
vars["complete"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
// fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
return nil
},
)
proc.AddHandler( // send the help/usage message get_help
&[]camundaclientgo.QueryFetchAndLockTopic{
{TopicName: "get_help"},
},
func(ctx *processor.Context) error {
// fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)
var err error
vars := make(map[string]camundaclientgo.Variable)
body := ` *Available commands are:*
1) _help_ or _?_
2) _rotate_ or _rotation_ to get the full rotation schedule
3) _who_ to see who the current on-call person is
4) _next_ to see who the next on-call person will be
5) _@username_ to place someone on-call
6) _auth_ or _authorized_ to see who is authorized to use the DictatorBot
7) _update_ to place the next person in the rotation on-call`
vars["message_type"] = camundaclientgo.Variable{Value: "success", Type: "string"}
vars["message"] = camundaclientgo.Variable{Value: body, Type: "string"}
vars["onCallOK"] = camundaclientgo.Variable{Value: "true", Type: "boolean"}
err = ctx.Complete(processor.QueryComplete{
Variables: &vars,
})
if err != nil {
fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
}
//fmt.Printf("Task %s completed\nTask Command: %s\nTask Result: %s", ctx.Task.Id, text, getOnCall())
return nil
},
)
http.HandleFunc("/dictator", dictator)
if config.SlackListener[0].Protocol == "https" {
err := http.ListenAndServeTLS(":"+fmt.Sprint(config.SlackListener[0].Port), "/home/davidgs/.node-red/combined", "/home/davidgs/.node-red/combined", nil) // set listen port
if err != nil {
log.Fatal("ListenAndServeTLS: ", err)
}
} else {
err := http.ListenAndServe(":"+fmt.Sprint(config.SlackListener[0].Port), nil) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
}
|
package storage
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/google/uuid"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
"github.com/openshift/oc-mirror/pkg/api/v1alpha2"
"github.com/openshift/oc-mirror/pkg/config"
)
func TestLocalBackend(t *testing.T) {
underlyingFS := afero.NewMemMapFs()
backend := localDirBackend{
fs: underlyingFS,
dir: filepath.Join("foo", config.SourceDir),
}
require.NoError(t, backend.init())
m := &v1alpha2.Metadata{}
m.Uid = uuid.New()
m.PastMirror = v1alpha2.PastMirror{
Timestamp: int(time.Now().Unix()),
Sequence: 1,
Mirror: v1alpha2.Mirror{
Platform: v1alpha2.Platform{
Channels: []v1alpha2.ReleaseChannel{
{Name: "stable-4.7", MinVersion: "4.7.13"},
},
},
Operators: []v1alpha2.Operator{
{Catalog: "registry.redhat.io/openshift/redhat-operators:v4.7"},
},
},
Operators: []v1alpha2.OperatorMetadata{
{
Catalog: "registry.redhat.io/openshift/redhat-operators:v4.7",
ImagePin: "registry.redhat.io/openshift/redhat-operators@sha256:a05ed1726b3cdc16e694b8ba3e26e834428a0fa58bc220bb0e07a30a76a595a6",
},
},
}
ctx := context.Background()
require.NoError(t, backend.WriteMetadata(ctx, m, config.MetadataBasePath))
info, metadataErr := underlyingFS.Stat("foo/src/publish/.metadata.json")
require.NoError(t, metadataErr)
require.True(t, info.Mode().IsRegular())
info, metadataErr = backend.fs.Stat("publish/.metadata.json")
require.NoError(t, metadataErr)
require.True(t, info.Mode().IsRegular())
info, metadataErr = backend.Stat(ctx, "publish/.metadata.json")
require.NoError(t, metadataErr)
require.True(t, info.Mode().IsRegular())
_, metadataErr = backend.Open(ctx, "publish/.metadata.json")
require.NoError(t, metadataErr)
readMeta := &v1alpha2.Metadata{}
require.NoError(t, backend.ReadMetadata(ctx, readMeta, config.MetadataBasePath))
require.Equal(t, m, readMeta)
metadataErr = backend.Cleanup(ctx, config.MetadataBasePath)
require.NoError(t, metadataErr)
require.ErrorIs(t, backend.ReadMetadata(ctx, readMeta, config.MetadataBasePath), ErrMetadataNotExist)
type object struct {
SomeData string
}
inObj := object{
SomeData: "bar",
}
require.NoError(t, backend.WriteObject(ctx, "bar-obj.json", inObj))
info, objErr := underlyingFS.Stat("foo/src/bar-obj.json")
require.NoError(t, objErr)
require.True(t, info.Mode().IsRegular())
info, objErr = backend.fs.Stat("bar-obj.json")
require.NoError(t, objErr)
require.True(t, info.Mode().IsRegular())
var outObj object
require.NoError(t, backend.ReadObject(ctx, "bar-obj.json", &outObj))
require.Equal(t, inObj, outObj)
}
|
package server
import (
"github.com/go-chi/chi"
"github.com/sergeychur/avito_auto/internal/models"
"github.com/sergeychur/avito_auto/internal/repository"
"log"
"net/http"
)
func (server *Server) CreateLink(w http.ResponseWriter, r *http.Request) {
link := models.Link{}
err := ReadFromBody(r, w, &link)
if err != nil {
log.Println("Cannot read from body because of: ", err)
WriteToResponse(w, http.StatusBadRequest, nil)
return
}
err = server.Validator.ValidateLink(link)
if err != nil {
log.Println("URL is invalid: ", err)
WriteToResponse(w, http.StatusBadRequest, "Link is invalid")
return
}
status, link := server.Repo.InsertLink(link)
DealRequestFromRepo(w, &link, status)
}
func (server *Server) GetLink(w http.ResponseWriter, r *http.Request) {
shortcut := chi.URLParam(r, "shortcut")
status, newUrl := server.Repo.GetLink(shortcut)
if status != repository.OK {
DealRequestFromRepo(w, nil, status)
return
}
http.Redirect(w, r, newUrl, http.StatusSeeOther)
}
|
package main
import "fmt"
func main() {
var height int
var length int
fmt.Scan(&height, &length)
fmt.Println(height*length, (height+length)*2)
}
|
package api_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/go-test/deep"
"github.com/porter-dev/porter/internal/auth/token"
"github.com/porter-dev/porter/internal/models"
)
// ------------------------- TEST TYPES AND MAIN LOOP ------------------------- //
type userTest struct {
initializers []func(t *tester)
msg string
method string
endpoint string
body string
expStatus int
expBody string
useCookie bool
validators []func(c *userTest, tester *tester, t *testing.T)
}
func testUserRequests(t *testing.T, tests []*userTest, canQuery bool) {
for _, c := range tests {
// create a new tester
tester := newTester(canQuery)
// if there's an initializer, call it
for _, init := range c.initializers {
init(tester)
}
req, err := http.NewRequest(
c.method,
c.endpoint,
strings.NewReader(c.body),
)
tester.req = req
if c.useCookie {
req.AddCookie(tester.cookie)
}
if err != nil {
t.Fatal(err)
}
tester.execute()
rr := tester.rr
// first, check that the status matches
if status := rr.Code; status != c.expStatus {
t.Errorf("%s, handler returned wrong status code: got %v want %v",
c.msg, status, c.expStatus)
}
// if there's a validator, call it
for _, validate := range c.validators {
validate(c, tester, t)
}
}
}
// ------------------------- TEST FIXTURES AND FUNCTIONS ------------------------- //
var authCheckTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Auth check successful. User is logged in.",
method: "GET",
endpoint: "/api/auth/check",
expStatus: http.StatusOK,
body: "",
expBody: `{"id":1,"email":"belanger@getporter.dev"}`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Auth check failure. User is not logged in.",
method: "GET",
endpoint: "/api/auth/check",
body: "",
expStatus: http.StatusForbidden,
expBody: http.StatusText(http.StatusForbidden) + "\n",
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleAuthCheck(t *testing.T) {
testUserRequests(t, authCheckTests, true)
}
func TestHandleAuthCheckToken(t *testing.T) {
tester := newTester(true)
initUserDefault(tester)
initProject(tester)
// generate a new token
tokGen, _ := token.GetTokenForAPI(1, 1)
tok, _ := tokGen.EncodeToken(&token.TokenGeneratorConf{
TokenSecret: "secret",
})
req, err := http.NewRequest(
"GET",
"/api/auth/check",
strings.NewReader(""),
)
tester.req = req
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tok))
tester.execute()
rr := tester.rr
if err != nil {
t.Fatal(err)
}
// first, check that the status matches
if status := rr.Code; status != 200 {
t.Errorf("%s, handler returned wrong status code: got %v want %v",
"auth check token", status, 200)
}
gotBody := &models.UserExternal{}
expBody := &models.UserExternal{}
json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev"}`), expBody)
if !reflect.DeepEqual(gotBody, expBody) {
t.Errorf("%s, handler returned wrong body: got %v want %v",
"auth check token", gotBody, expBody)
}
}
var createUserTests = []*userTest{
&userTest{
msg: "Create user",
method: "POST",
endpoint: "/api/users",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusCreated,
expBody: `{"id":1,"email":"belanger@getporter.dev"}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userModelBodyValidator,
},
},
&userTest{
msg: "Create user invalid email",
method: "POST",
endpoint: "/api/users",
body: `{
"email": "notanemail",
"password": "hello"
}`,
expStatus: http.StatusUnprocessableEntity,
expBody: `{"code":601,"errors":["email validation failed"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
msg: "Create user missing field",
method: "POST",
endpoint: "/api/users",
body: `{
"password": "hello"
}`,
expStatus: http.StatusUnprocessableEntity,
expBody: `{"code":601,"errors":["required validation failed"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Create user same email",
method: "POST",
endpoint: "/api/users",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusUnprocessableEntity,
expBody: `{"code":601,"errors":["email already taken"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
msg: "Create user invalid field type",
method: "POST",
endpoint: "/api/users",
body: `{
"email": "belanger@getporter.dev",
"password": 0
}`,
expStatus: http.StatusBadRequest,
expBody: `{"code":600,"errors":["could not process request"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleCreateUser(t *testing.T) {
testUserRequests(t, createUserTests, true)
}
var createUserTestsWriteFail = []*userTest{
&userTest{
msg: "Create user db connection down",
method: "POST",
endpoint: "/api/users",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusInternalServerError,
expBody: `{"code":500,"errors":["could not read from database"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleCreateUserWriteFail(t *testing.T) {
testUserRequests(t, createUserTestsWriteFail, false)
}
var loginUserTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Login user successful",
method: "POST",
endpoint: "/api/login",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusOK,
expBody: `{"id":1,"email":"belanger@getporter.dev"}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Login user already logged in",
method: "POST",
endpoint: "/api/login",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusOK,
expBody: `{"id":1,"email":"belanger@getporter.dev"}`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
msg: "Login user unregistered email",
method: "POST",
endpoint: "/api/login",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusUnauthorized,
expBody: `{"code":401,"errors":["email not registered"]}`,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Login user incorrect password",
method: "POST",
endpoint: "/api/login",
body: `{
"email": "belanger@getporter.dev",
"password": "notthepassword"
}`,
expStatus: http.StatusUnauthorized,
expBody: `{"code":401,"errors":["incorrect password"]}`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleLoginUser(t *testing.T) {
testUserRequests(t, loginUserTests, true)
}
var logoutUserTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Logout user successful",
method: "POST",
endpoint: "/api/logout",
body: `{
"email": "belanger@getporter.dev",
"password": "hello"
}`,
expStatus: http.StatusOK,
expBody: ``,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
func(c *userTest, tester *tester, t *testing.T) {
req, err := http.NewRequest(
"GET",
"/api/users/1",
strings.NewReader(""),
)
req.AddCookie(tester.cookie)
if err != nil {
t.Fatal(err)
}
rr2 := httptest.NewRecorder()
tester.router.ServeHTTP(rr2, req)
if status := rr2.Code; status != http.StatusForbidden {
t.Errorf("%s, handler returned wrong status: got %v want %v",
"validator failed", status, http.StatusForbidden)
}
},
},
},
}
func TestHandleLogoutUser(t *testing.T) {
testUserRequests(t, logoutUserTests, true)
}
var readUserTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Read user successful",
method: "GET",
endpoint: "/api/users/1",
body: "",
expStatus: http.StatusOK,
expBody: `{"id":1,"email":"belanger@getporter.dev"}`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userModelBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Read user unauthorized",
method: "GET",
endpoint: "/api/users/2",
body: "",
expStatus: http.StatusForbidden,
expBody: http.StatusText(http.StatusForbidden) + "\n",
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleReadUser(t *testing.T) {
testUserRequests(t, readUserTests, true)
}
var listUserProjectsTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
initProject,
},
msg: "List user projects successful",
method: "GET",
endpoint: "/api/users/1/projects",
body: "",
expStatus: http.StatusOK,
expBody: `[{"id":1,"name":"project-test","roles":[{"id":0,"kind":"admin","user_id":1,"project_id":1}]}]`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userProjectsListValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "List user projects unauthorized",
method: "GET",
endpoint: "/api/users/2/projects",
body: "",
expStatus: http.StatusForbidden,
expBody: http.StatusText(http.StatusForbidden) + "\n",
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleListUserProjects(t *testing.T) {
testUserRequests(t, listUserProjectsTests, true)
}
var deleteUserTests = []*userTest{
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Delete user successful",
method: "DELETE",
endpoint: "/api/users/1",
body: `{"password":"hello"}`,
expStatus: http.StatusNoContent,
expBody: "",
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
func(c *userTest, tester *tester, t *testing.T) {
req, err := http.NewRequest(
"GET",
"/api/users/1",
strings.NewReader(""),
)
req.AddCookie(tester.cookie)
if err != nil {
t.Fatal(err)
}
rr2 := httptest.NewRecorder()
tester.router.ServeHTTP(rr2, req)
gotBody := &models.UserExternal{}
expBody := &models.UserExternal{}
if status := rr2.Code; status != 404 {
t.Errorf("DELETE user validation, handler returned wrong status code: got %v want %v",
status, 404)
}
json.Unmarshal(rr2.Body.Bytes(), gotBody)
json.Unmarshal([]byte(`{"code":602,"errors":["could not find requested object"]}`), expBody)
if !reflect.DeepEqual(gotBody, expBody) {
t.Errorf("%s, handler returned wrong body: got %v want %v",
"validator failed", gotBody, expBody)
}
},
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Delete user invalid id",
method: "DELETE",
endpoint: "/api/users/aldkjf",
body: `{"password":"hello"}`,
expStatus: http.StatusForbidden,
expBody: http.StatusText(http.StatusForbidden) + "\n",
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
&userTest{
initializers: []func(tester *tester){
initUserDefault,
},
msg: "Delete user missing password",
method: "DELETE",
endpoint: "/api/users/1",
body: `{}`,
expStatus: http.StatusUnprocessableEntity,
expBody: `{"code":601,"errors":["required validation failed"]}`,
useCookie: true,
validators: []func(c *userTest, tester *tester, t *testing.T){
userBasicBodyValidator,
},
},
}
func TestHandleDeleteUser(t *testing.T) {
testUserRequests(t, deleteUserTests, true)
}
// ------------------------- INITIALIZERS AND VALIDATORS ------------------------- //
func initUserDefault(tester *tester) {
tester.createUserSession("belanger@getporter.dev", "hello")
}
func initUserAlt(tester *tester) {
tester.createUserSession("test@test.it", "hello")
}
func userBasicBodyValidator(c *userTest, tester *tester, t *testing.T) {
if body := tester.rr.Body.String(); strings.TrimSpace(body) != strings.TrimSpace(c.expBody) {
t.Errorf("%s, handler returned wrong body: got %v want %v",
c.msg, body, c.expBody)
}
}
func userModelBodyValidator(c *userTest, tester *tester, t *testing.T) {
gotBody := &models.UserExternal{}
expBody := &models.UserExternal{}
json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
json.Unmarshal([]byte(c.expBody), expBody)
if !reflect.DeepEqual(gotBody, expBody) {
t.Errorf("%s, handler returned wrong body: got %v want %v",
c.msg, gotBody, expBody)
}
}
func userProjectsListValidator(c *userTest, tester *tester, t *testing.T) {
gotBody := make([]*models.ProjectExternal, 0)
expBody := make([]*models.ProjectExternal, 0)
json.Unmarshal(tester.rr.Body.Bytes(), &gotBody)
json.Unmarshal([]byte(c.expBody), &expBody)
if diff := deep.Equal(gotBody, expBody); diff != nil {
t.Errorf("handler returned wrong body:\n")
t.Error(diff)
}
}
|
// Copyright 2016 The Lucas Alves Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package payable
import (
"github.com/luk4z7/pagarme-go/auth"
liberr "github.com/luk4z7/pagarme-go/error"
"github.com/luk4z7/pagarme-go/lib/payable"
"github.com/luk4z7/pagarme-go/repository"
"net/url"
)
var repositoryPayable repository.Repository
const (
endPoint = "https://api.pagar.me/1/transactions"
)
type TransactionPayable struct {
payable payable.Payable
}
func (s *TransactionPayable) Get(p url.Values, h auth.Headers) (payable.Payable, error, liberr.ErrorsAPI) {
route := endPoint + "/" + p.Get("transaction_id") + "/payables/" + p.Get("id")
_, err, errApi := repositoryPayable.Get(url.Values{"route": {route}}, &s.payable, h)
return s.payable, err, errApi
}
func (s *TransactionPayable) GetAll(p url.Values, h auth.Headers) ([]payable.Payable, error, liberr.ErrorsAPI) {
res := []payable.Payable{}
route := endPoint + "/" + p.Get("transaction_id") + "/payables"
_, err, errApi := repositoryPayable.Get(url.Values{"route": {route}}, &res, h)
return res, err, errApi
}
|
package main
import (
"fmt"
"github.com/tietang/props/ini"
"github.com/tietang/props/kvs"
)
func main() {
path := kvs.GetCurrentFilePath("config.ini", 1)
conf := ini.NewIniFileCompositeConfigSource(path)
appName := conf.GetDefault("app.name", "test")
appPort := conf.GetIntDefault("app.server.port", 8080)
appEnable := conf.GetBoolDefault("app.enable", false)
fmt.Println(appName)
fmt.Println(appPort)
fmt.Println(appEnable)
}
|
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package security
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"hash/crc32"
"io/ioutil"
"math/rand"
"time"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
)
const (
// Length of the join token shared secret.
joinTokenSecretLen = 16
// JoinTokenExpiration is the default expiration time of newly created join
// tokens.
JoinTokenExpiration = 30 * time.Minute
)
// JoinToken is a container for a TokenID and associated SharedSecret for use
// in certificate-free add/join operations.
type JoinToken struct {
TokenID uuid.UUID
SharedSecret []byte
fingerprint []byte
}
// GenerateJoinToken generates a new join token, and signs it with the CA cert
// in the certificate manager.
func GenerateJoinToken(cm *CertificateManager) (JoinToken, error) {
var jt JoinToken
jt.TokenID = uuid.MakeV4()
r := rand.New(rand.NewSource(timeutil.Now().UnixNano()))
jt.SharedSecret = randutil.RandBytes(r, joinTokenSecretLen)
jt.sign(cm.CACert().FileContents)
return jt, nil
}
// sign signs the provided CA cert using the shared secret, and sets the
// fingerprint field on the join token to the HMAC signature.
func (j *JoinToken) sign(caCert []byte) {
signer := hmac.New(sha256.New, j.SharedSecret)
_, _ = signer.Write(caCert)
j.fingerprint = signer.Sum(nil)
}
// VerifySignature verifies that the fingerprint provided in the join token
// matches the signature of the provided CA cert with the join token's shared
// secret.
func (j *JoinToken) VerifySignature(caCert []byte) bool {
signer := hmac.New(sha256.New, j.SharedSecret)
_, _ = signer.Write(caCert)
// TODO(aaron-crl): Avoid timing attacks here.
return bytes.Equal(signer.Sum(nil), j.fingerprint)
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
//
// The format of the text (after base64-decoding) is:
// <TokenID:uuid.Size><SharedSecret:joinTokenSecretLen><fingerprint:variable><crc:4>
func (j *JoinToken) UnmarshalText(text []byte) error {
decoder := base64.NewDecoder(base64.URLEncoding, bytes.NewReader(text))
decoded, err := ioutil.ReadAll(decoder)
if err != nil {
return err
}
if len(decoded) <= uuid.Size+joinTokenSecretLen+4 {
return errors.New("invalid join token")
}
expectedCSum := crc32.ChecksumIEEE(decoded[:len(decoded)-4])
_, cSum, err := encoding.DecodeUint32Ascending(decoded[len(decoded)-4:])
if err != nil {
return err
}
if cSum != expectedCSum {
return errors.New("invalid join token")
}
if err := j.TokenID.UnmarshalBinary(decoded[:uuid.Size]); err != nil {
return err
}
decoded = decoded[uuid.Size:]
j.SharedSecret = decoded[:joinTokenSecretLen]
j.fingerprint = decoded[joinTokenSecretLen : len(decoded)-4]
return nil
}
// MarshalText implements the encoding.TextMarshaler interface.
func (j *JoinToken) MarshalText() ([]byte, error) {
tokenID, err := j.TokenID.MarshalBinary()
if err != nil {
return nil, err
}
if len(j.SharedSecret) != joinTokenSecretLen {
return nil, errors.New("join token shared secret not of the right size")
}
token := make([]byte, 0, len(tokenID)+len(j.SharedSecret)+len(j.fingerprint)+4)
token = append(token, tokenID...)
token = append(token, j.SharedSecret...)
token = append(token, j.fingerprint...)
// Checksum.
cSum := crc32.ChecksumIEEE(token)
token = encoding.EncodeUint32Ascending(token, cSum)
var b bytes.Buffer
encoder := base64.NewEncoder(base64.URLEncoding, &b)
if _, err := encoder.Write(token); err != nil {
return nil, err
}
if err := encoder.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
|
package terminal
import (
"fmt"
"learn/src/go-talker/log"
"sync"
"github.com/cjbassi/termui"
)
type MessageBox struct {
*termui.Block
Messages []Message
Boxes []Box
MessageChan chan *Message
InChan chan *Message
locker sync.Mutex
showIndex int32
lastIndex int32
}
func (self *MessageBox) AddMessage(message Message) {
self.locker.Lock()
self.Messages = append(self.Messages, message)
self.locker.Unlock()
self.InChan <- &message
}
func NewMessageBox() *MessageBox {
return &MessageBox{
Block: termui.NewBlock(),
Messages: []Message{},
Boxes: make([]Box, 0),
MessageChan: make(chan *Message, 0),
InChan: make(chan *Message, 0),
}
}
type Message struct {
Content string //消息内容
Name string //消息发送者名称
Time int64 //发送消息时间
}
type Box struct {
message *Message
index int32
}
func NewMessageList() *MessageBox {
return &MessageBox{
Block: termui.NewBlock(),
}
}
func (self *MessageBox) Buffer() *termui.Buffer {
log.Logger.Info("bbbbbbbbbbbbb", len(self.Messages))
self.locker.Lock()
buf := self.Block.Buffer()
width := self.X - 4
y := self.Block.Y
y2 := y/2 - 1
if len(self.Messages) > y2 {
i := len(self.Messages) - y2
shown := self.Messages[i:]
for _i, _v := range shown {
fmtMessage := messageFormatter(_v.Name, _v.Content)
if len(fmtMessage) > width {
firstLine := fmtMessage[:width+1]
secondLine := fmtMessage[width+1:]
if len(secondLine) > width-6 {
secondLine = secondLine[:width-6] + "…"
}
buf.SetString(2, 1+2*_i, firstLine, 35, 47)
buf.SetString(4, 2+2*_i, secondLine, 35, 47)
} else {
buf.SetString(2, 1+2*_i, fmtMessage, 35, 47)
}
}
} else {
for _i, _v := range self.Messages {
fmtMessage := messageFormatter(_v.Name, _v.Content)
if len(fmtMessage) > width {
firstLine := fmtMessage[:width+1]
secondLine := fmtMessage[width+1:]
if len(secondLine) > width-6 {
secondLine = secondLine[:width-6] + "…"
}
buf.SetString(2, 1+2*_i, firstLine, 35, 47)
buf.SetString(4, 2+2*_i, secondLine, 35, 47)
} else {
buf.SetString(2, 1+2*_i, fmtMessage, 35, 47)
}
}
}
self.locker.Unlock()
return buf
}
func messageFormatter(name, content string) string {
return fmt.Sprintf("[%s]: %s", name, content)
}
|
package go_wasm_exec
func NewGlobal(fs Value) Object {
return NewObject(ObjectClass, map[string]Value{
"fs": fs,
"Object": ValueOf(ObjectClass),
"Array": ValueOf(ArrayClass),
"Function": ValueOf(FunctionClass),
"Uint8Array": ValueOf(Uint8ArrayClass),
})
}
|
package main
import (
"log"
"net/http"
"strings"
"time"
"github.com/Unknwon/com"
)
func main() {
log.Println("201402191")
client := &http.Client{}
p, err := com.HttpGetBytes(client, "http://godoc.org/-/index", nil)
if err != nil {
log.Fatalf("Fail to load page: %v", err)
}
content := string(p)
start := strings.Index(content, "<tbody>") + 7
end := strings.Index(content, "</tbody>")
content = content[start:end]
pkgs := strings.Split(content, "<tr>")[1:]
skipUntilIndex := 9052
endWhenIndex := 12000
for i, name := range pkgs {
if i < skipUntilIndex {
continue
} else if i == endWhenIndex {
break
}
name = strings.TrimSpace(name)[14:]
end := strings.Index(name, "\">")
name = name[:end]
log.Printf("#%d %s", i, name)
_, err = com.HttpGet(client, "https://gowalker.org/"+name, nil)
if err != nil {
log.Fatalf("Fail to load page: %v", err)
}
time.Sleep(0 * time.Second)
}
}
|
// Copyright 2021 Comcast Cable Communications Management, 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 classification EARS
//
// Documentation EARS API
//
// Schemes: https
// BasePath: /ears
// Version: 1.0.0
// Host: qa.gears.comcast.com
//
// Consumes:
// - application/json
// - application/yaml
//
// Produces:
// - application/json
// - application/yaml
//
// Security:
// Bearer:
//
// SecurityDefinitions:
// Bearer:
// In: header
// Name: Authorization
// Type: apiKey
//
// swagger:meta
//
package docs
|
package main
import (
"github.com/gopherjs/gopherjs/js"
"github.com/waybeams/waybeams/examples/todo/ctrl"
"github.com/waybeams/waybeams/examples/todo/model"
"github.com/waybeams/waybeams/pkg/clock"
"github.com/waybeams/waybeams/pkg/env/browser"
"github.com/waybeams/waybeams/pkg/scheduler"
)
func CreateCanvas() *js.Object {
doc := js.Global.Get("document")
canvas := doc.Call("createElement", "canvas")
body := doc.Get("body")
body.Set("style", "margin:0;padding:0;")
body.Call("appendChild", canvas)
return canvas
}
func main() {
canvas := browser.NewCanvasFromJsObject(CreateCanvas())
// Create and configure the Scheduler.
scheduler.New(
browser.NewWindow(
browser.BrowserWindow(js.Global.Get("window")),
browser.Title("Todo MVC"),
),
browser.NewSurface(canvas),
ctrl.AppRenderer(model.NewSample()),
clock.New(),
).Listen()
}
|
package postgres
import (
"bytes"
"encoding/json"
"log"
"net/http"
)
//go:generate $GOPATH/bin/easytags $GOFILE json
type TenantNotification struct {
TenantId uint32 `db:"tenant_id" json:"tenantId"`
Title string `db:"title" json:"title"`
Description string `db:"description" json:"description"`
ButtonText string `db:"button_text" json:"buttonText"`
ButtonUrl string `db:"button_url" json:"buttonUrl"`
ImageUrl *string `db:"image_url" json:"imageUrl"`
Options map[string]interface{} `db:"options" json:"options"`
}
type Notifications struct {
Notifications []*TenantNotification `json:"notifications"`
Token string `json:"token"`
}
func (n *Notifications) Send(url string) {
n.Token = "nF46JdQqAM5v9KI9lPMpcu8o9xiJGvNNWOGL7TJP"
body, err := json.Marshal(n)
if err != nil {
log.Println(err)
return
}
//log.Println("------------ Sending a new notification")
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
log.Printf("error in POST notifications: %v\n", err)
return
}
//req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
//log.Println("response Status:", resp.Status)
//log.Println("response Headers:", resp.Header)
//respBody, _ := ioutil.ReadAll(resp.Body)
//log.Println("response Body:", string(respBody))
}
func (n TenantNotification) Send(url string) {
body := Notifications{
Notifications: []*TenantNotification{&n},
}
body.Send(url)
}
|
// Copyright 2017 Zhang Peihao <zhangpeihao@gmail.com>
package mock
import (
"flag"
"fmt"
"sync"
"testing"
"time"
"github.com/golang/glog"
"github.com/zhangpeihao/zim/pkg/broker"
"github.com/zhangpeihao/zim/pkg/broker/register"
"github.com/zhangpeihao/zim/pkg/protocol"
)
var (
cmdPublish, cmdSubscribe *protocol.Command
locker sync.Mutex
)
func init() {
flag.Set("v", "4")
flag.Set("logtostderr", "true")
}
func TestMockBroker(t *testing.T) {
var err error
var testTag = "mocktag"
PublishMockHandler[testTag] = func(tag string, cmd *protocol.Command) (resp *protocol.Command, err error) {
glog.Infof("PublishMockHandler(%s)%s\n", tag, cmd)
glog.Infof("PublishMockHandler() done\n")
if tag != testTag {
t.Errorf("PublishMockHandler expect tag: %s, got: %s\n", testTag, tag)
err = fmt.Errorf("publishMockHandler expect tag: %s, got: %s", testTag, tag)
return
}
if !cmdPublish.Equal(cmd) {
t.Errorf("PublishMockHandler cmdPublish: %s, got: %s\n", cmdPublish, cmd)
err = fmt.Errorf("publishMockHandler cmdPublish: %s, got: %s", cmdPublish, cmd)
}
locker.Lock()
cmdSubscribe = cmd.Copy()
locker.Unlock()
return nil, nil
}
// 初始化broker
if err = register.Init("test"); err != nil {
t.Fatal("register.Init() error:", err)
}
b := broker.Get("mock")
if b == nil {
t.Fatal(`broker.Get("mock") return nil`)
}
b.Run(nil)
if b.String() != "mock" {
t.Errorf("b.String :%s\n", b.String())
}
SubscribeMockHandler = func(tag string) (cmd *protocol.Command, err error) {
glog.Infof("SubscribeMockHandler(%s)%s\n", tag)
for {
locker.Lock()
if cmdSubscribe == nil {
locker.Unlock()
time.Sleep(time.Second)
} else {
cmd = cmdSubscribe.Copy()
locker.Unlock()
glog.Infof("SubscribeMockHandler got(%s)%s\n", tag, cmd)
return
}
}
}
cmdPublish = &protocol.Command{
Version: "t1",
AppID: "test",
Name: "msg/foo/bar",
Data: &protocol.GatewayMessageCommand{},
Payload: []byte("foo bar"),
}
finishSignal := make(chan struct{})
go func() {
err = b.Subscribe(testTag, func(tag string, cmd *protocol.Command) (err error) {
glog.Infof("Subscribe got(%s)%s\n", tag, cmd)
defer func() {
finishSignal <- struct{}{}
}()
if tag != testTag {
t.Errorf("Subscribe expect tag: %s, got: %s\n", testTag, tag)
err = fmt.Errorf("publishMockHandler expect tag: %s, got: %s", testTag, tag)
return
}
if !cmdPublish.Equal(cmd) {
t.Errorf("Subscribe cmdPublish: %s, got: %s\n", cmdPublish, cmd)
err = fmt.Errorf("publishMockHandler cmdPublish: %s, got: %s", cmdPublish, cmd)
}
return err
})
if err == nil {
t.Error("b.Subscribe should error if no handle set")
}
}()
_, err = b.Publish(testTag, cmdPublish)
if err != nil {
t.Error("b.Publish error:", err)
}
select {
case <-finishSignal:
case <-time.After(time.Second * 4):
t.Error("Test timeout")
}
b.Close(time.Second)
}
|
package application
import (
"log"
"os"
)
type (
ApplicationLogger interface {
LogWithTimeDiff(arg ...interface{})
}
AppLogger struct {
Logger *log.Logger
Service *interface{}
}
)
func NewAppLogger(service *interface{}) *AppLogger {
return &AppLogger{
Logger: log.New(os.Stderr, "[SYSTEM]", log.Ldate|log.Ltime|log.Lshortfile),
Service: service,
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.