text stringlengths 11 4.05M |
|---|
package main
const esbuildVersion = "0.9.2"
|
package dynatrace
import (
"github.com/keptn-contrib/dynatrace-service/internal/test"
"testing"
"time"
)
func TestExecuteGetDynatraceSLO(t *testing.T) {
handler := test.NewFileBasedURLHandler()
handler.AddStartsWith("/api/v2/slo", "./testdata/test_get_slo_id.json")
dtClient, _, teardown := createDynatraceClient(handler)
defer teardown()
startTime := time.Unix(1571649084, 0).UTC()
endTime := time.Unix(1571649085, 0).UTC()
sloID := "524ca177-849b-3e8c-8175-42b93fbc33c5"
sloResult, err := NewSLOClient(dtClient).Get(sloID, startTime, endTime)
if err != nil {
t.Error(err)
}
if sloResult == nil {
t.Errorf("No SLO Result returned for " + sloID)
}
if sloResult.EvaluatedPercentage != 95.66405076939219 {
t.Error("Not returning expected value for SLO")
}
}
|
// 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 hwsec
import (
"context"
"google.golang.org/grpc"
apb "chromiumos/system_api/attestation_proto"
"chromiumos/tast/errors"
"chromiumos/tast/local/hwsec"
hwsecpb "chromiumos/tast/services/cros/hwsec"
"chromiumos/tast/testing"
)
func init() {
testing.AddService(&testing.Service{
Register: func(srv *grpc.Server, s *testing.ServiceState) {
hwsecpb.RegisterAttestationDBusServiceServer(srv, &AttestationDBusService{s})
},
})
}
type AttestationDBusService struct {
s *testing.ServiceState
}
func (*AttestationDBusService) GetStatus(ctx context.Context, request *apb.GetStatusRequest) (*apb.GetStatusReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.GetStatus(ctx, request)
}
func (*AttestationDBusService) CreateEnrollRequest(ctx context.Context, request *apb.CreateEnrollRequestRequest) (*apb.CreateEnrollRequestReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.CreateEnrollRequest(ctx, request)
}
func (*AttestationDBusService) FinishEnroll(ctx context.Context, request *apb.FinishEnrollRequest) (*apb.FinishEnrollReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.FinishEnroll(ctx, request)
}
func (*AttestationDBusService) CreateCertificateRequest(ctx context.Context, request *apb.CreateCertificateRequestRequest) (*apb.CreateCertificateRequestReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.CreateCertificateRequest(ctx, request)
}
func (*AttestationDBusService) FinishCertificateRequest(ctx context.Context, request *apb.FinishCertificateRequestRequest) (*apb.FinishCertificateRequestReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.FinishCertificateRequest(ctx, request)
}
func (*AttestationDBusService) SignEnterpriseChallenge(ctx context.Context, request *apb.SignEnterpriseChallengeRequest) (*apb.SignEnterpriseChallengeReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.SignEnterpriseChallenge(ctx, request)
}
func (*AttestationDBusService) SignSimpleChallenge(ctx context.Context, request *apb.SignSimpleChallengeRequest) (*apb.SignSimpleChallengeReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.SignSimpleChallenge(ctx, request)
}
func (*AttestationDBusService) GetKeyInfo(ctx context.Context, request *apb.GetKeyInfoRequest) (*apb.GetKeyInfoReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.GetKeyInfo(ctx, request)
}
func (*AttestationDBusService) GetEnrollmentID(ctx context.Context, request *apb.GetEnrollmentIdRequest) (*apb.GetEnrollmentIdReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.GetEnrollmentID(ctx, request)
}
func (*AttestationDBusService) SetKeyPayload(ctx context.Context, request *apb.SetKeyPayloadRequest) (*apb.SetKeyPayloadReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.SetKeyPayload(ctx, request)
}
func (*AttestationDBusService) RegisterKeyWithChapsToken(ctx context.Context, request *apb.RegisterKeyWithChapsTokenRequest) (*apb.RegisterKeyWithChapsTokenReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.RegisterKeyWithChapsToken(ctx, request)
}
func (*AttestationDBusService) DeleteKeys(ctx context.Context, request *apb.DeleteKeysRequest) (*apb.DeleteKeysReply, error) {
ac, err := hwsec.NewAttestationDBus(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create attestation client")
}
return ac.DeleteKeys(ctx, request)
}
|
package dsl
import (
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
v1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func MustPVCDeleted(controller v1.PersistentVolumeClaimController, namespace, name string) {
gomega.Eventually(func() bool {
_, err := controller.Get(namespace, name, metav1.GetOptions{})
if err != nil && apierrors.IsNotFound(err) {
return true
}
ginkgo.GinkgoT().Logf("PVC %s still exists: %v", name, err)
return false
}, pvcTimeoutInterval, pvcPollingInterval).Should(gomega.BeTrue())
}
|
import "fmt"
/*
* @lc app=leetcode id=401 lang=golang
*
* [401] Binary Watch
*
* https://leetcode.com/problems/binary-watch/description/
*
* algorithms
* Easy (47.18%)
* Likes: 582
* Dislikes: 995
* Total Accepted: 84.3K
* Total Submissions: 177.3K
* Testcase Example: '0'
*
* A binary watch has 4 LEDs on the top which represent the hours (0-11), and
* the 6 LEDs on the bottom represent the minutes (0-59).
* Each LED represents a zero or one, with the least significant bit on the
* right.
*
* For example, the above binary watch reads "3:25".
*
* Given a non-negative integer n which represents the number of LEDs that are
* currently on, return all possible times the watch could represent.
*
* Example:
* Input: n = 1Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04",
* "0:08", "0:16", "0:32"]
*
*
* Note:
*
* The order of output does not matter.
* The hour must not contain a leading zero, for example "01:00" is not valid,
* it should be "1:00".
* The minute must be consist of two digits and may contain a leading zero, for
* example "10:2" is not valid, it should be "10:02".
*
*
*/
// @lc code=start
func readBinaryWatch(num int) []string {
return readBinaryWatch1(num)
}
func readBinaryWatch1(num int) []string {
retVals := []string{}
for h := 0; h < 12; h++ {
for m := 0; m < 60; m++ {
if countingBit(h)+countingBit(m) == num {
retVals = append(retVals, fmt.Sprintf("%d:%02d", h, m))
}
}
}
return retVals
}
func countingBit(num int) int {
res := 0
for i := 0; i < 6; i++ {
if num&1 == 1 {
res++
}
num >>= 1
}
return res
}
func helper(num int) int {
res := 0
for num > 0 {
res += num % 2
num /= 2
}
return res
}
// @lc code=end |
package task
func Task01(i interface{}) (interface{}, error) {
config, ok := i.(Config)
if !ok {
return nil, typeError
}
attr01 := config.Attr01()
attr02 := config.Attr02()
attr01["I am map"] = 1
attr02 += 1 // 传递的数据需用map存储, 否则修改无效
return config, nil
}
|
package patterns
// Iterator is the interface for Java-style iterators.
type Iterator interface {
HasNext() bool
Next() interface{}
}
// GetAll returns all the values that the Iterator i
// (still) has.
func GetAll(i Iterator) []interface{} {
var result []interface{}
for i.HasNext() {
result = append(result, i.Next())
}
return result
}
|
package auth
import (
"net/http"
"time"
"github.com/jsm/gode/api/application"
"github.com/jsm/gode/api/v1/requests"
"github.com/jsm/gode/models"
"github.com/jsm/gode/services"
)
func testHandler(w http.ResponseWriter, r *http.Request) {
authorizations, success := Authenticate(w, r)
if !success {
return
}
w.WriteHeader(http.StatusOK)
w.Write(application.CreateResponseJSON(true, nil, authorizations))
}
func userResponse(user models.User) map[string]interface{} {
return map[string]interface{}{
"id": user.ID,
}
}
func loginOrSignupEmailHandler(w http.ResponseWriter, r *http.Request) {
var request requests.AuthLoginOrSignupEmail
if !application.HandleJSONDecode(&request, w, r, nil) {
return
}
errContext := map[string]string{
"email": request.Email,
}
alreadyRegistered, err := services.Auth.IsEmailRegistered(request.Email)
if err != nil {
application.HandleError(err, errContext, w)
return
}
var action string
if alreadyRegistered {
action = "login"
} else {
action = "signup"
}
responseJSON := application.CreateResponseJSON(true, nil, map[string]interface{}{
"email": request.Email,
"action": action,
})
w.WriteHeader(http.StatusOK)
w.Write(responseJSON)
}
func successfulLogin(user models.User, jwt string, expiresAt time.Time, w http.ResponseWriter) {
responseJSON := application.CreateResponseJSON(true, nil, map[string]interface{}{
"user": userResponse(user),
})
cookie := &http.Cookie{
Name: "auth_token",
Value: jwt,
Expires: expiresAt,
}
http.SetCookie(w, cookie)
w.WriteHeader(http.StatusOK)
w.Write(responseJSON)
}
func signupEmailHandler(w http.ResponseWriter, r *http.Request) {
var request requests.AuthSignupEmail
if !application.HandleJSONDecode(&request, w, r, nil) {
return
}
errContext := map[string]string{
"email": request.Email,
}
user, jwt, expiresAt, err := services.Auth.RegisterEmail(request.Email, request.Password)
if err != nil {
application.HandleError(err, errContext, w)
return
}
successfulLogin(user, jwt, expiresAt, w)
}
func loginEmailHandler(w http.ResponseWriter, r *http.Request) {
var request requests.AuthLoginEmail
if !application.HandleJSONDecode(&request, w, r, nil) {
return
}
errContext := map[string]string{
"email": request.Email,
}
user, jwt, expiresAt, err := services.Auth.LoginEmail(request.Email, request.Password)
if err != nil {
application.HandleError(err, errContext, w)
return
}
successfulLogin(user, jwt, expiresAt, w)
}
func loginOrSignupSSOHandler(w http.ResponseWriter, r *http.Request) {
var request requests.AuthLoginOrSignupSSO
if !application.HandleJSONDecode(&request, w, r, nil) {
return
}
user, jwt, expiresAt, err := services.Auth.LoginOrSignupSSO(request.Token, request.Provider)
if err != nil {
application.HandleError(err, nil, w)
return
}
successfulLogin(user, jwt, expiresAt, w)
}
|
package main
import (
"fmt"
"github.com/pocke/gha"
)
func main() {
key, err := gha.CLI("test-key", &gha.Request{
Note: "test app for gha",
})
if err != nil {
panic(err)
}
fmt.Println(key)
}
|
package main
type redis_set_req struct {
Key string
Value map[string]interface {}
}
type redis_get_req struct {
Key string
}
type redis_resp struct {
Key string
Value map[string]string
}
|
package monngo
import "github.com/go-bongo/bongo"
type Mongo interface {
Connection(config bongo.Config) *bongo.Connection
}
|
// Copyright 2019 The OctoSQL Authors.
// Copyright 2020 The VectorSQL Authors.
//
// Code is licensed under Apache License, Version 2.0.
package expressions
import (
"fmt"
"base/docs"
"base/errors"
"datavalues"
)
type IValidator interface {
docs.Documented
Validate(args ...datavalues.IDataValue) error
}
type ISingleArgumentValidator interface {
docs.Documented
Validate(arg datavalues.IDataValue) error
}
type all struct {
validators []IValidator
}
func All(validators ...IValidator) *all {
return &all{validators: validators}
}
func (v *all) Validate(args ...datavalues.IDataValue) error {
for _, validator := range v.validators {
err := validator.Validate(args...)
if err != nil {
return err
}
}
return nil
}
func (v *all) Document() docs.Documentation {
childDocs := make([]docs.Documentation, len(v.validators))
for i := range v.validators {
childDocs[i] = v.validators[i].Document()
}
return docs.List(childDocs...)
}
type oneOf struct {
validators []IValidator
}
func OneOf(validators ...IValidator) *oneOf {
return &oneOf{validators: validators}
}
func (v *oneOf) Validate(args ...datavalues.IDataValue) error {
var err error
for _, validator := range v.validators {
if err = validator.Validate(args...); err == nil {
return nil
}
}
return errors.Errorf("none of the conditions have been met: %+v", err)
}
func (v *oneOf) Document() docs.Documentation {
childDocs := make([]docs.Documentation, len(v.validators))
for i := range v.validators {
childDocs[i] = v.validators[i].Document()
}
return docs.Paragraph(docs.Text("must satisfy one of"), docs.List(childDocs...))
}
type singleOneOf struct {
validators []ISingleArgumentValidator
}
func SingleOneOf(validators ...ISingleArgumentValidator) *singleOneOf {
return &singleOneOf{validators: validators}
}
func (v *singleOneOf) Validate(arg datavalues.IDataValue) error {
errs := make([]error, len(v.validators))
for i, validator := range v.validators {
errs[i] = validator.Validate(arg)
if errs[i] == nil {
return nil
}
}
return fmt.Errorf("none of the conditions have been met: %+v", errs)
}
func (v *singleOneOf) Document() docs.Documentation {
childDocs := make([]docs.Documentation, len(v.validators))
for i := range v.validators {
childDocs[i] = v.validators[i].Document()
}
return docs.Paragraph(docs.Text("must satisfy one of the following"), docs.List(childDocs...))
}
type exactlyNArgs struct {
n int
}
func ExactlyNArgs(n int) *exactlyNArgs {
return &exactlyNArgs{n: n}
}
func (v *exactlyNArgs) Validate(args ...datavalues.IDataValue) error {
if len(args) != v.n {
return errors.Errorf("expected exactly %s, but got %v", argumentCount(v.n), len(args))
}
return nil
}
func (v *exactlyNArgs) Document() docs.Documentation {
return docs.Text(fmt.Sprintf("exactly %s must be provided", argumentCount(v.n)))
}
type typeOf struct {
wantedType datavalues.IDataValue
}
func TypeOf(wantedType datavalues.IDataValue) *typeOf {
return &typeOf{wantedType: wantedType}
}
func (v *typeOf) Validate(arg datavalues.IDataValue) error {
if v.wantedType.Type() != arg.Type() {
return errors.Errorf("expected type %v but got %v", v.wantedType.Document(), arg.Document())
}
return nil
}
func (v *typeOf) Document() docs.Documentation {
return docs.Paragraph(docs.Text("must be of type"), v.wantedType.Document())
}
type ifArgPresent struct {
i int
validator IValidator
}
func IfArgPresent(i int, validator IValidator) *ifArgPresent {
return &ifArgPresent{i: i, validator: validator}
}
func (v *ifArgPresent) Validate(args ...datavalues.IDataValue) error {
if len(args) < v.i+1 {
return nil
}
return v.validator.Validate(args...)
}
func (v *ifArgPresent) Document() docs.Documentation {
return docs.Paragraph(
docs.Text(fmt.Sprintf("if the %s argument is provided, then", docs.Ordinal(v.i+1))),
v.validator.Document(),
)
}
type atLeastNArgs struct {
n int
}
func AtLeastNArgs(n int) *atLeastNArgs {
return &atLeastNArgs{n: n}
}
func (v *atLeastNArgs) Validate(args ...datavalues.IDataValue) error {
if len(args) < v.n {
return errors.Errorf("expected at least %s, but got %v", argumentCount(v.n), len(args))
}
return nil
}
func (v *atLeastNArgs) Document() docs.Documentation {
return docs.Text(fmt.Sprintf("at least %s may be provided", argumentCount(v.n)))
}
type atMostNArgs struct {
n int
}
func AtMostNArgs(n int) *atMostNArgs {
return &atMostNArgs{n: n}
}
func (v *atMostNArgs) Validate(args ...datavalues.IDataValue) error {
if len(args) > v.n {
return errors.Errorf("expected at most %s, but got %v", argumentCount(v.n), len(args))
}
return nil
}
func (v *atMostNArgs) Document() docs.Documentation {
return docs.Text(fmt.Sprintf("at most %s may be provided", argumentCount(v.n)))
}
type arg struct {
i int
validator ISingleArgumentValidator
}
func Arg(i int, validator ISingleArgumentValidator) *arg {
return &arg{i: i, validator: validator}
}
func (v *arg) Validate(args ...datavalues.IDataValue) error {
if err := v.validator.Validate(args[v.i]); err != nil {
return fmt.Errorf("bad argument at index %v: %v", v.i, err)
}
return nil
}
func (v *arg) Document() docs.Documentation {
return docs.Paragraph(
docs.Text(fmt.Sprintf("the %s argument", docs.Ordinal(v.i+1))),
v.validator.Document(),
)
}
type sameType struct {
idxs []int
}
func SameType(idx ...int) *sameType {
return &sameType{idxs: idx}
}
func (v *sameType) Validate(args ...datavalues.IDataValue) error {
var current datavalues.IDataValue
for i, idx := range v.idxs {
arg := args[idx]
if current == nil {
current = arg
}
if current.Type() != arg.Type() {
return fmt.Errorf("bad argument type at index %v, wanted:%v, got:%v", i, current.Document(), arg.Document())
}
}
return nil
}
func (v *sameType) Document() docs.Documentation {
return docs.Text(fmt.Sprintf("index %+v type must be same", v.idxs))
}
type sameFamily struct {
family datavalues.Family
}
func SameFamily(f datavalues.Family) *sameFamily {
return &sameFamily{family: f}
}
func (v *sameFamily) Validate(args ...datavalues.IDataValue) error {
for i, arg := range args {
if arg.Family() != v.family {
return fmt.Errorf("bad argument family at index %v, wanted:%v, got:%v", i, v.family, arg.Family())
}
}
return nil
}
func (v *sameFamily) Document() docs.Documentation {
return docs.Text(fmt.Sprintf("index %+v family must be same", v.family))
}
type allArgs struct {
validator ISingleArgumentValidator
}
func AllArgs(validator ISingleArgumentValidator) *allArgs {
return &allArgs{validator: validator}
}
func (v *allArgs) Validate(args ...datavalues.IDataValue) error {
for i := range args {
if err := v.validator.Validate(args[i]); err != nil {
return errors.Errorf("bad argument at index %v: %v", i, err)
}
}
return nil
}
func (v *allArgs) Document() docs.Documentation {
return docs.Paragraph(
docs.Text("all arguments"),
v.validator.Document(),
)
}
func argumentCount(n int) string {
switch n {
case 1:
return "1 argument"
default:
return fmt.Sprintf("%d arguments", n)
}
}
|
package provider
import (
"errors"
"fmt"
"github.com/evcc-io/evcc/provider/sma"
"github.com/evcc-io/evcc/util"
"gitlab.com/bboehmke/sunny"
)
// SMA provider
type SMA struct {
device *sma.Device
value sunny.ValueID
scale float64
}
func init() {
registry.Add("sma", NewSMAFromConfig)
}
// NewSMAFromConfig creates SMA provider
func NewSMAFromConfig(other map[string]interface{}) (Provider, error) {
cc := struct {
URI, Password, Interface string
Serial uint32
Value string
Scale float64
}{
Password: "0000",
Scale: 1,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
discoverer, err := sma.GetDiscoverer(cc.Interface)
if err != nil {
return nil, fmt.Errorf("failed to get discoverer failed: %w", err)
}
provider := &SMA{
scale: cc.Scale,
}
switch {
case cc.URI != "":
provider.device, err = discoverer.DeviceByIP(cc.URI, cc.Password)
if err != nil {
return nil, err
}
case cc.Serial > 0:
provider.device = discoverer.DeviceBySerial(cc.Serial, cc.Password)
if provider.device == nil {
return nil, fmt.Errorf("device not found: %d", cc.Serial)
}
default:
return nil, errors.New("missing uri or serial")
}
provider.value, err = sunny.ValueIDString(cc.Value)
if err != nil {
return nil, err
}
return provider, err
}
// FloatGetter creates handler for float64
func (p *SMA) FloatGetter() func() (float64, error) {
return func() (float64, error) {
values, err := p.device.Values()
if err != nil {
return 0, err
}
return sma.AsFloat(values[p.value]) * p.scale, nil
}
}
// IntGetter creates handler for int64
func (p *SMA) IntGetter() func() (int64, error) {
fl := p.FloatGetter()
return func() (int64, error) {
f, err := fl()
if err != nil {
return 0, err
}
return int64(f), nil
}
}
|
package user
import (
// "img_tag/middleware"
"github.com/gin-gonic/gin"
)
func InitRouter(r *gin.Engine) {
userRouter := r.Group("user").Use()
{
userRouter.GET("/error", GetUserError)
userRouter.GET("/id", GetUser)
}
}
|
/*
Copyright 2021 The Tekton 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 cloudevent
import (
"fmt"
cdeevents "github.com/cdfoundation/sig-events/cde/sdk/go/pkg/cdf/events"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"knative.dev/pkg/apis"
)
var artifactMappings = map[string]resultMapping{
"artifactId": {
defaultResultName: "cd.artifact.id",
annotationResultNameKey: "cd.events/results.artifact.id",
},
"artifactName": {
defaultResultName: "cd.artifact.name",
annotationResultNameKey: "cd.events/results.artifact.name",
},
"artifactVersion": {
defaultResultName: "cd.artifact.version",
annotationResultNameKey: "cd.events/results.artifact.version",
},
}
const ArtifactPackagedEventAnnotation cdEventAnnotationType = "cd.artifact.packaged"
const ArtifactPublishedEventAnnotation cdEventAnnotationType = "cd.artifact.published"
// getArtifactEventType returns an eventType is conditions are met
func getArtifactEventType(runObject objectWithCondition, cdEventType cdeevents.CDEventType) (*EventType, error) {
c := runObject.GetStatusCondition().GetCondition(apis.ConditionSucceeded)
if c == nil {
return nil, fmt.Errorf("no condition for ConditionSucceeded in %T", runObject)
}
if !c.IsTrue() {
return nil, fmt.Errorf("no artifact event for condition %T", c)
}
eventType := &EventType{
Type: cdEventType,
}
switch runObject.(type) {
case *v1beta1.TaskRun, *v1beta1.PipelineRun:
return eventType, nil
}
return nil, fmt.Errorf("unknown type of Tekton resource")
}
// getArtifactPackagedEventType returns a CDF Artifact Packaged EventType if objectWithCondition meets conditions
func getArtifactPackagedEventType(runObject objectWithCondition) (*EventType, error) {
annotations := runObject.GetObjectMeta().GetAnnotations()
if _, ok := annotations[ArtifactPackagedEventAnnotation.String()]; ok {
return getArtifactEventType(runObject, cdeevents.ArtifactPackagedEventV1)
}
return nil, fmt.Errorf("no %s annotation found", ArtifactPackagedEventAnnotation.String())
}
// getArtifactPublishedEventType returns a CDF Artifact Published EventType if objectWithCondition meets conditions
func getArtifactPublishedEventType(runObject objectWithCondition) (*EventType, error) {
annotations := runObject.GetObjectMeta().GetAnnotations()
if _, ok := annotations[ArtifactPublishedEventAnnotation.String()]; ok {
return getArtifactEventType(runObject, cdeevents.ArtifactPublishedEventV1)
}
return nil, fmt.Errorf("no %s annotation found", ArtifactPublishedEventAnnotation.String())
}
// getArtifactEventData
func getArtifactEventData(runObject objectWithCondition) (CDECloudEventData, error) {
cdeCloudEventData, err := getEventData(runObject)
if err != nil {
return nil, err
}
for mappingName, mapping := range artifactMappings {
mappingValue, err := resultForMapping(runObject, mapping)
if err != nil {
return nil, err
}
cdeCloudEventData[mappingName] = mappingValue
}
return cdeCloudEventData, nil
}
// getArtifactPackagedEventData returns the data for a CDF Artifact Packaged Event
func getArtifactPackagedEventData(runObject objectWithCondition) (CDECloudEventData, error) {
return getArtifactEventData(runObject)
}
// getArtifactPublishedEventData returns the data for a CDF Artifact Packaged Event
func getArtifactPublishedEventData(runObject objectWithCondition) (CDECloudEventData, error) {
return getArtifactEventData(runObject)
}
func artifactPackagedEventForObjectWithCondition(runObject objectWithCondition) (*cloudevents.Event, error) {
etype, err := getArtifactPackagedEventType(runObject)
if err != nil {
return nil, err
}
data, err := getArtifactPackagedEventData(runObject)
if err != nil {
return nil, err
}
params := cdeevents.ArtifactEventParams{
ArtifactName: data["artifactName"],
ArtifactVersion: data["artifactVersion"],
ArtifactId: data["artifactId"],
ArtifactData: data,
}
event, err := cdeevents.CreateArtifactEvent(etype.Type, params)
if err != nil {
return nil, err
}
event.SetSubject(runObject.GetObjectMeta().GetName())
event.SetSource(getSource(runObject))
return &event, nil
}
func artifactPublishedEventForObjectWithCondition(runObject objectWithCondition) (*cloudevents.Event, error) {
etype, err := getArtifactPublishedEventType(runObject)
if err != nil {
return nil, err
}
data, err := getArtifactPublishedEventData(runObject)
if err != nil {
return nil, err
}
params := cdeevents.ArtifactEventParams{
ArtifactName: data["artifactName"],
ArtifactVersion: data["artifactVersion"],
ArtifactId: data["artifactId"],
ArtifactData: data,
}
event, err := cdeevents.CreateArtifactEvent(etype.Type, params)
if err != nil {
return nil, err
}
event.SetSubject(runObject.GetObjectMeta().GetName())
event.SetSource(getSource(runObject))
return &event, nil
}
|
package main
import fmt "fmt"
// integer array for representating graph
type graph [][]int
// data structure queue with basic properties
type queue []int
func (q* queue) push(e int) {
*q=(*q)[0:len(*q)+1]
(*q)[len(*q)-1]=e
}
func (q* queue) pop() int {
ret:=(*q)[0]
*q=(*q)[1:]
return ret
}
func create(s []int) *queue {
tempslice:=queue(s[0:0])
return &tempslice
}
func (q* queue) empty() bool {
if(len(*q)==0) { return true }
return false
}
// returns the length of shortest path from source to destination in graph g
func bfs(g graph, source int, dest int) int {
q:=create(make([]int,1000))
q.push(source)
visited:=make([]bool,len(g))
dist:=make([]int,len(g))
dist[source]=0
for !q.empty() {
e := q.pop()
visited[e]=true
if(e==dest) {
return dist[e]
}
for i:=0;i<len(g);i++ {
if(g[e][i]==1 && !visited[i]) {
visited[i]=true
dist[i]=dist[e]+1
q.push(i)
}
}
}
return -1
}
func main() {
// integer array for representating graph
g := [][]int{
[]int{0,1,0,0,0,0,0,0},
[]int{0,0,1,0,1,1,0,0},
[]int{0,0,0,1,0,0,1,0},
[]int{0,0,1,0,0,0,0,1},
[]int{1,0,0,0,0,1,0,0},
[]int{0,0,0,0,0,0,1,0},
[]int{0,0,0,0,0,1,0,0},
[]int{0,0,0,1,0,0,1,0}}
source := 0
destination := 6
fmt.Printf("Shortest route from %d to %d is %d steps\n",source,destination,bfs(g,source,destination))
}
|
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
"github.com/ledisdb/ledisdb/ledis"
"github.com/mylxsw/adanos-alert/agent/api"
"github.com/mylxsw/adanos-alert/agent/config"
"github.com/mylxsw/adanos-alert/agent/job"
"github.com/mylxsw/adanos-alert/agent/store"
"github.com/mylxsw/adanos-alert/internal/extension"
"github.com/mylxsw/adanos-alert/internal/repository"
"github.com/mylxsw/adanos-alert/pkg/misc"
"github.com/mylxsw/adanos-alert/rpc/protocol"
"github.com/mylxsw/asteria/formatter"
"github.com/mylxsw/asteria/level"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/asteria/writer"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/glacier/starter/app"
"google.golang.org/grpc"
lediscfg "github.com/ledisdb/ledisdb/config"
)
// Version GitCommit 编译参数,编译时通过编译选项 ldflags 指定
var Version = "1.0"
var GitCommit = "5dbef13fb456f51a5d29464d"
var AsyncRunner = 3
var DEBUG = ""
func main() {
if DEBUG == "true" {
infra.DEBUG = true
}
ins := app.Create(fmt.Sprintf("%s (%s)", Version, GitCommit), AsyncRunner).WithLogger(log.Module("glacier"))
ins.AddFlags(app.StringEnvFlag("server_addr", "127.0.0.1:19998", "server grpc listen address", "ADANOS_SERVER_ADDR"))
ins.AddFlags(app.StringEnvFlag("server_token", "000000", "API Token for grpc api access control", "ADANOS_SERVER_TOKEN"))
ins.AddStringFlag("data_dir", "/tmp/adanos-agent", "本地数据库存储目录")
ins.AddStringFlag("log_path", "", "日志文件输出目录(非文件名),默认为空,输出到标准输出")
ins.AddFlags(app.StringEnvFlag("listen", "127.0.0.1:29999", "agent listen address", "ADANOS_AGENT_LISTEN_ADDR"))
ins.Init(func(c infra.FlagContext) error {
stackWriter := writer.NewStackWriter()
logPath := c.String("log_path")
if logPath == "" {
log.All().LogFormatter(formatter.NewJSONFormatter())
stackWriter.PushWithLevels(writer.NewStdoutWriter())
return nil
}
log.All().LogFormatter(formatter.NewJSONWithTimeFormatter())
stackWriter.PushWithLevels(writer.NewDefaultRotatingFileWriter(context.TODO(), func(le level.Level, module string) string {
return filepath.Join(logPath, fmt.Sprintf("agent-%s.%s.log", le.GetLevelName(), time.Now().Format("20060102")))
}))
stackWriter.PushWithLevels(
NewErrorCollectorWriter(ins.Resolver()),
level.Error,
level.Emergency,
level.Critical,
)
log.All().LogWriter(stackWriter)
return nil
})
// Config
ins.Singleton(func(c infra.FlagContext) *config.Config {
return &config.Config{
DataDir: c.String("data_dir"),
ServerAddr: c.String("server_addr"),
ServerToken: c.String("server_token"),
Listen: c.String("listen"),
LogPath: c.String("log_path"),
}
})
// Ledis DB
ins.Singleton(func(conf *config.Config) (*ledis.Ledis, error) {
cfg := lediscfg.NewConfigDefault()
cfg.DataDir = conf.DataDir
cfg.Databases = 1
return ledis.Open(cfg)
})
ins.Singleton(func(ld *ledis.Ledis) (*ledis.DB, error) {
return ld.Select(0)
})
// GRPC
ins.Singleton(func(conf *config.Config) (grpc.ClientConnInterface, error) {
return grpc.Dial(conf.ServerAddr, grpc.WithInsecure(), grpc.WithPerRPCCredentials(NewAuthAPI(conf.ServerToken)))
})
ins.Async(func(conf *config.Config, db *ledis.DB) {
agentID, err := db.Get([]byte("agent-id"))
if err != nil || agentID == nil {
_ = db.Set([]byte("agent-id"), []byte(misc.UUID()))
agentID, _ = db.Get([]byte("agent-id"))
}
if log.DebugEnabled() {
log.WithFields(log.Fields{
"config": conf,
"agent_id": string(agentID),
}).Debug("configuration")
}
})
ins.Provider(api.Provider{})
ins.Provider(store.Provider{})
ins.Provider(job.Provider{})
if err := ins.Run(os.Args); err != nil {
log.Errorf("exit with error: %s", err)
}
}
// ErrorCollectorWriter Agent 错误日志采集器
type ErrorCollectorWriter struct {
resolver infra.Resolver
}
// NewErrorCollectorWriter 创建一个错误日志采集器
func NewErrorCollectorWriter(resolver infra.Resolver) *ErrorCollectorWriter {
return &ErrorCollectorWriter{resolver: resolver}
}
func (e *ErrorCollectorWriter) Write(le level.Level, module string, message string) error {
return e.resolver.Resolve(func(msgStore store.EventStore) error {
ips, _ := misc.GetLanIPs()
data, _ := json.Marshal(extension.CommonEvent{
Content: message,
Meta: repository.EventMeta{
"module": module,
"level": le.GetLevelName(),
"ip": ips,
},
Tags: []string{"agent"},
Origin: "agent",
})
req := protocol.MessageRequest{Data: string(data)}
return msgStore.Enqueue(&req)
})
}
func (e *ErrorCollectorWriter) ReOpen() error {
return nil
}
func (e *ErrorCollectorWriter) Close() error {
return nil
}
// AuthAPI 权限插件
type AuthAPI struct {
token string
}
// NewAuthAPI 创建一个Auth API
func NewAuthAPI(token string) *AuthAPI {
return &AuthAPI{token: token}
}
func (a *AuthAPI) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"token": a.token,
}, nil
}
func (a *AuthAPI) RequireTransportSecurity() bool {
return false
}
|
package jira
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/andygrunwald/go-jira"
)
// Issue 一个 Jira Issue
type Issue struct {
CustomFields map[string]interface{} `json:"custom_fields"`
ProjectKey string `json:"project_key"`
Summary string `json:"summary"`
Description string `json:"description"`
IssueType string `json:"issue_type"`
Priority string `json:"priority"`
Assignee string `json:"assignee"`
}
// Client 用于操作 jira 的客户端对象
type Client struct {
client *jira.Client
}
// NewClient create a new jira client
func NewClient(baseURL string, username, password string) (*Client, error) {
httpClient := &http.Client{}
httpClient.Transport = &http.Transport{Proxy: func(req *http.Request) (*url.URL, error) {
if username != "" && password != "" {
req.SetBasicAuth(username, password)
}
return nil, nil
}}
jiraClient, err := jira.NewClient(httpClient, baseURL)
if err != nil {
return nil, err
}
return &Client{client: jiraClient}, nil
}
// IssueResp 查询到的 Issue,附加状态
type IssueResp struct {
Issue Issue `json:"issue"`
Status string `json:"status"`
}
// GetIssue 获取一个 Issue
func (client Client) GetIssue(ctx context.Context, issueID string) (IssueResp, error) {
issue, resp, err := client.client.Issue.GetWithContext(ctx, issueID, nil)
if err != nil {
return IssueResp{}, fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
return IssueResp{
Issue: Issue{
CustomFields: issue.Fields.Unknowns,
ProjectKey: issue.Fields.Project.Key,
Summary: issue.Fields.Summary,
Description: issue.Fields.Description,
IssueType: issue.Fields.Type.ID,
Priority: issue.Fields.Priority.ID,
Assignee: issue.Fields.Assignee.Name,
},
Status: issue.Fields.Status.Name,
}, nil
}
// CreateIssue create a jira issue
func (client Client) CreateIssue(ctx context.Context, issue Issue) (string, error) {
fields := jira.IssueFields{
Project: jira.Project{Key: issue.ProjectKey},
Summary: issue.Summary,
Description: issue.Description,
Unknowns: issue.CustomFields,
}
if issue.Assignee != "" {
fields.Assignee = &jira.User{Name: issue.Assignee}
}
if issue.Priority != "" {
fields.Priority = &jira.Priority{ID: issue.Priority}
}
if issue.IssueType != "" {
fields.Type = jira.IssueType{ID: issue.IssueType}
}
createdIssue, resp, err := client.client.Issue.CreateWithContext(ctx, &jira.Issue{Fields: &fields})
if err != nil {
return "", fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
return createdIssue.ID, nil
}
// UpdateIssue 更新 Issue 的自定义字段
func (client Client) UpdateIssue(ctx context.Context, issueID string, customFields map[string]interface{}) error {
resp, err := client.client.Issue.UpdateIssueWithContext(ctx, issueID, map[string]interface{}{"fields": customFields})
if err != nil {
return fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
return nil
}
// CreateComment 创建一个评论
func (client Client) CreateComment(ctx context.Context, issueID string, comment string) error {
_, resp, err := client.client.Issue.AddCommentWithContext(ctx, issueID, &jira.Comment{Body: comment})
if err != nil {
return fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
return nil
}
// IssueType is a jira issue type object
type IssueType struct {
ID string `json:"id"`
Name string `json:"name"`
}
// GetIssueTypes return all issue types for a project
func (client Client) GetIssueTypes(ctx context.Context, projectKey string) ([]IssueType, error) {
metas, resp, err := client.client.Issue.GetCreateMetaWithContext(ctx, projectKey)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
if metas == nil || metas.GetProjectWithKey(projectKey) == nil {
return []IssueType{}, nil
}
issueTypes := make([]IssueType, 0)
for _, m := range metas.GetProjectWithKey(projectKey).IssueTypes {
issueTypes = append(issueTypes, IssueType{
ID: m.Id,
Name: m.Name,
})
}
return issueTypes, nil
}
// IssuePriority is a jira issue priority object
type IssuePriority struct {
ID string `json:"id"`
Name string `json:"name"`
}
// GetPriorities return all priorities supported by jira
func (client Client) GetPriorities(ctx context.Context) ([]IssuePriority, error) {
priorityList, resp, err := client.client.Priority.GetListWithContext(ctx)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
priorities := make([]IssuePriority, 0)
for _, pr := range priorityList {
priorities = append(priorities, IssuePriority{
ID: pr.ID,
Name: pr.Name,
})
}
return priorities, nil
}
// CustomField 自定义字段
type CustomField struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
// GetCustomFields 获取所有的自定义字段
func (client Client) GetCustomFields(ctx context.Context) ([]CustomField, error) {
fields, resp, err := client.client.Field.GetListWithContext(ctx)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, client.extractResponse(resp))
}
customFields := make([]CustomField, 0)
for _, f := range fields {
if f.Custom {
customFields = append(customFields, CustomField{
ID: f.ID,
Name: f.Name,
Type: f.Schema.Type,
})
}
}
return customFields, nil
}
// extractResponse 解析服务端返回的响应内容
func (client Client) extractResponse(resp *jira.Response) string {
defer func() {
recover()
}()
if resp == nil {
return ""
}
body, _ := ioutil.ReadAll(resp.Body)
return string(body)
}
|
package sics
type Skin struct {
Batsmen [2]string
Overs []Over
}
|
package main
import (
. "imageserver/models"
. "imageserver/service"
"github.com/emicklei/go-restful"
"net/http"
"log"
"github.com/bmizerany/pat"
"fmt"
)
func main() {
app := App{Model:&TransformFactory{Session:&SessionDb{}},Neural:&LearningNeural{},MiniNeural:&LearningNeuralMini{},Training:&Training{}}
app.Model.SetLimit(16)
app.Neural.Create(app.Model.Session,50)
app.MiniNeural.Create(app.Model.Session,16)
//app.FeedForward.Init(2,2,1)
// accept and respond in JSON unless told otherwise
restful.DefaultRequestContentType(restful.MIME_JSON)
restful.DefaultResponseContentType(restful.MIME_JSON)
// gzip if accepted
restful.DefaultContainer.EnableContentEncoding(true)
// faster router
restful.DefaultContainer.Router(restful.CurlyRouter{})
restful.Filter(app.CorsRule(restful.DefaultContainer).Filter)
restful.Filter(app.OptionFilter)
restful.Add(app.RegisterRoute())
// Для отдачи сервером статичных файлов из папки public/static
fs := http.FileServer(http.Dir("./public/static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
mux := pat.New()
mux.Get("/:page", http.HandlerFunc(app.PostHandler))
mux.Get("/:page/", http.HandlerFunc(app.PostHandler))
mux.Get("/", http.HandlerFunc(app.PostHandler))
http.Handle("/", mux)
fmt.Println("[go-restful] Сервис нейросети бота. Работает на http://localhost:4000")
log.Fatal(http.ListenAndServe(":4000", nil))
}
|
package aws
import (
"fmt"
"net/http"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
)
const (
HttpClientTimeout = 30
)
func getSession(region string) (ss *session.Session, err error) {
// TODO Use getSession for ec2 service too
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{}, // check environment
&credentials.SharedCredentialsProvider{}, // check home dir
},
)
if isRegionEmpty(region) { // user didn't set region
region = getRegionFromEnv()
if isRegionEmpty(region) {
err = fmt.Errorf("Empty region provided")
return ss, err
}
}
ss, err = session.NewSession(&aws.Config{
Credentials: creds,
Region: aws.String(region),
CredentialsChainVerboseErrors: aws.Bool(true),
HTTPClient: &http.Client{
Timeout: HttpClientTimeout * time.Second},
})
if err != nil {
return nil, fmt.Errorf("failed to create AWS session: %v", err)
}
return ss, nil
}
|
package gobucket
import (
"encoding/json"
)
func GetHookData(payload []byte) (*Hook, error) {
var h Hook
err := json.Unmarshal(payload, &h)
if err != nil {
return nil, err
}
return &h, nil
}
type Hook struct {
Repository HookRepository `json:"repository"`
Truncated bool `json:"truncated"`
Commits []Commit `json:"commits"`
ConnonUrl string `json:"canon_url"`
User string `json:"user"`
}
type Callback interface {
Exec(h *Hook)
}
type HookObserver struct {
callbacks []Callback
}
func (o *HookObserver) Add(c Callback) {
o.callbacks = append(o.callbacks, c)
}
func (o *HookObserver) Process(h *Hook) {
for _, c := range o.callbacks {
c.Exec(h)
}
}
|
package store
import (
"github.com/SamuelRamond/xauth/model"
)
// Store is an Interface you need to satisfy to implement your own backend
type Store interface {
AddPermission(p *model.Permission) error
UpdatePermissions(userID uint64, pss []*model.Permission) error
GetPermissions(userID uint64) []*model.Permission
AddUser(u *model.User) error
GetUserByID(userID uint64) *model.User
GetUserByUsername(username string) *model.User
}
|
package call
import (
"crypto/md5"
"encoding/json"
"fmt"
M "github.com/ionous/sashimi/compiler/model"
G "github.com/ionous/sashimi/game"
"github.com/ionous/sashimi/util/ident"
"io"
"reflect"
"runtime"
"strings"
)
type Marker struct {
M.CallbackModel
}
func MarkFileLine(file string, line int) Marker {
return Marker{M.CallbackModel{file, line, 0}}
}
func MakeMarker(cb G.Callback) Marker {
v := reflect.ValueOf(cb)
pc := v.Pointer()
f := runtime.FuncForPC(pc)
return MarkFileLine(f.FileLine(pc - 1))
}
func (cfg Config) MakeMarker(cb G.Callback) Marker {
m := MakeMarker(cb)
if strings.HasPrefix(m.File, cfg.BasePath+"/") {
m.File = m.File[len(cfg.BasePath)+1:]
}
return m
}
func (cfg Config) MarkFileLine(file string, line int) Marker {
m := MarkFileLine(file, line)
if strings.HasPrefix(m.File, cfg.BasePath+"/") {
m.File = m.File[len(cfg.BasePath)+1:]
}
return m
}
func (m Marker) Encode() (ret ident.Id, err error) {
if text, e := json.Marshal(m); e != nil {
err = e
} else {
hash := md5.New()
io.WriteString(hash, string(text))
b := hash.Sum(nil)
s := fmt.Sprintf("~%x", b)
if len(s) > len("~e2c569be17396eca2a2e3c11578123ed") {
panic(s)
}
ret = ident.MakeId(s)
}
return
}
|
package main
import "strings"
type matcher interface {
Match(string) bool
}
type globMatcher struct {
parts []string
caseSensitive bool
anyMatch bool
exactMatch bool
leadingGlob bool
trailingGlob bool
}
func newGlob(pattern string) *globMatcher {
m := new(globMatcher)
if pattern == "*" {
m.anyMatch = true
return m
}
m.caseSensitive = pattern != strings.ToLower(pattern)
if strings.HasPrefix(pattern, "*") {
m.leadingGlob = true
pattern = pattern[1:]
}
if strings.HasSuffix(pattern, "*") {
m.trailingGlob = true
pattern = pattern[:len(pattern)-1]
}
m.parts = strings.Split(pattern, "*")
m.exactMatch = len(m.parts) == 1 && !m.leadingGlob && !m.trailingGlob
return m
}
func (m *globMatcher) Match(s string) bool {
if m.anyMatch {
return true
}
if !m.caseSensitive {
s = strings.ToLower(s)
}
if m.exactMatch {
return s == m.parts[0]
}
parts := m.parts
if !m.leadingGlob {
if strings.HasPrefix(s, parts[0]) {
parts = parts[1:]
} else {
return false
}
}
if !m.trailingGlob {
if strings.HasSuffix(s, parts[len(parts)-1]) {
parts = parts[:len(parts)-1]
} else {
return false
}
}
for _, part := range parts {
n := strings.Index(s, part)
if n < 0 {
return false
}
s = s[n+len(part):]
}
return true
}
|
package main
import (
"fmt"
"os"
)
func main() {
mapper, err := NewJIS0213RuneMapper()
if err != nil {
fmt.Fprintf(os.Stderr, "sjis to unicode mapping construction failed: %v", err)
os.Exit(1)
}
for k, v := range *mapper {
if len(v) > 1 {
fmt.Printf("%#0X(%d): %c\n", k, k, k)
for _, vv := range v {
fmt.Printf("%v\n", vv)
}
}
}
//<---
//r := bufio.NewReader(transform.NewReader(bytes.NewReader(sjis.SJISCode{0x81, 0x80}), japanese.ShiftJIS.NewDecoder()))
//c, _, err := r.ReadRune()
//if err != nil {
// panic(err)
//}
//fmt.Printf("!!!%c\n", c)
//<---
runes := mapper.Runes()
//fmt.Printf("runes: %d\n", len(runes))
table := RangeTable(runes)
DumpRangeTable(os.Stdout, table)
}
|
package system
import (
"go-xops/dto/cacheService"
"go-xops/dto/request"
"go-xops/dto/response"
"go-xops/dto/service"
"go-xops/models/system"
"go-xops/pkg/utils"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// 获取操作日志列表
func GetOperLogs(c *gin.Context) {
// 绑定参数
var req request.OperLogListReq
reqErr := c.Bind(&req)
if reqErr != nil {
response.FailWithCode(response.ParmError)
return
}
var operationLogs []system.SysOperLog
var err error
// 创建缓存对象
cache, err := cacheService.New(time.Second * 20)
if err != nil {
logrus.Error(err)
}
key := "operationLog:" + req.Name + ":" + req.Method + ":" + req.Username + ":" + req.Ip + ":" + req.Path + ":" +
strconv.Itoa(int(req.Current)) + ":" + strconv.Itoa(int(req.PageSize)) + ":" + strconv.Itoa(int(req.Total))
cache.DBGetter = func() interface{} {
// 创建服务
s := service.New()
operationLogs, err = s.GetOperLogs(&req)
return operationLogs
}
// 获取缓存
cache.Get(key)
if err != nil {
response.FailWithMsg(err.Error())
return
}
// 转为ResponseStruct, 隐藏部分字段
var respStruct []response.OperationLogListResp
utils.Struct2StructByJson(operationLogs, &respStruct)
// 返回分页数据
var resp response.PageData
// 设置分页参数
resp.PageInfo = req.PageInfo
// 设置数据列表
resp.DataList = respStruct
response.SuccessWithData(resp)
}
// 批量删除操作日志
func BatchDeleteOperLogByIds(c *gin.Context) {
var req request.IdsReq
err := c.Bind(&req)
if err != nil {
response.FailWithCode(response.ParmError)
return
}
// 创建服务
s := service.New()
// 删除数据
err = s.DeleteOperationLogByIds(req.Ids)
if err != nil {
response.FailWithMsg(err.Error())
return
}
response.Success()
}
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"os"
"os/signal"
"time"
"github.com/golang/glog"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/rootfs/snapshot/pkg/client"
"github.com/rootfs/snapshot/pkg/cloudprovider"
"github.com/rootfs/snapshot/pkg/cloudprovider/providers/aws"
"github.com/rootfs/snapshot/pkg/cloudprovider/providers/gce"
"github.com/rootfs/snapshot/pkg/cloudprovider/providers/openstack"
snapshotcontroller "github.com/rootfs/snapshot/pkg/controller/snapshot-controller"
"github.com/rootfs/snapshot/pkg/volume"
"github.com/rootfs/snapshot/pkg/volume/aws_ebs"
"github.com/rootfs/snapshot/pkg/volume/cinder"
"github.com/rootfs/snapshot/pkg/volume/gce_pd"
"github.com/rootfs/snapshot/pkg/volume/hostpath"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
)
const (
defaultSyncDuration time.Duration = 60 * time.Second
)
var (
kubeconfig = flag.String("kubeconfig", "", "Path to a kube config. Only required if out-of-cluster.")
cloudProvider = flag.String("cloudprovider", "", "aws|gce|openstack")
cloudConfigFile = flag.String("cloudconfig", "", "Path to a Cloud config. Only required if cloudprovider is set.")
volumePlugins = make(map[string]volume.VolumePlugin)
)
func main() {
flag.Parse()
flag.Set("logtostderr", "true")
// Create the client config. Use kubeconfig if given, otherwise assume in-cluster.
config, err := buildConfig(*kubeconfig)
if err != nil {
panic(err)
}
clientset, err := kubernetes.NewForConfig(config)
aeclientset, err := apiextensionsclient.NewForConfig(config)
if err != nil {
panic(err)
}
// initialize CRD resource if it does not exist
err = client.CreateCRD(aeclientset)
if err != nil {
panic(err)
}
// make a new config for our extension's API group, using the first config as a baseline
snapshotClient, snapshotScheme, err := client.NewClient(config)
if err != nil {
panic(err)
}
// wait until CRD gets processed
err = client.WaitForSnapshotResource(snapshotClient)
if err != nil {
panic(err)
}
// build volume plugins map
buildVolumePlugins()
// start controller on instances of our CRD
glog.Infof("starting snapshot controller")
ssController := snapshotcontroller.NewSnapshotController(snapshotClient, snapshotScheme, clientset, &volumePlugins, defaultSyncDuration)
stopCh := make(chan struct{})
go ssController.Run(stopCh)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
close(stopCh)
}
func buildConfig(kubeconfig string) (*rest.Config, error) {
if kubeconfig != "" {
return clientcmd.BuildConfigFromFlags("", kubeconfig)
}
return rest.InClusterConfig()
}
func buildVolumePlugins() {
if len(*cloudProvider) != 0 {
cloud, err := cloudprovider.InitCloudProvider(*cloudProvider, *cloudConfigFile)
if err == nil && cloud != nil {
if *cloudProvider == aws.ProviderName {
awsPlugin := aws_ebs.RegisterPlugin()
awsPlugin.Init(cloud)
volumePlugins[aws_ebs.GetPluginName()] = awsPlugin
glog.Info("Register cloudprovider aws")
}
if *cloudProvider == gce.ProviderName {
gcePlugin := gce_pd.RegisterPlugin()
gcePlugin.Init(cloud)
volumePlugins[gce_pd.GetPluginName()] = gcePlugin
glog.Info("Register cloudprovider %s", gce_pd.GetPluginName())
}
if *cloudProvider == openstack.ProviderName {
cinderPlugin := cinder.RegisterPlugin()
cinderPlugin.Init(cloud)
volumePlugins[cinder.GetPluginName()] = cinderPlugin
glog.Info("Register cloudprovider %s", cinder.GetPluginName())
}
} else {
glog.Warningf("failed to initialize cloudprovider: %v, supported cloudproviders are %#v", err, cloudprovider.CloudProviders())
}
}
volumePlugins[hostpath.GetPluginName()] = hostpath.RegisterPlugin()
}
|
// Copyright 2019 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 main
import (
"context"
"github.com/stretchr/testify/require"
)
// runIndexUpgrade runs a test that creates an index before a version upgrade,
// and modifies it in a mixed version setting. It aims to test the changes made
// to index encodings done to allow secondary indexes to respect column families.
func runIndexUpgrade(ctx context.Context, t *test, c *cluster, predecessorVersion string) {
firstExpected := [][]int{
{2, 3, 4},
{6, 7, 8},
{10, 11, 12},
{14, 15, 17},
}
secondExpected := [][]int{
{2, 3, 4},
{6, 7, 8},
{10, 11, 12},
{14, 15, 17},
{21, 25, 25},
}
roachNodes := c.All()
// An empty string means that the cockroach binary specified by flag
// `cockroach` will be used.
const mainVersion = ""
u := newVersionUpgradeTest(c,
uploadAndStart(roachNodes, predecessorVersion),
waitForUpgradeStep(roachNodes),
// Fill the cluster with data.
createDataStep(),
// Upgrade one of the nodes.
binaryUpgradeStep(c.Node(1), mainVersion),
// Modify index data from that node.
modifyData(1,
`INSERT INTO t VALUES (13, 14, 15, 16)`,
`UPDATE t SET w = 17 WHERE y = 14`,
),
// Ensure all nodes see valid index data.
verifyTableData(1, firstExpected),
verifyTableData(2, firstExpected),
verifyTableData(3, firstExpected),
// Upgrade the rest of the cluster.
binaryUpgradeStep(c.Node(2), mainVersion),
binaryUpgradeStep(c.Node(3), mainVersion),
// Finalize the upgrade.
allowAutoUpgradeStep(1),
waitForUpgradeStep(roachNodes),
// Modify some more data now that the cluster is upgraded.
modifyData(1,
`INSERT INTO t VALUES (20, 21, 22, 23)`,
`UPDATE t SET w = 25, z = 25 WHERE y = 21`,
),
// Ensure all nodes see valid index data.
verifyTableData(1, secondExpected),
verifyTableData(2, secondExpected),
verifyTableData(3, secondExpected),
)
u.run(ctx, t)
}
func createDataStep() versionStep {
return func(ctx context.Context, t *test, u *versionUpgradeTest) {
conn := u.conn(ctx, t, 1)
if _, err := conn.Exec(`
CREATE TABLE t (
x INT PRIMARY KEY, y INT, z INT, w INT,
INDEX i (y) STORING (z, w),
FAMILY (x), FAMILY (y), FAMILY (z), FAMILY (w)
);
INSERT INTO t VALUES (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12);
`); err != nil {
t.Fatal(err)
}
}
}
func modifyData(node int, sql ...string) versionStep {
return func(ctx context.Context, t *test, u *versionUpgradeTest) {
// Write some data into the table.
conn := u.conn(ctx, t, node)
for _, s := range sql {
if _, err := conn.Exec(s); err != nil {
t.Fatal(err)
}
}
}
}
func verifyTableData(node int, expected [][]int) versionStep {
return func(ctx context.Context, t *test, u *versionUpgradeTest) {
conn := u.conn(ctx, t, node)
rows, err := conn.Query(`SELECT y, z, w FROM t@i ORDER BY y`)
if err != nil {
t.Fatal(err)
}
var y, z, w int
count := 0
for ; rows.Next(); count++ {
if err := rows.Scan(&y, &z, &w); err != nil {
t.Fatal(err)
}
found := []int{y, z, w}
require.Equal(t, found, expected[count])
}
}
}
func registerSecondaryIndexesMultiVersionCluster(r *testRegistry) {
r.Add(testSpec{
Name: "schemachange/secondary-index-multi-version",
Owner: OwnerSQLSchema,
Cluster: makeClusterSpec(3),
MinVersion: "v20.1.0",
Run: func(ctx context.Context, t *test, c *cluster) {
predV, err := PredecessorVersion(r.buildVersion)
if err != nil {
t.Fatal(err)
}
runIndexUpgrade(ctx, t, c, predV)
},
})
}
|
package main
import . "fmt"
func main() {
var a Formatter
}
|
package api
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"gorm.io/gorm"
semver "github.com/Masterminds/semver/v3"
"github.com/porter-dev/porter/internal/analytics"
"github.com/porter-dev/porter/internal/kubernetes/prometheus"
"github.com/porter-dev/porter/internal/models"
"github.com/porter-dev/porter/internal/templater/parser"
"helm.sh/helm/v3/pkg/release"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/go-chi/chi"
"github.com/porter-dev/porter/internal/forms"
"github.com/porter-dev/porter/internal/helm"
"github.com/porter-dev/porter/internal/helm/grapher"
"github.com/porter-dev/porter/internal/helm/loader"
"github.com/porter-dev/porter/internal/integrations/ci/actions"
"github.com/porter-dev/porter/internal/integrations/slack"
"github.com/porter-dev/porter/internal/kubernetes"
"github.com/porter-dev/porter/internal/repository"
"gopkg.in/yaml.v2"
)
// Enumeration of release API error codes, represented as int64
const (
ErrReleaseDecode ErrorCode = iota + 600
ErrReleaseValidateFields
ErrReleaseReadData
ErrReleaseDeploy
)
var (
createEnvSecretConstraint, _ = semver.NewConstraint(" < 0.1.0")
)
// HandleListReleases retrieves a list of releases for a cluster
// with various filter options
func (app *App) HandleListReleases(w http.ResponseWriter, r *http.Request) {
form := &forms.ListReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
ListFilter: &helm.ListFilter{},
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
form.PopulateListFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
releases, err := agent.ListReleases(form.Namespace, form.ListFilter)
if err != nil {
app.handleErrorRead(err, ErrReleaseReadData, w)
return
}
if err := json.NewEncoder(w).Encode(releases); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// PorterRelease is a helm release with a form attached
type PorterRelease struct {
*release.Release
Form *models.FormYAML `json:"form"`
HasMetrics bool `json:"has_metrics"`
LatestVersion string `json:"latest_version"`
GitActionConfig *models.GitActionConfigExternal `json:"git_action_config"`
ImageRepoURI string `json:"image_repo_uri"`
}
// HandleGetRelease retrieves a single release based on a name and revision
func (app *App) HandleGetRelease(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
revision, err := strconv.ParseUint(chi.URLParam(r, "revision"), 0, 64)
form := &forms.GetReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
Revision: int(revision),
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
// get the filter options
k8sForm := &forms.K8sForm{
OutOfClusterConfig: &kubernetes.OutOfClusterConfig{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
}
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
k8sForm.PopulateK8sOptionsFromQueryParams(vals, app.Repo.Cluster)
k8sForm.DefaultNamespace = form.ReleaseForm.Namespace
// validate the form
if err := app.validator.Struct(k8sForm); err != nil {
app.handleErrorFormValidation(err, ErrK8sValidate, w)
return
}
// create a new dynamic client
dynClient, err := kubernetes.GetDynamicClientOutOfClusterConfig(k8sForm.OutOfClusterConfig)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
parserDef := &parser.ClientConfigDefault{
DynamicClient: dynClient,
HelmChart: release.Chart,
HelmRelease: release,
}
res := &PorterRelease{release, nil, false, "", nil, ""}
for _, file := range release.Chart.Files {
if strings.Contains(file.Name, "form.yaml") {
formYAML, err := parser.FormYAMLFromBytes(parserDef, file.Data, "")
if err != nil {
break
}
res.Form = formYAML
break
}
}
// if form not populated, detect common charts
if res.Form == nil {
// for now just case by name
if res.Release.Chart.Name() == "velero" {
formYAML, err := parser.FormYAMLFromBytes(parserDef, []byte(veleroForm), "")
if err == nil {
res.Form = formYAML
}
}
}
// get prometheus service
_, found, err := prometheus.GetPrometheusService(agent.K8sAgent.Clientset)
if err != nil {
app.handleErrorFormValidation(err, ErrK8sValidate, w)
return
}
res.HasMetrics = found
// detect if Porter application chart and attempt to get the latest version
// from chart repo
chartRepoURL, firstFound := app.ChartLookupURLs[res.Chart.Metadata.Name]
if !firstFound {
app.updateChartRepoURLs()
chartRepoURL, _ = app.ChartLookupURLs[res.Chart.Metadata.Name]
}
if chartRepoURL != "" {
repoIndex, err := loader.LoadRepoIndexPublic(chartRepoURL)
if err == nil {
porterChart := loader.FindPorterChartInIndexList(repoIndex, res.Chart.Metadata.Name)
res.LatestVersion = res.Chart.Metadata.Version
// set latest version to the greater of porterChart.Versions and res.Chart.Metadata.Version
porterChartVersion, porterChartErr := semver.NewVersion(porterChart.Versions[0])
currChartVersion, currChartErr := semver.NewVersion(res.Chart.Metadata.Version)
if currChartErr == nil && porterChartErr == nil && porterChartVersion.GreaterThan(currChartVersion) {
res.LatestVersion = porterChart.Versions[0]
}
}
}
// if the release was created from this server,
modelRelease, err := app.Repo.Release.ReadRelease(form.Cluster.ID, release.Name, release.Namespace)
if modelRelease != nil {
res.ImageRepoURI = modelRelease.ImageRepoURI
gitAction := modelRelease.GitActionConfig
if gitAction.ID != 0 {
res.GitActionConfig = gitAction.Externalize()
}
}
if err := json.NewEncoder(w).Encode(res); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// HandleGetReleaseComponents retrieves kubernetes objects listed in a release identified by name and revision
func (app *App) HandleGetReleaseComponents(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
revision, err := strconv.ParseUint(chi.URLParam(r, "revision"), 0, 64)
form := &forms.GetReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
Revision: int(revision),
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
yamlArr := grapher.ImportMultiDocYAML([]byte(release.Manifest))
objects := grapher.ParseObjs(yamlArr, release.Namespace)
parsed := grapher.ParsedObjs{
Objects: objects,
}
parsed.GetControlRel()
parsed.GetLabelRel()
parsed.GetSpecRel()
if err := json.NewEncoder(w).Encode(parsed); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// HandleGetReleaseControllers retrieves controllers that belong to a release.
// Used to display status of charts.
func (app *App) HandleGetReleaseControllers(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
revision, err := strconv.ParseUint(chi.URLParam(r, "revision"), 0, 64)
form := &forms.GetReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
Revision: int(revision),
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
// get the filter options
k8sForm := &forms.K8sForm{
OutOfClusterConfig: &kubernetes.OutOfClusterConfig{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
}
k8sForm.PopulateK8sOptionsFromQueryParams(vals, app.Repo.Cluster)
k8sForm.DefaultNamespace = form.ReleaseForm.Namespace
// validate the form
if err := app.validator.Struct(k8sForm); err != nil {
app.handleErrorFormValidation(err, ErrK8sValidate, w)
return
}
// create a new kubernetes agent
var k8sAgent *kubernetes.Agent
if app.ServerConf.IsTesting {
k8sAgent = app.TestAgents.K8sAgent
} else {
k8sAgent, err = kubernetes.GetAgentOutOfClusterConfig(k8sForm.OutOfClusterConfig)
}
yamlArr := grapher.ImportMultiDocYAML([]byte(release.Manifest))
controllers := grapher.ParseControllers(yamlArr)
retrievedControllers := []interface{}{}
// get current status of each controller
// TODO: refactor with type assertion
for _, c := range controllers {
c.Namespace = form.ReleaseForm.Form.Namespace
switch c.Kind {
case "Deployment":
rc, err := k8sAgent.GetDeployment(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
rc.Kind = c.Kind
retrievedControllers = append(retrievedControllers, rc)
case "StatefulSet":
rc, err := k8sAgent.GetStatefulSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
rc.Kind = c.Kind
retrievedControllers = append(retrievedControllers, rc)
case "DaemonSet":
rc, err := k8sAgent.GetDaemonSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
rc.Kind = c.Kind
retrievedControllers = append(retrievedControllers, rc)
case "ReplicaSet":
rc, err := k8sAgent.GetReplicaSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
rc.Kind = c.Kind
retrievedControllers = append(retrievedControllers, rc)
case "CronJob":
rc, err := k8sAgent.GetCronJob(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
rc.Kind = c.Kind
retrievedControllers = append(retrievedControllers, rc)
}
}
if err := json.NewEncoder(w).Encode(retrievedControllers); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// HandleGetReleaseAllPods retrieves all pods that are associated with a given release.
func (app *App) HandleGetReleaseAllPods(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
revision, err := strconv.ParseUint(chi.URLParam(r, "revision"), 0, 64)
form := &forms.GetReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
Revision: int(revision),
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
// get the filter options
k8sForm := &forms.K8sForm{
OutOfClusterConfig: &kubernetes.OutOfClusterConfig{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
}
k8sForm.PopulateK8sOptionsFromQueryParams(vals, app.Repo.Cluster)
k8sForm.DefaultNamespace = form.ReleaseForm.Namespace
// validate the form
if err := app.validator.Struct(k8sForm); err != nil {
app.handleErrorFormValidation(err, ErrK8sValidate, w)
return
}
// create a new kubernetes agent
var k8sAgent *kubernetes.Agent
if app.ServerConf.IsTesting {
k8sAgent = app.TestAgents.K8sAgent
} else {
k8sAgent, err = kubernetes.GetAgentOutOfClusterConfig(k8sForm.OutOfClusterConfig)
}
yamlArr := grapher.ImportMultiDocYAML([]byte(release.Manifest))
controllers := grapher.ParseControllers(yamlArr)
pods := make([]v1.Pod, 0)
// get current status of each controller
for _, c := range controllers {
var selector *metav1.LabelSelector
switch c.Kind {
case "Deployment":
rc, err := k8sAgent.GetDeployment(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
selector = rc.Spec.Selector
case "StatefulSet":
rc, err := k8sAgent.GetStatefulSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
selector = rc.Spec.Selector
case "DaemonSet":
rc, err := k8sAgent.GetDaemonSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
selector = rc.Spec.Selector
case "ReplicaSet":
rc, err := k8sAgent.GetReplicaSet(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
selector = rc.Spec.Selector
case "CronJob":
rc, err := k8sAgent.GetCronJob(c)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
selector = rc.Spec.JobTemplate.Spec.Selector
}
selectors := make([]string, 0)
for key, val := range selector.MatchLabels {
selectors = append(selectors, key+"="+val)
}
namespace := vals.Get("namespace")
podList, err := k8sAgent.GetPodsByLabel(strings.Join(selectors, ","), namespace)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
pods = append(pods, podList.Items...)
}
if err := json.NewEncoder(w).Encode(pods); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
type GetJobStatusResult struct {
Status string `json:"status,omitempty"`
StartTime *metav1.Time `json:"start_time,omitempty"`
}
// HandleGetJobStatus gets the status for a specific job
func (app *App) HandleGetJobStatus(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
namespace := chi.URLParam(r, "namespace")
form := &forms.GetReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
Storage: "secret",
Namespace: namespace,
},
},
Name: name,
Revision: 0,
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
// get the filter options
k8sForm := &forms.K8sForm{
OutOfClusterConfig: &kubernetes.OutOfClusterConfig{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
}
k8sForm.PopulateK8sOptionsFromQueryParams(vals, app.Repo.Cluster)
k8sForm.DefaultNamespace = form.ReleaseForm.Namespace
// validate the form
if err := app.validator.Struct(k8sForm); err != nil {
app.handleErrorFormValidation(err, ErrK8sValidate, w)
return
}
// create a new kubernetes agent
var k8sAgent *kubernetes.Agent
if app.ServerConf.IsTesting {
k8sAgent = app.TestAgents.K8sAgent
} else {
k8sAgent, err = kubernetes.GetAgentOutOfClusterConfig(k8sForm.OutOfClusterConfig)
}
jobs, err := k8sAgent.ListJobsByLabel(namespace, kubernetes.Label{
Key: "helm.sh/chart",
Val: fmt.Sprintf("%s-%s", release.Chart.Name(), release.Chart.Metadata.Version),
}, kubernetes.Label{
Key: "meta.helm.sh/release-name",
Val: name,
})
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
res := &GetJobStatusResult{}
// get the most recent job
if len(jobs) > 0 {
mostRecentJob := jobs[0]
for _, job := range jobs {
createdAt := job.ObjectMeta.CreationTimestamp
if mostRecentJob.CreationTimestamp.Before(&createdAt) {
mostRecentJob = job
}
}
res.StartTime = mostRecentJob.Status.StartTime
// get the status of the most recent job
if mostRecentJob.Status.Succeeded >= 1 {
res.Status = "succeeded"
} else if mostRecentJob.Status.Active >= 1 {
res.Status = "running"
} else if mostRecentJob.Status.Failed >= 1 {
res.Status = "failed"
}
}
if err := json.NewEncoder(w).Encode(res); err != nil {
app.handleErrorFormDecoding(err, ErrK8sDecode, w)
return
}
}
// HandleListReleaseHistory retrieves a history of releases based on a release name
func (app *App) HandleListReleaseHistory(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
form := &forms.ListReleaseHistoryForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
}
agent, err := app.getAgentFromQueryParams(
w,
r,
form.ReleaseForm,
form.ReleaseForm.PopulateHelmOptionsFromQueryParams,
)
// errors are handled in app.getAgentFromQueryParams
if err != nil {
return
}
release, err := agent.GetReleaseHistory(form.Name)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
if err := json.NewEncoder(w).Encode(release); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// HandleGetReleaseToken retrieves the webhook token of a specific release.
func (app *App) HandleGetReleaseToken(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
vals, err := url.ParseQuery(r.URL.RawQuery)
namespace := vals["namespace"][0]
clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, namespace)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
releaseExt := release.Externalize()
if err := json.NewEncoder(w).Encode(releaseExt); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
// HandleCreateWebhookToken creates a new webhook token for a release
func (app *App) HandleCreateWebhookToken(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
// read the release from the target cluster
form := &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
}
form.PopulateHelmOptionsFromQueryParams(
vals,
app.Repo.Cluster,
)
agent, err := app.getAgentFromReleaseForm(
w,
r,
form,
)
if err != nil {
app.handleErrorFormDecoding(err, ErrUserDecode, w)
return
}
rel, err := agent.GetRelease(name, 0)
if err != nil {
app.handleErrorDataRead(err, w)
return
}
token, err := repository.GenerateRandomBytes(16)
if err != nil {
app.handleErrorInternal(err, w)
return
}
// create release with webhook token in db
image, ok := rel.Config["image"].(map[string]interface{})
if !ok {
app.handleErrorInternal(fmt.Errorf("Could not find field image in config"), w)
return
}
repository := image["repository"]
repoStr, ok := repository.(string)
if !ok {
app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
return
}
release := &models.Release{
ClusterID: form.Form.Cluster.ID,
ProjectID: form.Form.Cluster.ProjectID,
Namespace: form.Form.Namespace,
Name: name,
WebhookToken: token,
ImageRepoURI: repoStr,
}
release, err = app.Repo.Release.CreateRelease(release)
if err != nil {
app.handleErrorInternal(err, w)
return
}
releaseExt := release.Externalize()
if err := json.NewEncoder(w).Encode(releaseExt); err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
}
type ContainerEnvConfig struct {
Container struct {
Env struct {
Normal map[string]string `yaml:"normal"`
} `yaml:"env"`
} `yaml:"container"`
}
// HandleUpgradeRelease upgrades a release with new values.yaml
func (app *App) HandleUpgradeRelease(w http.ResponseWriter, r *http.Request) {
projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
if err != nil || projID == 0 {
app.handleErrorFormDecoding(err, ErrProjectDecode, w)
return
}
name := chi.URLParam(r, "name")
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
form := &forms.UpgradeReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
}
form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
vals,
app.Repo.Cluster,
)
if err := json.NewDecoder(r.Body).Decode(form); err != nil {
app.handleErrorFormDecoding(err, ErrUserDecode, w)
return
}
agent, err := app.getAgentFromReleaseForm(
w,
r,
form.ReleaseForm,
)
// errors are handled in app.getAgentFromBodyParams
if err != nil {
return
}
registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(projID))
if err != nil {
app.handleErrorDataRead(err, w)
return
}
conf := &helm.UpgradeReleaseConfig{
Name: form.Name,
Cluster: form.ReleaseForm.Cluster,
Repo: *app.Repo,
Registries: registries,
}
// if the chart version is set, load a chart from the repo
if form.ChartVersion != "" {
release, err := agent.GetRelease(form.Name, 0)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"chart version not found"},
}, w)
return
}
chartRepoURL, foundFirst := app.ChartLookupURLs[release.Chart.Metadata.Name]
if !foundFirst {
app.updateChartRepoURLs()
var found bool
chartRepoURL, found = app.ChartLookupURLs[release.Chart.Metadata.Name]
if !found {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"chart not found"},
}, w)
return
}
}
chart, err := loader.LoadChartPublic(
chartRepoURL,
release.Chart.Metadata.Name,
form.ChartVersion,
)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"chart not found"},
}, w)
return
}
conf.Chart = chart
}
rel, upgradeErr := agent.UpgradeRelease(conf, form.Values, app.DOConf)
slackInts, _ := app.Repo.SlackIntegration.ListSlackIntegrationsByProjectID(uint(projID))
clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
release, _ := app.Repo.Release.ReadRelease(uint(clusterID), name, form.Namespace)
var notifConf *models.NotificationConfigExternal
notifConf = nil
if release != nil && release.NotificationConfig != 0 {
conf, err := app.Repo.NotificationConfig.ReadNotificationConfig(release.NotificationConfig)
if err != nil {
app.handleErrorInternal(err, w)
return
}
notifConf = conf.Externalize()
}
notifier := slack.NewSlackNotifier(notifConf, slackInts...)
notifyOpts := &slack.NotifyOpts{
ProjectID: uint(projID),
ClusterID: form.Cluster.ID,
ClusterName: form.Cluster.Name,
Name: name,
Namespace: form.Namespace,
URL: fmt.Sprintf(
"%s/applications/%s/%s/%s",
app.ServerConf.ServerURL,
url.PathEscape(form.Cluster.Name),
form.Namespace,
name,
) + fmt.Sprintf("?project_id=%d", uint(projID)),
}
if upgradeErr != nil {
notifyOpts.Status = slack.StatusFailed
notifyOpts.Info = upgradeErr.Error()
slackErr := notifier.Notify(notifyOpts)
fmt.Println("SLACK ERROR IS", slackErr)
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseDeploy,
Errors: []string{upgradeErr.Error()},
}, w)
return
}
notifyOpts.Status = string(rel.Info.Status)
notifyOpts.Version = rel.Version
notifier.Notify(notifyOpts)
// update the github actions env if the release exists and is built from source
if cName := rel.Chart.Metadata.Name; cName == "job" || cName == "web" || cName == "worker" {
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
if release != nil {
// update image repo uri if changed
repository := rel.Config["image"].(map[string]interface{})["repository"]
repoStr, ok := repository.(string)
if !ok {
app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
return
}
if repoStr != release.ImageRepoURI {
release, err = app.Repo.Release.UpdateRelease(release)
if err != nil {
app.handleErrorInternal(err, w)
return
}
}
gitAction := release.GitActionConfig
if gitAction.ID != 0 {
// parse env into build env
cEnv := &ContainerEnvConfig{}
yaml.Unmarshal([]byte(form.Values), cEnv)
gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
if err != nil {
if err != gorm.ErrRecordNotFound {
app.handleErrorInternal(err, w)
return
}
gr = nil
}
repoSplit := strings.Split(gitAction.GitRepo, "/")
gaRunner := &actions.GithubActions{
ServerURL: app.ServerConf.ServerURL,
GithubOAuthIntegration: gr,
GithubInstallationID: gitAction.GithubInstallationID,
GithubAppID: app.GithubAppConf.AppID,
GithubAppSecretPath: app.GithubAppConf.SecretPath,
GitRepoName: repoSplit[1],
GitRepoOwner: repoSplit[0],
Repo: *app.Repo,
GithubConf: app.GithubProjectConf,
ProjectID: uint(projID),
ReleaseName: name,
GitBranch: gitAction.GitBranch,
DockerFilePath: gitAction.DockerfilePath,
FolderPath: gitAction.FolderPath,
ImageRepoURL: gitAction.ImageRepoURI,
BuildEnv: cEnv.Container.Env.Normal,
ClusterID: release.ClusterID,
Version: gitAction.Version,
}
actionVersion, err := semver.NewVersion(gaRunner.Version)
if err != nil {
app.handleErrorInternal(err, w)
}
if createEnvSecretConstraint.Check(actionVersion) {
if err := gaRunner.CreateEnvSecret(); err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"could not update github secret"},
}, w)
}
}
}
}
}
w.WriteHeader(http.StatusOK)
}
// HandleReleaseDeployWebhook upgrades a release when a chart specific webhook is called.
func (app *App) HandleReleaseDeployWebhook(w http.ResponseWriter, r *http.Request) {
token := chi.URLParam(r, "token")
// retrieve release by token
release, err := app.Repo.Release.ReadReleaseByWebhookToken(token)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found with given webhook"},
}, w)
return
}
params := map[string][]string{}
params["cluster_id"] = []string{fmt.Sprint(release.ClusterID)}
params["storage"] = []string{"secret"}
params["namespace"] = []string{release.Namespace}
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
form := &forms.UpgradeReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: release.Name,
}
form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
params,
app.Repo.Cluster,
)
agent, err := app.getAgentFromReleaseForm(
w,
r,
form.ReleaseForm,
)
// errors are handled in app.getAgentFromBodyParams
if err != nil {
return
}
rel, err := agent.GetRelease(form.Name, 0)
// repository is set to current repository by default
commit := vals["commit"][0]
repository := rel.Config["image"].(map[string]interface{})["repository"]
gitAction := release.GitActionConfig
if gitAction.ID != 0 && (repository == "porterdev/hello-porter" || repository == "public.ecr.aws/o1j4x7p4/hello-porter") {
repository = gitAction.ImageRepoURI
} else if gitAction.ID != 0 && (repository == "porterdev/hello-porter-job" || repository == "public.ecr.aws/o1j4x7p4/hello-porter-job") {
repository = gitAction.ImageRepoURI
}
image := map[string]interface{}{}
image["repository"] = repository
image["tag"] = commit
rel.Config["image"] = image
if rel.Config["auto_deploy"] == false {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseDeploy,
Errors: []string{"Deploy webhook is disabled for this deployment."},
}, w)
return
}
registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(form.ReleaseForm.Cluster.ProjectID))
if err != nil {
app.handleErrorDataRead(err, w)
return
}
conf := &helm.UpgradeReleaseConfig{
Name: form.Name,
Cluster: form.ReleaseForm.Cluster,
Repo: *app.Repo,
Registries: registries,
Values: rel.Config,
}
slackInts, _ := app.Repo.SlackIntegration.ListSlackIntegrationsByProjectID(uint(form.ReleaseForm.Cluster.ProjectID))
var notifConf *models.NotificationConfigExternal
notifConf = nil
if release != nil && release.NotificationConfig != 0 {
conf, err := app.Repo.NotificationConfig.ReadNotificationConfig(release.NotificationConfig)
if err != nil {
app.handleErrorInternal(err, w)
return
}
notifConf = conf.Externalize()
}
notifier := slack.NewSlackNotifier(notifConf, slackInts...)
notifyOpts := &slack.NotifyOpts{
ProjectID: uint(form.ReleaseForm.Cluster.ProjectID),
ClusterID: form.Cluster.ID,
ClusterName: form.Cluster.Name,
Name: rel.Name,
Namespace: rel.Namespace,
URL: fmt.Sprintf(
"%s/applications/%s/%s/%s",
app.ServerConf.ServerURL,
url.PathEscape(form.Cluster.Name),
form.Namespace,
rel.Name,
) + fmt.Sprintf("?project_id=%d", uint(form.ReleaseForm.Cluster.ProjectID)),
}
rel, err = agent.UpgradeReleaseByValues(conf, app.DOConf)
if err != nil {
notifyOpts.Status = slack.StatusFailed
notifyOpts.Info = err.Error()
notifier.Notify(notifyOpts)
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseDeploy,
Errors: []string{err.Error()},
}, w)
return
}
notifyOpts.Status = string(rel.Info.Status)
notifyOpts.Version = rel.Version
notifier.Notify(notifyOpts)
app.analyticsClient.Track(analytics.CreateSegmentRedeployViaWebhookTrack("anonymous", repository.(string)))
w.WriteHeader(http.StatusOK)
}
// HandleReleaseJobUpdateImage
func (app *App) HandleReleaseUpdateJobImages(w http.ResponseWriter, r *http.Request) {
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
form := &forms.UpdateImageForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
}
form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
vals,
app.Repo.Cluster,
)
if err := json.NewDecoder(r.Body).Decode(form); err != nil {
app.handleErrorFormDecoding(err, ErrUserDecode, w)
return
}
releases, err := app.Repo.Release.ListReleasesByImageRepoURI(form.Cluster.ID, form.ImageRepoURI)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"releases not found with given image repo uri"},
}, w)
return
}
agent, err := app.getAgentFromReleaseForm(
w,
r,
form.ReleaseForm,
)
// errors are handled in app.getAgentFromBodyParams
if err != nil {
return
}
registries, err := app.Repo.Registry.ListRegistriesByProjectID(uint(form.ReleaseForm.Cluster.ProjectID))
if err != nil {
app.handleErrorDataRead(err, w)
return
}
// asynchronously update releases with that image repo uri
var wg sync.WaitGroup
mu := &sync.Mutex{}
errors := make([]string, 0)
for i := range releases {
index := i
wg.Add(1)
go func() {
defer wg.Done()
// read release via agent
rel, err := agent.GetRelease(releases[index].Name, 0)
if err != nil {
mu.Lock()
errors = append(errors, err.Error())
mu.Unlock()
}
if rel.Chart.Name() == "job" {
image := map[string]interface{}{}
image["repository"] = releases[index].ImageRepoURI
image["tag"] = form.Tag
rel.Config["image"] = image
rel.Config["paused"] = true
conf := &helm.UpgradeReleaseConfig{
Name: releases[index].Name,
Cluster: form.ReleaseForm.Cluster,
Repo: *app.Repo,
Registries: registries,
Values: rel.Config,
}
_, err = agent.UpgradeReleaseByValues(conf, app.DOConf)
if err != nil {
mu.Lock()
errors = append(errors, err.Error())
mu.Unlock()
}
}
}()
}
wg.Wait()
w.WriteHeader(http.StatusOK)
}
// HandleRollbackRelease rolls a release back to a specified revision
func (app *App) HandleRollbackRelease(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return
}
form := &forms.RollbackReleaseForm{
ReleaseForm: &forms.ReleaseForm{
Form: &helm.Form{
Repo: app.Repo,
DigitalOceanOAuth: app.DOConf,
},
},
Name: name,
}
form.ReleaseForm.PopulateHelmOptionsFromQueryParams(
vals,
app.Repo.Cluster,
)
if err := json.NewDecoder(r.Body).Decode(form); err != nil {
app.handleErrorFormDecoding(err, ErrUserDecode, w)
return
}
agent, err := app.getAgentFromReleaseForm(
w,
r,
form.ReleaseForm,
)
// errors are handled in app.getAgentFromBodyParams
if err != nil {
return
}
err = agent.RollbackRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseDeploy,
Errors: []string{"error rolling back release " + err.Error()},
}, w)
return
}
// get the full release data for GHA updating
rel, err := agent.GetRelease(form.Name, form.Revision)
if err != nil {
app.sendExternalError(err, http.StatusNotFound, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
// update the github actions env if the release exists and is built from source
if cName := rel.Chart.Metadata.Name; cName == "job" || cName == "web" || cName == "worker" {
clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"release not found"},
}, w)
return
}
release, err := app.Repo.Release.ReadRelease(uint(clusterID), name, rel.Namespace)
if release != nil {
// update image repo uri if changed
repository := rel.Config["image"].(map[string]interface{})["repository"]
repoStr, ok := repository.(string)
if !ok {
app.handleErrorInternal(fmt.Errorf("Could not find field repository in config"), w)
return
}
if repoStr != release.ImageRepoURI {
release, err = app.Repo.Release.UpdateRelease(release)
if err != nil {
app.handleErrorInternal(err, w)
return
}
}
gitAction := release.GitActionConfig
if gitAction.ID != 0 {
// parse env into build env
cEnv := &ContainerEnvConfig{}
rawValues, err := yaml.Marshal(rel.Config)
if err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"could not get values of previous revision"},
}, w)
}
yaml.Unmarshal(rawValues, cEnv)
gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
if err != nil {
if err != gorm.ErrRecordNotFound {
app.handleErrorInternal(err, w)
return
}
gr = nil
}
repoSplit := strings.Split(gitAction.GitRepo, "/")
projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
if err != nil || projID == 0 {
app.handleErrorFormDecoding(err, ErrProjectDecode, w)
return
}
gaRunner := &actions.GithubActions{
ServerURL: app.ServerConf.ServerURL,
GithubOAuthIntegration: gr,
GithubInstallationID: gitAction.GithubInstallationID,
GithubAppID: app.GithubAppConf.AppID,
GithubAppSecretPath: app.GithubAppConf.SecretPath,
GitRepoName: repoSplit[1],
GitRepoOwner: repoSplit[0],
Repo: *app.Repo,
GithubConf: app.GithubProjectConf,
ProjectID: uint(projID),
ReleaseName: name,
GitBranch: gitAction.GitBranch,
DockerFilePath: gitAction.DockerfilePath,
FolderPath: gitAction.FolderPath,
ImageRepoURL: gitAction.ImageRepoURI,
BuildEnv: cEnv.Container.Env.Normal,
ClusterID: release.ClusterID,
Version: gitAction.Version,
}
actionVersion, err := semver.NewVersion(gaRunner.Version)
if err != nil {
app.handleErrorInternal(err, w)
}
if createEnvSecretConstraint.Check(actionVersion) {
if err := gaRunner.CreateEnvSecret(); err != nil {
app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
Code: ErrReleaseReadData,
Errors: []string{"could not update github secret"},
}, w)
}
}
}
}
}
w.WriteHeader(http.StatusOK)
}
// ------------------------ Release handler helper functions ------------------------ //
// getAgentFromQueryParams uses the query params to populate a form, and then
// passes that form to the underlying app.getAgentFromReleaseForm to create a new
// Helm agent.
func (app *App) getAgentFromQueryParams(
w http.ResponseWriter,
r *http.Request,
form *forms.ReleaseForm,
// populate uses the query params to populate a form
populate ...func(vals url.Values, repo repository.ClusterRepository) error,
) (*helm.Agent, error) {
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
return nil, err
}
for _, f := range populate {
err := f(vals, app.Repo.Cluster)
if err != nil {
app.handleErrorInternal(err, w)
return nil, err
}
}
return app.getAgentFromReleaseForm(w, r, form)
}
// getAgentFromReleaseForm uses a non-validated form to construct a new Helm agent based on
// the userID found in the session and the options required by the Helm agent.
func (app *App) getAgentFromReleaseForm(
w http.ResponseWriter,
r *http.Request,
form *forms.ReleaseForm,
) (*helm.Agent, error) {
var err error
// validate the form
if err := app.validator.Struct(form); err != nil {
app.handleErrorFormValidation(err, ErrReleaseValidateFields, w)
return nil, err
}
// create a new agent
var agent *helm.Agent
if app.ServerConf.IsTesting {
agent = app.TestAgents.HelmAgent
} else {
agent, err = helm.GetAgentOutOfClusterConfig(form.Form, app.Logger)
}
if err != nil {
app.handleErrorInternal(err, w)
}
return agent, err
}
const veleroForm string = `tags:
- hello
tabs:
- name: main
context:
type: cluster
config:
group: velero.io
version: v1
resource: backups
label: Backups
sections:
- name: section_one
contents:
- type: heading
label: 💾 Velero Backups
- type: resource-list
value: |
.items[] | {
name: .metadata.name,
label: .metadata.namespace,
status: .status.phase,
timestamp: .status.completionTimestamp,
message: [
(if .status.volumeSnapshotsAttempted then "\(.status.volumeSnapshotsAttempted) volume snapshots attempted, \(.status.volumeSnapshotsCompleted) completed." else null end),
"Finished \(.status.completionTimestamp).",
"Backup expires on \(.status.expiration)."
]|join(" "),
data: {
"Included Namespaces": (if .spec.includedNamespaces then .spec.includedNamespaces|join(",") else "* (all)" end),
"Included Resources": (if .spec.includedResources then .spec.includedResources|join(",") else "* (all)" end),
"Storage Location": .spec.storageLocation
}
}`
|
// Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
// defined in https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm
package ecdsa
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"errors"
"io"
"math/big"
"github.com/VIVelev/btcd/crypto/elliptic"
"github.com/VIVelev/btcd/crypto/hash"
)
// PublicKey represents an ECDSA public key.
type PublicKey struct {
elliptic.Curve
X, Y *big.Int
}
func (pub *PublicKey) Marshal() []byte {
return elliptic.Marshal(pub.Curve, pub.X, pub.Y)
}
func (pub *PublicKey) MarshalCompressed() []byte {
return elliptic.MarshalCompressed(pub.Curve, pub.X, pub.Y)
}
func (pub *PublicKey) Unmarshal(buf []byte) (*PublicKey, error) {
x, y, err := elliptic.Unmarshal(pub.Curve, buf)
pub.X, pub.Y = x, y
return pub, err
}
// PrivateKey represents an ECDSA private key.
type PrivateKey struct {
PublicKey
D *big.Int // this is the secret
}
func (priv *PrivateKey) deterministicRandomInt(z []byte) *big.Int {
length := len(z)
k, v := make([]byte, length), make([]byte, length)
for i := 0; i < len(z); i++ {
k[i] = 0x00
v[i] = 0x01
}
secretBytes := make([]byte, length)
copy(secretBytes[length-(priv.D.BitLen()+7)/8:], priv.D.Bytes())
sha256Hmac := func(k, v []byte) []byte {
h := hmac.New(sha256.New, k)
h.Write(v)
return h.Sum(nil)
}
k = sha256Hmac(k, bytes.Join([][]byte{v, {0x00}, secretBytes, z}, nil))
v = sha256Hmac(k, v)
k = sha256Hmac(k, bytes.Join([][]byte{v, {0x01}, secretBytes, z}, nil))
v = sha256Hmac(k, v)
candidate := new(big.Int)
for {
v = sha256Hmac(k, v)
candidate.SetBytes(v)
if candidate.Sign() == 1 && candidate.Cmp(priv.Curve.Params().N) == -1 {
return candidate
}
k = sha256Hmac(k, append(v, 0x00))
v = sha256Hmac(k, v)
}
}
// Sign computes the signature pair r and s from D and msgDigest.
func (priv *PrivateKey) Sign(sighash []byte) *Signature {
// Obtain the group order n of the curve.
n := priv.Curve.Params().N
RESTART:
k := priv.deterministicRandomInt(sighash)
k.Mod(k, n)
if k.Sign() == 0 {
goto RESTART
}
// Compute (x, y) = k*G, where G is the generator point.
x, _ := priv.Curve.ScalarBaseMult(k)
// Calculate the signature.
sig := new(Signature)
// Compute r = x mod n. If r=0, generate another random k and start over.
sig.r = new(big.Int).Mod(x, n)
if sig.r.Sign() == 0 {
goto RESTART
}
// Compute s = (msgDigest + r*D) / k mod n. If s=0, generate another random k and start over.
sig.s = new(big.Int).SetBytes(sighash)
prod := new(big.Int).Mul(sig.r, priv.D)
sig.s.Add(sig.s, prod)
kInv := new(big.Int).ModInverse(k, n)
sig.s.Mul(sig.s, kInv)
sig.s.Mod(sig.s, n)
if sig.s.Sign() == 0 {
goto RESTART
}
// It turns out that using the low-s value will get nodes to relay our transactions.
// This is for malleability reasons.
halfN := new(big.Int).Div(n, big.NewInt(2))
if sig.s.Cmp(halfN) == 1 {
sig.s.Sub(n, sig.s)
}
return sig
}
// Signature represents an ECDSA signature.
type Signature struct {
r *big.Int
s *big.Int
}
// Verify reports whether the signature pair r and s, pub and msgDigest are all consistent.
func (sig *Signature) Verify(pub *PublicKey, msgDigest []byte) bool {
n := pub.Curve.Params().N
// Verify that both r and s are between 1 and n-1.
if sig.r.Sign() != 1 || new(big.Int).Sub(n, sig.r).Sign() != 1 {
return false
}
if sig.s.Sign() != 1 || new(big.Int).Sub(n, sig.s).Sign() != 1 {
return false
}
// Compute u1 = msgDigest/s mod n and u2 = r/s mod n.
sInv := new(big.Int).ModInverse(sig.s, n)
u1 := new(big.Int).SetBytes(msgDigest)
u1.Mul(u1, sInv)
u1.Mod(u1, n)
u2 := new(big.Int).Set(sig.r)
u2.Mul(u2, sInv)
u2.Mod(u2, n)
// Compute (x, y) = u1*G + u2*pub and ensure it is not equal to the point at infinity.
u1X, u1Y := pub.Curve.ScalarBaseMult(u1)
u2X, u2Y := pub.Curve.ScalarMult(pub.X, pub.Y, u2)
x, y := pub.Curve.Add(u1X, u1Y, u2X, u2Y)
// TODO: Isn't (x, y) = (0, 0) the point at infinity only for a subset of curves?
if x.Sign() == 0 && y.Sign() == 0 {
return false
}
// If r = x mod n then the signature is valid. Otherwise, the signature is invalid.
return x.Mod(x, n).Cmp(sig.r) == 0
}
// Marshal encodes sig in DER format.
//
// DER has the following format:
// 0x30 [total-length] 0x02 [r-length] [r] 0x02 [s-length] [s]
//
// total-length: 1-byte length descriptor of everything that follows.
// r-length: 1-byte length descriptor of the r value that follows.
// r: arbitrary-length big-endian encoded r value. It cannot start with any 0x00 bytes,
// unless the first byte that follows is 0x80 or higher, in which case a single 0x00 is required.
// s-length: 1-byte length descriptor of the s value that follows.
// s: arbitrary-length big-endian encoded s value. The same rules apply as for r.
func (sig *Signature) Marshal() []byte {
encode := func(n *big.Int) []byte {
nb := n.Bytes()
nb = bytes.TrimLeft(nb, "\x00")
if nb[0] >= 0x80 {
nb = append([]byte{0}, nb...)
}
return nb
}
rb := encode(sig.r)
rbLen := byte(len(rb))
sb := encode(sig.s)
sbLen := byte(len(sb))
u := []byte{0x30, 2 + rbLen + 2 + sbLen, 0x02, rbLen}
v := []byte{0x02, sbLen}
return bytes.Join([][]byte{u, rb, v, sb}, nil)
}
// Unmarshal decodes DER format to sig.
func (sig *Signature) Unmarshal(der []byte) (*Signature, error) {
r := bytes.NewReader(der)
// read and validate 0x30 prefix
b, err := r.ReadByte()
if err != nil {
return nil, err
}
if b != 0x30 {
return nil, errors.New("der signatures should begin with 0x30 byte")
}
// read and validate total-length
totalLength, err := r.ReadByte()
if err != nil {
return nil, err
}
if totalLength != byte(len(der)-2) {
return nil, errors.New("total-length does not match")
}
// read and validate marker
b, err = r.ReadByte()
if err != nil {
return nil, err
}
if b != 0x02 {
return nil, errors.New("invalid marker")
}
// read r
rbLen, err := r.ReadByte()
if err != nil {
return nil, err
}
rb := make([]byte, rbLen)
_, err = io.ReadFull(r, rb)
if err != nil {
return nil, err
}
// read and validate marker
b, err = r.ReadByte()
if err != nil {
return nil, err
}
if b != 0x02 {
return nil, errors.New("invalid marker")
}
// read s
sbLen, err := r.ReadByte()
if err != nil {
return nil, err
}
sb := make([]byte, sbLen)
_, err = io.ReadFull(r, sb)
if err != nil {
return nil, err
}
// validate lengths
if 6+rbLen+sbLen != byte(len(der)) { // 6 is the number of misc bytes
return nil, errors.New("read length doesn't match der length")
}
sig.r = new(big.Int).SetBytes(rb)
sig.s = new(big.Int).SetBytes(sb)
return sig, nil
}
func GenerateKeyFromSecret(c elliptic.Curve, secret *big.Int) *PrivateKey {
priv := new(PrivateKey)
priv.Curve = c
priv.D = secret
priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(priv.D)
return priv
}
// GenerateKey generates a public and private key pair from the passphrase.
func GenerateKey(c elliptic.Curve, passphrase string) *PrivateKey {
buf := hash.Hash256([]byte(passphrase))
return GenerateKeyFromSecret(c, new(big.Int).SetBytes(buf[:]))
}
|
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/AlexanderEkdahl/rope/version"
)
// TODO: Add update parameter for when to use the latest version of transitive
// dependency.
func add(timeout time.Duration, packages []string) error {
ctx := context.Background()
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
project, err := ReadRopefile()
ropefilePath := ""
if errors.Is(err, ErrRopefileNotFound) {
project = &Project{Dependencies: []Dependency{}}
ropefilePath = "rope.json"
} else if err != nil {
return err
}
// index := &Index{url: DefaultIndex}
index := &PyPI{}
for _, p := range packages {
d, err := version.ParseDependency(p)
if err != nil {
return err
}
if len(d.Versions) > 1 {
return fmt.Errorf("expected at most a single version, got: %d", len(d.Versions))
}
if len(d.Extras) > 0 {
// TODO: Support extras
return fmt.Errorf("extras not supported")
}
var version version.Version
if len(d.Versions) > 0 {
version = d.Versions[0].Version
}
p, err := index.FindPackage(ctx, d.Name, version)
if err != nil {
return fmt.Errorf("finding '%s-%s': %w", d.Name, version, err)
}
project.Dependencies = append(project.Dependencies, Dependency{
Name: p.Name(),
Version: p.Version(),
})
}
list, minimalRequirements, err := MinimalVersionSelection(ctx, project.Dependencies, index)
if err != nil {
return fmt.Errorf("failed version selection: %w", err)
}
for _, d := range list {
p, err := index.FindPackage(ctx, d.Name, d.Version)
if err != nil {
return fmt.Errorf("failed to find package after version selection: %w", err)
}
// TODO: This function need to find the package AGAIN? doesn't make sense
if _, err := p.Install(ctx); err != nil {
return fmt.Errorf("installing '%s-%s': %w", d.Name, d.Version, err)
}
}
project.Dependencies = minimalRequirements
return WriteRopefile(project, ropefilePath)
}
|
// Copyright © 2019 Maks Balashov <maksbalashov@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"github.com/identixone/identixone-go/api/client"
"github.com/identixone/identixone-go/api/common"
"github.com/identixone/identixone-go/api/const/conf"
"github.com/identixone/identixone-go/api/source"
"github.com/identixone/identixone-go/utils"
"github.com/spf13/cobra"
)
const (
sourcesList = "list"
sourcesDelete = "delete"
sourcersGet = "get"
sourcesUpdate = "update"
sourcesCreate = "create"
)
var (
q string
sourceId int
identifyFacesizeThreshold int
manualCreateFacesizeThreshold int
autoCreateFacesizeThreshold int
autoCheckAngleThreshold int
storeImagesForConfs []conf.Conf
storeImagesForConfsStrings []string
ppsTimestamp bool
autoCreatePerson bool
autoCreateOnHa bool
autoCreateOnJunk bool
autoCheckFaceAngle bool
autoCheckAsm bool
autoCreateCheckBlur bool
autoCreateCheckExp bool
autoCheckLiveness bool
autoCreateLivenessOnly bool
manualCreateOnHa bool
manualCreateOnJunk bool
manualCheckAsm bool
manualCreateLivenessOnly bool
manualCheckLiveness bool
)
//func get
// serveCmd represents the serve command
var sourcesCmd = &cobra.Command{
Use: "sources",
Short: "sources API",
Long: "",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("only one argument supported at time")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
//fmt.Println(args)
if len(storeImagesForConfsStrings) > 0 {
for i := range storeImagesForConfsStrings {
storeImagesForConfs = append(storeImagesForConfs, conf.Conf(storeImagesForConfsStrings[i]))
}
}
switch args[0] {
case sourcesList:
query := common.NewSearchPaginationQuery(q, limit, offset)
c, err := client.NewClient()
ifErrorExit(err)
sources, err := c.Sources().List(query)
ifErrorExit(err)
if outputPath != "" {
preOut, err := utils.GetPretty(sources)
ifErrorExit(err)
err = utils.WriteToFile(outputPath, preOut)
ifErrorExit(err)
} else {
ifErrorExit(utils.PrettyPrint(sources))
}
case sourcesDelete:
if sourceId == 0 {
printAndExit("source id is required")
}
c, err := client.NewClient()
ifErrorExit(err)
ifErrorExit(c.Sources().Delete(sourceId))
fmt.Printf("source %d successfuly deleted", sourceId)
fmt.Println()
case sourcersGet:
if sourceId == 0 {
printAndExit("source id is required")
}
c, err := client.NewClient()
ifErrorExit(err)
source, err := c.Sources().Get(sourceId)
ifErrorExit(err)
ifErrorExit(utils.PrettyPrint(source))
case sourcesUpdate:
if sourceId == 0 {
printAndExit("source id is required")
}
c, err := client.NewClient()
ifErrorExit(err)
req := source.UpdateRequest{ID: sourceId}
req.
SetPpsTimestamp(ppsTimestamp).
SetStoreImagesForConfs(storeImagesForConfs).
SetName(sourceName).
SetIdentifyFacesizeThreshold(identifyFacesizeThreshold).
SetAutoCreatePersons(autoCreatePerson).
SetAutoCreateFacesizeThreshold(autoCreateFacesizeThreshold).
SetAutoCreateOnHa(autoCreateOnHa).
SetAutoCreateOnJunk(autoCreateOnJunk).
SetAutoCheckFaceAngle(autoCheckFaceAngle).
SetAutoCheckAngleThreshold(autoCheckAngleThreshold).
SetAutoCheckAsm(autoCheckAsm).
SetAutoCreateCheckBlur(autoCreateCheckBlur).
SetAutoCreateCheckExp(autoCreateCheckExp).
SetAutoCheckLiveness(autoCheckLiveness).
SetAutoCreateLivenessOnly(autoCreateLivenessOnly).
SetManualCreateFacesizeThreshold(manualCreateFacesizeThreshold).
SetManualCreateOnHa(manualCreateOnHa).
SetManualCreateOnJunk(manualCreateOnJunk).
SetManualCheckAsm(manualCheckAsm).
SetManualCreateLivenessOnly(manualCreateLivenessOnly).
SetManualCheckLiveness(manualCheckLiveness)
resp, err := c.Sources().Update(req)
ifErrorExit(err)
ifErrorExit(utils.PrettyPrint(resp))
case sourcesCreate:
if sourceName == "" {
printAndExit("source name is required")
}
c, err := client.NewClient()
ifErrorExit(err)
req := source.DefaultSourceWithName(sourceName)
req.
SetPpsTimestamp(ppsTimestamp).
SetStoreImagesForConfs(storeImagesForConfs).
SetName(sourceName).
SetIdentifyFacesizeThreshold(identifyFacesizeThreshold).
SetAutoCreatePersons(autoCreatePerson).
SetAutoCreateFacesizeThreshold(autoCreateFacesizeThreshold).
SetAutoCreateOnHa(autoCreateOnHa).
SetAutoCreateOnJunk(autoCreateOnJunk).
SetAutoCheckFaceAngle(autoCheckFaceAngle).
SetAutoCheckAngleThreshold(autoCheckAngleThreshold).
SetAutoCheckAsm(autoCheckAsm).
SetAutoCreateCheckBlur(autoCreateCheckBlur).
SetAutoCreateCheckExp(autoCreateCheckExp).
SetAutoCheckLiveness(autoCheckLiveness).
SetAutoCreateLivenessOnly(autoCreateLivenessOnly).
SetManualCreateFacesizeThreshold(manualCreateFacesizeThreshold).
SetManualCreateOnHa(manualCreateOnHa).
SetManualCreateOnJunk(manualCreateOnJunk).
SetManualCheckAsm(manualCheckAsm).
SetManualCreateLivenessOnly(manualCreateLivenessOnly).
SetManualCheckLiveness(manualCheckLiveness)
resp, err := c.Sources().Create(req)
ifErrorExit(err)
ifErrorExit(utils.PrettyPrint(resp))
}
},
}
func init() {
sourcesCmd.Flags().StringVarP(&q, "search", "s", "", "filtering of a source sourcesList by partly or fully specified name")
sourcesCmd.Flags().IntVar(&sourceId, "id", 0, "source id")
sourcesCmd.Flags().BoolVar(&ppsTimestamp, "ppsTimestamp", false, "ppsTimestamp")
sourcesCmd.Flags().BoolVar(&autoCreatePerson, "autoCreatePerson", false, "autoCreatePerson")
sourcesCmd.Flags().BoolVar(&autoCreateOnHa, "autoCreateOnHa", false, "autoCreateOnHa")
sourcesCmd.Flags().BoolVar(&autoCreateOnJunk, "autoCreateOnJunk", false, "autoCreateOnJunk")
sourcesCmd.Flags().BoolVar(&autoCheckFaceAngle, "autoCheckFaceAngle", false, "autoCheckFaceAngel")
sourcesCmd.Flags().BoolVar(&autoCheckAsm, "autoCheckAsm", false, "autoCheckAsm")
sourcesCmd.Flags().BoolVar(&autoCreateCheckBlur, "autoCreateCheckBlur", false, "autoCreateCheckBlur")
sourcesCmd.Flags().BoolVar(&autoCreateCheckExp, "autoCreateCheckExp", false, "autoCreateCheckExp")
sourcesCmd.Flags().BoolVar(&autoCheckLiveness, "autoCheckLiveness", false, "autoCheckLiveness")
sourcesCmd.Flags().BoolVar(&autoCreateLivenessOnly, "autoCreateLivenessOnly", false, "autoCreateLivenessOnly")
sourcesCmd.Flags().BoolVar(&manualCreateOnHa, "manualCreateOnHa", false, "manualCreateOnHa")
sourcesCmd.Flags().BoolVar(&manualCreateOnJunk, "manualCreateOnJunk", false, "manualCreateOnJunk")
sourcesCmd.Flags().BoolVar(&manualCheckAsm, "manualCheckAsm", false, "manualCheckAsm")
sourcesCmd.Flags().BoolVar(&manualCreateLivenessOnly, "manualCreateLivenessOnly", false, "manualCreateLivenessOnly")
sourcesCmd.Flags().BoolVar(&manualCheckLiveness, "manualCheckLiveness", false, "manualCheckLiveness")
sourcesCmd.Flags().IntVar(&manualCreateFacesizeThreshold, "manualCreateFacesizeThreshold", 0, "manualCreateFacesizeThreshold")
sourcesCmd.Flags().IntVar(&identifyFacesizeThreshold, "identifyFacesizeThreshold", 0, "identifyFacesizeThreshold")
sourcesCmd.Flags().IntVar(&autoCreateFacesizeThreshold, "autoCreateFacesizeThreshold", 0, "autoCreateFacesizeThreshold")
sourcesCmd.Flags().IntVar(&autoCheckAngleThreshold, "autoCheckAngleThreshold", 0, "autoCheckAngleThreshold")
sourcesCmd.Flags().StringArrayVar(&storeImagesForConfsStrings, "storeImagesForConfs", []string{}, "storeImagesForConfs")
rootCmd.AddCommand(sourcesCmd)
}
|
package middlewares
import (
"project/config"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
// Leverage default authentication middleware from echo
func AuthenticationMiddleware() echo.MiddlewareFunc {
return middleware.JWTWithConfig(middleware.JWTConfig{
SigningMethod: "HS256",
SigningKey: []byte(config.Config.JWTSecret),
})
}
|
// Copyright 2019 Yunion
//
// 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 aws
import (
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/service/elasticache"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
billingapi "yunion.io/x/onecloud/pkg/apis/billing"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
"yunion.io/x/onecloud/pkg/util/billing"
)
func (region *SRegion) DescribeElasticacheReplicationGroups(Id string) ([]*elasticache.ReplicationGroup, error) {
ecClient, err := region.getAwsElasticacheClient()
if err != nil {
return nil, errors.Wrap(err, "client.getAwsElasticacheClient")
}
input := elasticache.DescribeReplicationGroupsInput{}
replicaGroup := []*elasticache.ReplicationGroup{}
marker := ""
maxrecords := (int64)(100)
input.MaxRecords = &maxrecords
if len(Id) > 0 {
input.ReplicationGroupId = &Id
}
for {
if len(marker) >= 0 {
input.Marker = &marker
}
out, err := ecClient.DescribeReplicationGroups(&input)
if err != nil {
return nil, errors.Wrap(err, "ecClient.DescribeReplicationGroups")
}
replicaGroup = append(replicaGroup, out.ReplicationGroups...)
if out.Marker != nil && len(*out.Marker) > 0 {
marker = *out.Marker
} else {
break
}
}
return replicaGroup, nil
}
func (region *SRegion) GetElasticaches() ([]SElasticache, error) {
replicaGroups, err := region.DescribeElasticacheReplicationGroups("")
if err != nil {
return nil, errors.Wrap(err, " region.DescribeElasticacheReplicationGroups")
}
result := []SElasticache{}
for i := range replicaGroups {
result = append(result, SElasticache{region: region, replicaGroup: replicaGroups[i]})
}
return result, nil
}
func (region *SRegion) GetIElasticcaches() ([]cloudprovider.ICloudElasticcache, error) {
sElasticahes, err := region.GetElasticaches()
if err != nil {
return nil, errors.Wrap(err, "region.GetSElasticaches()")
}
result := []cloudprovider.ICloudElasticcache{}
for i := range sElasticahes {
result = append(result, &sElasticahes[i])
}
return result, nil
}
func (region *SRegion) GetSElasticacheById(Id string) (*SElasticache, error) {
replicaGroups, err := region.DescribeElasticacheReplicationGroups(Id)
if err != nil {
return nil, errors.Wrap(err, " region.DescribeElasticacheReplicationGroups")
}
if len(replicaGroups) == 0 {
return nil, cloudprovider.ErrNotFound
}
if len(replicaGroups) > 1 {
return nil, cloudprovider.ErrDuplicateId
}
return &SElasticache{region: region, replicaGroup: replicaGroups[0]}, nil
}
func (region *SRegion) GetIElasticcacheById(id string) (cloudprovider.ICloudElasticcache, error) {
sElasticache, err := region.GetSElasticacheById(id)
if err != nil {
return nil, errors.Wrapf(err, "region.GetSElasticacheById(%s)", id)
}
return sElasticache, nil
}
func (region *SRegion) DescribeElasticacheClusters() ([]*elasticache.CacheCluster, error) {
ecClient, err := region.getAwsElasticacheClient()
if err != nil {
return nil, errors.Wrap(err, "client.getAwsElasticacheClient")
}
input := elasticache.DescribeCacheClustersInput{}
clusters := []*elasticache.CacheCluster{}
marker := ""
maxrecords := (int64)(100)
input.MaxRecords = &maxrecords
for {
if len(marker) >= 0 {
input.Marker = &marker
}
out, err := ecClient.DescribeCacheClusters(&input)
if err != nil {
return nil, errors.Wrap(err, "ecClient.DescribeCacheClusters")
}
clusters = append(clusters, out.CacheClusters...)
if out.Marker != nil && len(*out.Marker) > 0 {
marker = *out.Marker
} else {
break
}
}
return clusters, nil
}
func (region *SRegion) DescribeCacheSubnetGroups(Id string) ([]*elasticache.CacheSubnetGroup, error) {
ecClient, err := region.getAwsElasticacheClient()
if err != nil {
return nil, errors.Wrap(err, "client.getAwsElasticacheClient")
}
input := elasticache.DescribeCacheSubnetGroupsInput{}
subnetGroups := []*elasticache.CacheSubnetGroup{}
marker := ""
maxrecords := (int64)(100)
input.MaxRecords = &maxrecords
if len(Id) > 0 {
input.CacheSubnetGroupName = &Id
}
for {
if len(marker) >= 0 {
input.Marker = &marker
}
out, err := ecClient.DescribeCacheSubnetGroups(&input)
if err != nil {
return nil, errors.Wrap(err, "ecClient.DescribeCacheSubnetGroups")
}
subnetGroups = append(subnetGroups, out.CacheSubnetGroups...)
if out.Marker != nil && len(*out.Marker) > 0 {
marker = *out.Marker
} else {
break
}
}
return subnetGroups, nil
}
type SElasticache struct {
multicloud.SElasticcacheBase
multicloud.AwsTags
region *SRegion
replicaGroup *elasticache.ReplicationGroup
cacheClusters []*elasticache.CacheCluster
subnetGroup *elasticache.CacheSubnetGroup
}
func (self *SElasticache) GetId() string {
return *self.replicaGroup.ReplicationGroupId
}
func (self *SElasticache) GetName() string {
return *self.replicaGroup.ReplicationGroupId
}
func (self *SElasticache) GetGlobalId() string {
return self.GetId()
}
func (self *SElasticache) GetStatus() string {
if self.replicaGroup.Status == nil {
return api.ELASTIC_CACHE_STATUS_UNKNOWN
}
// creating, available, modifying, deleting, create-failed, snapshotting
switch *self.replicaGroup.Status {
case "creating":
return api.ELASTIC_CACHE_STATUS_DEPLOYING
case "available":
return api.ELASTIC_CACHE_STATUS_RUNNING
case "modifying":
return api.ELASTIC_CACHE_STATUS_CHANGING
case "deleting":
return api.ELASTIC_CACHE_STATUS_DELETING
case "create-failed":
return api.ELASTIC_CACHE_STATUS_CREATE_FAILED
case "snapshotting":
return api.ELASTIC_CACHE_STATUS_SNAPSHOTTING
default:
return api.ELASTIC_CACHE_STATUS_UNKNOWN
}
}
func (self *SElasticache) Refresh() error {
if self.replicaGroup.ReplicationGroupId == nil {
return errors.Wrap(cloudprovider.ErrNotFound, "replicationGroupId not found")
}
replica, err := self.region.DescribeElasticacheReplicationGroups(*self.replicaGroup.ReplicationGroupId)
if err != nil {
return errors.Wrapf(err, "self.region.DescribeElasticacheReplicationGroups(%s)", *self.replicaGroup.ReplicationGroupId)
}
if len(replica) == 0 {
return cloudprovider.ErrNotFound
}
if len(replica) > 1 {
return cloudprovider.ErrDuplicateId
}
self.replicaGroup = replica[0]
self.cacheClusters = nil
self.subnetGroup = nil
return nil
}
func (self *SElasticache) GetBillingType() string {
return billingapi.BILLING_TYPE_POSTPAID
}
func (self *SElasticache) GetCreatedAt() time.Time {
return time.Time{}
}
func (self *SElasticache) GetExpiredAt() time.Time {
return time.Time{}
}
func (self *SElasticache) fetchClusters() error {
if self.cacheClusters != nil {
return nil
}
clusters, err := self.region.DescribeElasticacheClusters()
if err != nil {
return errors.Wrap(err, "self.region.DescribeElasticacheClusters")
}
self.cacheClusters = []*elasticache.CacheCluster{}
for i := range clusters {
if clusters[i].ReplicationGroupId != nil && *clusters[i].ReplicationGroupId == self.GetId() {
self.cacheClusters = append(self.cacheClusters, clusters[i])
}
}
return nil
}
func (self *SElasticache) GetInstanceType() string {
if self.replicaGroup.CacheNodeType != nil {
return *self.replicaGroup.CacheNodeType
}
return ""
}
func (self *SElasticache) GetCapacityMB() int {
return 0
}
func (self *SElasticache) GetArchType() string {
if self.replicaGroup.ClusterEnabled != nil && *self.replicaGroup.ClusterEnabled == true {
return api.ELASTIC_CACHE_ARCH_TYPE_CLUSTER
}
self.fetchClusters()
if len(self.cacheClusters) > 1 {
return api.ELASTIC_CACHE_ARCH_TYPE_RWSPLIT
}
return api.ELASTIC_CACHE_ARCH_TYPE_SINGLE
}
func (self *SElasticache) GetNodeType() string {
nodeGroupNums := 1
for _, nodeGroup := range self.replicaGroup.NodeGroups {
if nodeGroup != nil {
nodeGroupNums = len(nodeGroup.NodeGroupMembers)
break
}
}
switch nodeGroupNums {
case 1:
return api.ELASTIC_CACHE_NODE_TYPE_SINGLE
case 2:
return api.ELASTIC_CACHE_NODE_TYPE_DOUBLE
case 3:
return api.ELASTIC_CACHE_NODE_TYPE_THREE
case 4:
return api.ELASTIC_CACHE_NODE_TYPE_FOUR
case 5:
return api.ELASTIC_CACHE_NODE_TYPE_FIVE
case 6:
return api.ELASTIC_CACHE_NODE_TYPE_SIX
}
return strconv.Itoa(nodeGroupNums)
}
func (self *SElasticache) GetEngine() string {
self.fetchClusters()
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.Engine != nil {
return *cluster.Engine
}
}
return ""
}
func (self *SElasticache) GetEngineVersion() string {
self.fetchClusters()
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.EngineVersion != nil {
return *cluster.EngineVersion
}
}
return ""
}
func (self *SElasticache) fetchSubnetGroup() error {
if self.subnetGroup != nil {
return nil
}
err := self.fetchClusters()
if err != nil {
return errors.Wrap(err, "self.fetchClusters()")
}
subnetGroupName := ""
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.CacheSubnetGroupName != nil {
subnetGroupName = *cluster.CacheSubnetGroupName
}
}
if len(subnetGroupName) == 0 {
return cloudprovider.ErrNotFound
}
subnetGroup, err := self.region.DescribeCacheSubnetGroups(subnetGroupName)
if err != nil {
return errors.Wrapf(err, "self.region.DescribeCacheSubnetGroups(%s)", subnetGroupName)
}
if len(subnetGroup) == 0 {
return errors.Wrapf(cloudprovider.ErrNotFound, "subnetGroup %s not found", subnetGroupName)
}
if len(subnetGroup) > 1 {
return cloudprovider.ErrDuplicateId
}
self.subnetGroup = subnetGroup[0]
return nil
}
func (self *SElasticache) GetVpcId() string {
err := self.fetchSubnetGroup()
if err != nil {
log.Errorf("Error:%s,self.fetchSubnetGroup()", err)
return ""
}
if self.subnetGroup != nil && self.subnetGroup.VpcId != nil {
return *self.subnetGroup.VpcId
}
return ""
}
func (self *SElasticache) GetZoneId() string {
return ""
}
func (self *SElasticache) GetNetworkType() string {
if len(self.GetVpcId()) > 0 {
return api.LB_NETWORK_TYPE_VPC
}
return api.LB_NETWORK_TYPE_CLASSIC
}
func (self *SElasticache) GetNetworkId() string {
return ""
}
// cluster mode(shard) 只有配置endpoint,no cluster mode 有primary/readonly endpoint
func (self *SElasticache) GetPrivateDNS() string {
for _, nodeGroup := range self.replicaGroup.NodeGroups {
if nodeGroup != nil && nodeGroup.PrimaryEndpoint != nil && nodeGroup.PrimaryEndpoint.Address != nil {
return *nodeGroup.PrimaryEndpoint.Address
}
}
return ""
}
func (self *SElasticache) GetPrivateIpAddr() string {
return ""
}
func (self *SElasticache) GetPrivateConnectPort() int {
for _, nodeGroup := range self.replicaGroup.NodeGroups {
if nodeGroup != nil && nodeGroup.PrimaryEndpoint != nil && nodeGroup.PrimaryEndpoint.Port != nil {
return int(*nodeGroup.PrimaryEndpoint.Port)
}
}
return 0
}
func (self *SElasticache) GetPublicDNS() string {
return ""
}
func (self *SElasticache) GetPublicIpAddr() string {
return ""
}
func (self *SElasticache) GetPublicConnectPort() int {
return 0
}
func (self *SElasticache) GetMaintainStartTime() string {
self.fetchClusters()
window := ""
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.PreferredMaintenanceWindow != nil {
window = *cluster.PreferredMaintenanceWindow
break
}
}
splited := strings.Split(window, "-")
return splited[0]
}
func (self *SElasticache) GetMaintainEndTime() string {
self.fetchClusters()
window := ""
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.PreferredMaintenanceWindow != nil {
window = *cluster.PreferredMaintenanceWindow
break
}
}
splited := strings.Split(window, "-")
if len(splited) == 2 {
return splited[1]
}
return ""
}
func (self *SElasticache) GetUsers() ([]SElasticacheUser, error) {
result := []SElasticacheUser{}
users, err := self.region.DescribeUsers("")
if err != nil {
return nil, errors.Wrap(err, "self.region.DescribeUsers")
}
for i := range users {
result = append(result, SElasticacheUser{region: self.region, user: users[i]})
}
return result, nil
}
func (self *SElasticache) GetICloudElasticcacheAccounts() ([]cloudprovider.ICloudElasticcacheAccount, error) {
result := []cloudprovider.ICloudElasticcacheAccount{}
users, err := self.GetUsers()
if err != nil {
return nil, errors.Wrap(err, "self.GetUsers()")
}
for i := range users {
result = append(result, &users[i])
}
return result, nil
}
func (self *SElasticache) GetUserById(id string) (*SElasticacheUser, error) {
users, err := self.region.DescribeUsers("")
if err != nil {
return nil, errors.Wrap(err, "self.region.DescribeUsers")
}
for i := range users {
temp := SElasticacheUser{region: self.region, user: users[i]}
if temp.GetId() == id {
return &temp, nil
}
}
return nil, cloudprovider.ErrNotFound
}
func (self *SElasticache) GetICloudElasticcacheAccount(accountId string) (cloudprovider.ICloudElasticcacheAccount, error) {
user, err := self.GetUserById(accountId)
if err != nil {
return nil, errors.Wrapf(err, "self.GetUserById(%s)", accountId)
}
return user, nil
}
func (self *SElasticache) GetICloudElasticcacheAcls() ([]cloudprovider.ICloudElasticcacheAcl, error) {
return []cloudprovider.ICloudElasticcacheAcl{}, nil
}
func (self *SElasticache) GetICloudElasticcacheAcl(aclId string) (cloudprovider.ICloudElasticcacheAcl, error) {
return nil, cloudprovider.ErrNotSupported
}
func (self *SElasticache) GetSnapshots() ([]SElasticacheSnapshop, error) {
result := []SElasticacheSnapshop{}
snapshots, err := self.region.DescribeSnapshots(self.GetName(), "")
if err != nil {
return nil, errors.Wrapf(err, " self.region.DescribeSnapshots(%s)", self.GetName())
}
for i := range snapshots {
result = append(result, SElasticacheSnapshop{region: self.region, snapshot: snapshots[i]})
}
return result, nil
}
func (self *SElasticache) GetICloudElasticcacheBackups() ([]cloudprovider.ICloudElasticcacheBackup, error) {
snapshots, err := self.GetSnapshots()
if err != nil {
return nil, errors.Wrap(err, "self.GetSnapshots()")
}
result := []cloudprovider.ICloudElasticcacheBackup{}
for i := range snapshots {
result = append(result, &snapshots[i])
}
return result, nil
}
func (self *SElasticache) GetICloudElasticcacheBackup(backupId string) (cloudprovider.ICloudElasticcacheBackup, error) {
snapshots, err := self.GetSnapshots()
if err != nil {
return nil, errors.Wrap(err, "self.GetSnapshots()")
}
for i := range snapshots {
if snapshots[i].GetId() == backupId {
return &snapshots[i], nil
}
}
return nil, cloudprovider.ErrNotFound
}
func (self *SElasticache) GetParameterGroupName() (string, error) {
err := self.fetchClusters()
if err != nil {
return "", errors.Wrap(err, "self.fetchClusters()")
}
for _, cluster := range self.cacheClusters {
if cluster != nil && cluster.CacheParameterGroup != nil && cluster.CacheParameterGroup.CacheParameterGroupName != nil {
return *cluster.CacheParameterGroup.CacheParameterGroupName, nil
}
}
return "", cloudprovider.ErrNotFound
}
func (self *SElasticache) GetParameters() ([]SElasticacheParameter, error) {
groupName, err := self.GetParameterGroupName()
if err != nil {
return nil, errors.Wrap(err, "self.GetParameterGroupName()")
}
parameters, err := self.region.DescribeCacheParameters(groupName)
if err != nil {
return nil, errors.Wrapf(err, "self.region.DescribeCacheParameters(%s)", groupName)
}
result := []SElasticacheParameter{}
for i := range parameters {
result = append(result, SElasticacheParameter{parameterGroup: groupName, parameter: parameters[i]})
}
return result, nil
}
func (self *SElasticache) GetICloudElasticcacheParameters() ([]cloudprovider.ICloudElasticcacheParameter, error) {
parameters, err := self.GetParameters()
if err != nil {
return nil, errors.Wrap(err, "self.GetParameters()")
}
result := []cloudprovider.ICloudElasticcacheParameter{}
for i := range parameters {
result = append(result, ¶meters[i])
}
return result, nil
}
func (self *SElasticache) GetSecurityGroupIds() ([]string, error) {
err := self.fetchClusters()
if err != nil {
return nil, errors.Wrap(err, "self.fetchClusters()")
}
result := []string{}
for _, cluster := range self.cacheClusters {
if cluster != nil {
for _, securityGroup := range cluster.SecurityGroups {
if securityGroup != nil && securityGroup.Status != nil && *securityGroup.Status == "active" {
if securityGroup.SecurityGroupId != nil {
result = append(result, *securityGroup.SecurityGroupId)
}
}
}
}
}
return result, nil
}
func (self *SElasticache) AllocatePublicConnection(port int) (string, error) {
return "", cloudprovider.ErrNotSupported
}
func (self *SElasticache) ChangeInstanceSpec(spec string) error {
return cloudprovider.ErrNotSupported
}
func (self *SElasticache) CreateAccount(input cloudprovider.SCloudElasticCacheAccountInput) (cloudprovider.ICloudElasticcacheAccount, error) {
return nil, cloudprovider.ErrNotImplemented
}
func (self *SElasticache) CreateAcl(aclName, securityIps string) (cloudprovider.ICloudElasticcacheAcl, error) {
return nil, cloudprovider.ErrNotSupported
}
func (self *SElasticache) CreateBackup(desc string) (cloudprovider.ICloudElasticcacheBackup, error) {
return nil, cloudprovider.ErrNotImplemented
}
func (self *SElasticache) Delete() error {
return cloudprovider.ErrNotImplemented
}
func (self *SElasticache) FlushInstance(input cloudprovider.SCloudElasticCacheFlushInstanceInput) error {
return cloudprovider.ErrNotSupported
}
func (self *SElasticache) GetAuthMode() string {
return ""
}
func (self *SElasticache) ReleasePublicConnection() error {
return cloudprovider.ErrNotSupported
}
func (self *SElasticache) Renew(bc billing.SBillingCycle) error {
return cloudprovider.ErrNotSupported
}
func (self *SElasticache) Restart() error {
return cloudprovider.ErrNotSupported
}
func (self *SElasticache) SetMaintainTime(maintainStartTime, maintainEndTime string) error {
return cloudprovider.ErrNotImplemented
}
func (self *SElasticache) UpdateAuthMode(noPwdAccess bool, password string) error {
return cloudprovider.ErrNotImplemented
}
func (self *SElasticache) UpdateBackupPolicy(config cloudprovider.SCloudElasticCacheBackupPolicyUpdateInput) error {
return cloudprovider.ErrNotImplemented
}
func (self *SElasticache) UpdateInstanceParameters(config jsonutils.JSONObject) error {
return cloudprovider.ErrNotImplemented
}
func (self *SElasticache) UpdateSecurityGroups(secgroupIds []string) error {
return cloudprovider.ErrNotImplemented
}
|
package limiter
import (
"context"
"errors"
)
var ErrLimited = errors.New("limiter: Limited")
type DoneFunc func()
type AllowOptions struct {
NoWait bool
N int
}
type Limiter interface {
Allow(context.Context, AllowOptions) (DoneFunc, error)
}
|
package main
import (
"errors"
"fmt"
"log"
"net/http"
"github.com/cyc-ttn/gorouter"
. "github.com/altrudos/api"
)
var (
ErrBlankConfigPath = errors.New("config file path is blank")
ErrNoPort = errors.New("port in config is empty")
)
type Server struct {
S *Services
Config *Config
R *gorouter.RouterNode
}
func NewServer(config *Config) (*Server, error) {
services, err := config.Connect()
if err != nil {
return nil, err
}
s := &Server{}
s.S = services
s.Config = config
s.AddRoutes(
CharityRoutes,
DonationRoutes,
DriveRoutes,
)
return s, nil
}
func NewServerFromConfigFile(confFile string) (*Server, error) {
if confFile == "" {
return nil, ErrBlankConfigPath
}
config, err := ParseConfig(confFile)
if err != nil {
return nil, err
}
return NewServer(config)
}
func (s *Server) AddRoutes(rs ...[]gorouter.Route) error {
if s.R == nil {
s.R = gorouter.NewRouter()
}
for _, rr := range rs {
for _, r := range rr {
if err := s.R.AddRoute(r); err != nil {
return err
}
}
}
return nil
}
func (s *Server) Run() error {
if s.Config.Port == 0 {
return ErrNoPort
}
log.Printf("Starting server on port %d", s.Config.Port)
return http.ListenAndServe(fmt.Sprintf(":%d", s.Config.Port), s)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//CORS
w.Header().Set("Access-Control-Allow-Origin", s.Config.WebsiteUrl)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
ctx := &gorouter.RouteContext{
W: w,
R: r,
Method: r.Method,
Path: r.URL.Path,
Query: r.URL.Query(),
}
route, err := s.R.Match(r.Method, r.URL.Path, ctx)
if err == gorouter.ErrPathNotFound || route == nil {
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
route.GetHandler()(&RouteContext{
Services: s.S,
RouteContext: *ctx,
Config: s.Config,
})
}
|
package actions
import "log"
import "cointhink/proto"
import gproto "github.com/golang/protobuf/proto"
import "cointhink/model/algorithm"
func DoAlgorithmList(_algorithmList *proto.AlgorithmList, accountId string) []gproto.Message {
var responses []gproto.Message
rows, err := algorithm.FindReady()
if err != nil {
log.Printf("algo err %+v", err)
responses = append(responses, &proto.AlgorithmListResponse{Ok: false,
Algorithms: []*proto.Algorithm{}})
} else {
log.Printf("algo rows %d", len(rows))
responses = append(responses, &proto.AlgorithmListResponse{Ok: true,
Algorithms: rows})
}
return responses
}
|
package array
// Permutations test
// Given a collection of numbers, return all possible permutations
func Permutations(arr []int, start int) [][]int {
temp := make([]int, 0)
temp = append(temp, arr[start:]...)
res := make([][]int, 0)
if len(temp) == 2 {
res = append(res, []int{temp[0], temp[1]})
res = append(res, []int{temp[1], temp[0]})
return res
}
for i := 0; i < len(temp); i++ {
temp[0], temp[i] = arr[i], arr[0]
children := Permutations(arr, start+1)
for j := 0; j < len(children); j++ {
curr := make([]int, 1)
curr[0] = temp[0]
curr = append(curr, children[j]...)
res = append(res, curr)
}
}
return res
}
|
package constants
const (
// DBConnectionString : mysql connection string
DBConnectionString string = "root:password@/gatorloop?charset=utf8"
// TotalPodDistance : the total distance from start to finish of the track
TotalPodDistance float64 = 5000
)
|
package service
import (
"errors"
"testing"
"github.com/scottski/di-test/pkg/database"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func Test_ReceiveMessage_Success(t *testing.T) {
dbMock := &database.DBMock{}
// Return this on any argument passed in
dbMock.On("Upsert", mock.Anything).Return(nil)
msgService := NewMessageService(dbMock)
status, err := msgService.RecieveMessage("")
assert.Nil(t, err)
assert.Equal(t, status, 200)
}
func Test_SendMessage_Error(t *testing.T) {
dbMock := &database.DBMock{}
// Return an error on any argument
dbMock.On("Upsert", mock.Anything).Return(errors.New("Bad json"))
msgService := NewMessageService(dbMock)
status, err := msgService.RecieveMessage("")
assert.NotNil(t, err)
assert.Equal(t, status, 500)
assert.Equal(t, err.Error(), "Bad json")
}
|
/*
* Copyright 2020 The Dragonfly 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 version
const (
Major = "2"
Minor = "0"
GitVersion = "v2.0.0-rc.0"
GoVersion = "go1.15.2"
Platform = osArch
BuildDay = "2021-04-26"
)
|
// This file has been created by "go generate" as initial code. go generate will never update it, EXCEPT if you remove it.
// So, update it for your need.
package main
import (
"io/ioutil"
"fmt"
"github.com/forj-oss/goforjj"
"github.com/xanzy/go-gitlab"
"gopkg.in/yaml.v2"
)
//GitlabPlugin main struct
type GitlabPlugin struct{
yaml YamlGitlab
sourcePath string
deployMount string
instance string
deployTo string
token string
group string
app *AppInstanceStruct //forjfile access
Client *gitlab.Client //gitlab client ~ api gitlab
gitlabSource GitlabSourceStruct //urls...
gitlabDeploy GitlabDeployStruct //
gitFile string
deployFile string
sourceFile string
//maintain
workspaceMount string
maintainCtxt bool
force bool
newForge bool
}
//GitlabSourceStruct (Fix inline)
type GitlabSourceStruct struct{
goforjj.PluginService `,inline` //base url
ProdGroup string `yaml:"production-group-name"` //`yaml:"production-group-name, omitempty"`
}
//GitlabDeployStruct (TODO)
type GitlabDeployStruct struct{
goforjj.PluginService `yaml:",inline"` //urls
Projects map[string]ProjectStruct // projects managed in gitlab
NoProjects bool `yaml:",omitempty"`
ProdGroup string
Group string
GroupDisplayName string
GroupId int
//...
}
const gitlabFile = "forjj-gitlab.yaml"
//YamlGitlab (TODO)
type YamlGitlab struct {
}
func newPlugin(src string) (gls *GitlabPlugin) {
gls = new(GitlabPlugin)
gls.sourcePath = src
return
}
func (gls *GitlabPlugin) initializeFrom(r *CreateReq, ret *goforjj.PluginData) (status bool) {
return true
}
func (gls *GitlabPlugin) loadFrom(ret *goforjj.PluginData) (status bool) {
return true
}
func (gls *GitlabPlugin) updateFrom(r *UpdateReq, ret *goforjj.PluginData) (status bool) {
return true
}
func (gls *GitlabPlugin) saveYaml(in interface{}, file string) (Updated bool, _ error) {
d, err := yaml.Marshal(in)
if err != nil {
return false, fmt.Errorf("Unable to encode gitlab data in yaml. %s", err)
}
if dBefore, err := ioutil.ReadFile(file); err != nil{
Updated = true
} else {
Updated = (string(d) != string(dBefore))
}
if !Updated {
return
}
if err = ioutil.WriteFile(file, d, 0644); err != nil {
return false, fmt.Errorf("Unable to save '%s'. %s", file, err)
}
return
}
func (gls *GitlabPlugin) loadYaml(file string) error {
d, err := ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("Unable to load '%s'. %s", file, err)
}
err = yaml.Unmarshal(d, &gls.gitlabDeploy)
if err != nil {
return fmt.Errorf("Unable to decode gitlab data in yaml. %s", err)
}
return nil
}
|
package audioprocessing
import (
"github.com/xfrr/goffmpeg/transcoder"
"log"
)
type FFmpegPlayer struct {
PlayerNo int
Trans *transcoder.Transcoder
Tracks TrackManager
}
func (fp *FFmpegPlayer) Queue(t Track) int {
index := fp.Tracks.AddTrack(t)
log.Printf("[ Player %v ] Queued track at position %v", fp.PlayerNo, index)
return index
}
func (fp *FFmpegPlayer) RemoveTrackByIndex(n int) bool {
success, track := fp.Tracks.RemoveTrackByIndex(n)
if success {
log.Printf("[ Player %v ] Removed track %v", fp.PlayerNo, track.Id)
} else {
log.Printf("[ Player %v ] Failed to removed track as index %v", fp.PlayerNo, n)
}
return success
}
func (fp *FFmpegPlayer) RemoveTrackById(id string) bool {
success, track := fp.Tracks.RemoveTrackById(id)
if success {
log.Printf("[ Player %v ] Removed track %v", fp.PlayerNo, track.Id)
} else {
log.Printf("[ Player %v ] Failed to removed track with id %v", fp.PlayerNo, id)
}
return success
}
|
package main
import (
"log"
"net/http"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
const gitRevision = "<filled in by CI service>"
func main() {
// start collector
coll := NewCollector(conf.db, conf.ms, conf.scanInterval, conf.extraServers, conf.verbose)
go coll.Run()
// start web frontends
r := chi.NewRouter()
r.Use(
middleware.RedirectSlashes,
requestLogging,
)
r.Mount("/api", NewAPI(conf.db))
r.Mount("/", NewWebInterface(conf.db, conf.kidban))
log.Println("server listening on", conf.webInterfaceAddress)
err := http.ListenAndServe(conf.webInterfaceAddress, r)
if err != nil {
log.Println(err)
}
}
func requestLogging(h http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
remoteAddr := req.Header.Get("X-Real-IP")
if remoteAddr == "" {
remoteAddr = req.RemoteAddr
}
log.Println(strings.Split(remoteAddr, ":")[0], "requested", req.URL.String())
h.ServeHTTP(resp, req)
})
}
|
package simplegrab
import (
"crypto/md5"
"encoding/hex"
"errors"
"io"
"net/http"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
)
// 计算string的md5值,以32位字符串形式返回
func StringToMd5(s string) string {
h := md5.New()
io.WriteString(h, s)
return hex.EncodeToString(h.Sum(nil))
}
// 将数据(url)下载到本地(filepath)
// 注意:需要保证url链接的网页(或文件)无需设置相关cookie和header也可下载
func download(urlStr, filepath string) (*http.Response, error) {
resp, err := http.Get(urlStr)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("StatusCode not 200")
}
file, err := os.Create(filepath)
if err != nil {
return nil, err
}
defer file.Close()
io.Copy(file, resp.Body)
return resp, nil
}
// 根据url和后缀(ext)得到在本地存储的filename
func GetFilenameFromUrl(urlStr, ext string) string {
ext = "." + strings.TrimLeft(ext, ".")
return StringToMd5(urlStr) + ext
}
// 下载url,保存到本地目录dir下,文件名为GetFilenameFromUrl(urlStr, ext)
// 注意:需要保证url链接的网页(或文件)无需设置相关cookie和header也可下载
func Download(urlStr, dir, ext string, refresh bool) (*http.Response, string, error) {
dir = strings.TrimRight(dir, "/") + "/"
filepath := dir + GetFilenameFromUrl(urlStr, ext)
// 若本地已经存在就不再下载,此时http.Response为nil
if !refresh {
if _, err := os.Stat(filepath); err == nil {
return nil, filepath, nil
}
}
resp, err := download(urlStr, filepath)
if err != nil {
return nil, "", err
}
return resp, filepath, nil
}
// 下载网页(url),并返回它的Document结构
// 如果网页已经存在,则不重新下载
func GetDocument(url, dir, ext string) (*goquery.Document, *http.Response, string, error) {
resp, filepath, err := Download(url, dir, ext, false)
if err != nil {
return nil, nil, "", err
}
file, err := os.Open(filepath)
if err != nil {
return nil, resp, filepath, err
}
defer file.Close()
doc, err := goquery.NewDocumentFromReader(file)
if err != nil {
return nil, resp, filepath, err
}
return doc, resp, filepath, nil
}
// 下载网页(url),并返回它的Document结构
// 如果网页已经存在,仍然重新下载
func GetDocumentNeedRefresh(url, dir, ext string) (*goquery.Document, *http.Response, string, error) {
resp, filepath, err := Download(url, dir, ext, true)
if err != nil {
return nil, nil, "", err
}
file, err := os.Open(filepath)
if err != nil {
return nil, resp, filepath, err
}
defer file.Close()
doc, err := goquery.NewDocumentFromReader(file)
if err != nil {
return nil, resp, filepath, err
}
return doc, resp, filepath, nil
}
// 拷贝文件,返回写入的字节数或错误
func CopyFile(dstName, srcName string) (written int64, err error) {
file, err := os.Stat(dstName)
if err == nil && file.IsDir() {
dstName = strings.TrimRight(dstName, "/") + "/" + srcName
}
src, err := os.Open(srcName)
if err != nil {
return 0, err
}
defer src.Close()
dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, os.ModePerm)
if err != nil {
return 0, err
}
defer dst.Close()
return io.Copy(dst, src)
}
|
package server
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/dan-v/seattlerb-battleship/battleship"
"github.com/dan-v/seattlerb-battleship/common"
)
type Server struct {
wins int
losses int
gameID int
games map[int]*battleship.Game
previousGuess map[int]battleship.Location
}
func NewServer() *Server {
server := &Server{
wins: 0,
losses: 0,
gameID: 0,
games: make(map[int]*battleship.Game),
previousGuess: make(map[int]battleship.Location),
}
return server
}
func (s *Server) newGame(w http.ResponseWriter, r *http.Request) {
s.gameID++
fmt.Fprintf(w, "{\"game_id\": %v}", s.gameID)
}
func (s *Server) turn(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var turn common.Turn
err := decoder.Decode(&turn)
if err != nil {
panic(err)
}
defer r.Body.Close()
log.Println("RAW TURN RESPONSE:", turn)
if _, ok := s.games[turn.GameID]; !ok {
s.games[turn.GameID] = battleship.NewGame()
s.previousGuess[turn.GameID] = "J1"
}
opponentResponse := s.games[turn.GameID].HandleAttackResponse(s.previousGuess[turn.GameID], &turn)
log.Println("RAW RESPONSE:", opponentResponse)
guess := s.games[turn.GameID].GetRecommendedNextMove()
s.previousGuess[turn.GameID] = guess
log.Println("GUESS:", guess)
responseTurn := &common.Turn{
GameID: turn.GameID,
Guess: common.Guess{
Guess: string(guess),
},
Response: *opponentResponse,
}
b, err := json.Marshal(responseTurn)
fmt.Println(s.games[turn.GameID].MyBoard)
fmt.Println(s.games[turn.GameID].OpponentBoard)
if turn.Response.Lost {
log.Println("###############")
log.Println("YOU WON!")
log.Println("###############")
s.wins++
log.Printf("Record: %v wins and %v losses", s.wins, s.losses)
}
if opponentResponse.Lost {
log.Println("###############")
log.Println("YOU LOST :(")
log.Println("###############")
s.losses++
log.Printf("Record: %v wins and %v losses", s.wins, s.losses)
}
fmt.Fprint(w, string(b))
}
func (s *Server) Run() {
http.HandleFunc("/new_game", s.newGame)
http.HandleFunc("/turn", s.turn)
log.Fatal(http.ListenAndServe(":8888", nil))
}
|
package entitys
import (
"time"
)
type ArticleBox struct {
ID string `gorm:"type:uuid; primary_key; default: uuid_generate_v4();" json:"id"`
Name string `gorm:"size:100" json:"name"`
Creator User
CreatorId string `gorm:"type:varchar(100)" json:"-"`
Type string `gorm:"size:30;default:'DEFAULT'" json:"type"`
Status string `gorm:"size:30;default:'ACTIVE'" json:"status"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
|
package im
import (
"encoding/json"
"errors"
)
const userBaseUrl = "https://api.im.jpush.cn/v1/users/"
type User struct {
IM
}
type UserInfo struct {
UserName string `json:"username"`
AppKey string `json:"appkey"` //用户所在的appkey 估计android ios不能使同一个应用
Password string `json:"password"` //极光会md5一次
NickName string `json:"nickname"`
Avatar string `json:"avatar"` //需要填上从文件上传接口获得的media_id
Birthday string `json:"birthday"` //"1990-01-24 00:00:00"
Gender int8 `json:"gender"` //性别 0 - 未知, 1 - 男 ,2 - 女
Signature string `json:"signature"` //用户签名
Region string `json:"region"` //用户所属地区
Address string `json:"address"` //用户详细地址
CTime string `json:"ctime"` //创建"1990-01-24 00:00:00"
MTime string `json:"mtime"` //修改"1990-01-24 00:00:00"
Extras string `json:"extras"` //自定义字段 json 对象
}
type UserInfoResult struct {
UserName string `json:"username"`
Error `json:"error"`
}
func NewUser(config *Config) *User {
return &User{
IM{config: config},
}
}
// 用户注册 这里为啥不传UserInfo 是因为那边有些参数存在无值会报错
func (i *User) Register(userList []map[string]interface{}) (error, []UserInfoResult) {
l := len(userList)
result := make([]UserInfoResult, l)
if l == 0 {
return errors.New("请传要添加的用户列表"), result
}
if l > 500 {
return errors.New("一次最多500"), result
}
i.setUri(userBaseUrl)
bytes, err := json.Marshal(userList)
if err != nil {
return err, result
}
Response := i.post(bytes)
if Response.Err != nil {
return Response.Err, result
}
err = json.Unmarshal(Response.Data, &result)
if err == nil {
return err, result
}
//创建失败,具体信息看返回
if Response.StatusCode != 201 {
return errors.New("添加失败"), result
}
return nil, result
}
// 更新信息
func (i *User) Update(userName string, info map[string]interface{}) error {
i.setUri(userBaseUrl + userName)
bytes, err := json.Marshal(info)
if err != nil {
return err
}
Response := i.put(bytes)
if Response.Err != nil {
return Response.Err
}
if Response.StatusCode != 204 {
return errors.New("更新失败")
}
return nil
}
|
package thttp
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jrapoport/gothic/config"
"github.com/jrapoport/gothic/jwt"
"github.com/jrapoport/gothic/models/user"
"github.com/stretchr/testify/require"
)
// Do does an http request
func Do(t *testing.T, s *httptest.Server,
method, path string, v url.Values, body interface{}) (*http.Response, error) {
return DoAuth(t, s, method, path, "", v, body)
}
// DoAuth does an authorized http request
func DoAuth(t *testing.T, s *httptest.Server,
method, path, token string, v url.Values, body interface{}) (*http.Response, error) {
req := Request(t, method, s.URL+path, token, v, body)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
if res.StatusCode != http.StatusOK {
err = errors.New(res.Status)
var b string
if res.Body != nil {
buf, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() {
err = res.Body.Close()
require.NoError(t, err)
})
b = string(buf)
}
if len(b) > 0 {
b = strings.TrimRight(b, "\n")
err = fmt.Errorf("%w: %s", err, b)
}
t.Log(err)
return nil, err
}
return res, nil
}
// DoRequest makes an HTTP server request.
func DoRequest(t *testing.T, s *httptest.Server, method, path string, v url.Values, body interface{}) (string, error) {
return DoAuthRequest(t, s, method, path, "", v, body)
}
// DoAuthRequest makes an authenticated HTTP server request.
func DoAuthRequest(t *testing.T, s *httptest.Server, method, path, token string, v url.Values, body interface{}) (string, error) {
res, err := DoAuth(t, s, method, path, token, v, body)
if err != nil {
return "", err
}
var b string
if res.Body != nil {
buf, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() {
err = res.Body.Close()
require.NoError(t, err)
})
b = string(buf)
}
return b, err
}
// FmtError formats an error for tests.
func FmtError(code int) error {
msg := http.StatusText(code)
return fmt.Errorf("%d %s: %s", code, msg, msg)
}
// UserToken returns a dummy token for tests.
func UserToken(t *testing.T, c config.JWT, confirmed, admin bool) string {
return token(t, c, uuid.New(), confirmed, admin)
}
// BadToken returns a bad token for tests.
func BadToken(t *testing.T, c config.JWT) string {
return token(t, c, uuid.Nil, false, false)
}
func token(t *testing.T, c config.JWT, uid uuid.UUID, confirmed, admin bool) string {
if admin {
confirmed = true
}
claims := jwt.NewUserClaims(&user.User{})
claims.StandardClaims = *jwt.NewStandardClaims(uid.String())
_ = claims.Set(jwt.AdminKey, admin)
_ = claims.Set(jwt.ConfirmedKey, confirmed)
tk, err := jwt.NewToken(c, claims).Bearer()
require.NoError(t, err)
return tk
}
|
package main
import "sort"
//1365. 有多少小于当前数字的数字
//给你一个数组nums,对于其中每个元素nums[i],请你统计数组中比它小的所有数字的数目。
//
//换而言之,对于每个nums[i]你必须计算出有效的j的数量,其中 j 满足j != i 且 nums[j] < nums[i]。
func smallerNumbersThanCurrent(nums []int) []int {
dic := make(map[int][]int)
for i, v := range nums {
dic[v] = append(dic[v], i)
}
sort.Ints(nums)
result := make([]int, len(nums))
var pre, index int
for i, v := range nums {
if pre != v {
pre = v
index = i
for _, val := range dic[v] {
result[val] = index
}
}
}
return result
}
|
package main
func minSubArrayLen(s int, nums []int) int {
array := make([]int, 0)
result := 0
sum := 0
for _, w := range nums {
array = append(array, w)
sum += w
for sum >= s {
if result == 0 || result > len(array) {
result = len(array)
}
sum -= array[0]
array = array[1:]
}
}
return result
}
func main() {
minSubArrayLen(7, []int{2, 3, 1, 2, 4, 3})
}
|
package controllers
import (
"github.com/1046102779/common/consts"
. "github.com/1046102779/official_account/logger"
"github.com/1046102779/official_account/models"
"github.com/astaxie/beego"
"github.com/pkg/errors"
)
// IndustryCodeQuerysController oprations for IndustryCodeQuerys
type IndustryCodeQuerysController struct {
beego.Controller
}
// 获取主行业列表
// @router /main_industrys [GET]
func (t *IndustryCodeQuerysController) GetAllMainIndutry() {
if mainIndustrys, retcode, err := models.GetAllMainIndutryNoLocks(); err != nil {
Logger.Error(err.Error())
t.Data["json"] = map[string]interface{}{
"err_code": retcode,
"err_msg": errors.Cause(err).Error(),
}
t.ServeJSON()
return
} else {
t.Data["json"] = map[string]interface{}{
"err_code": 0,
"err_msg": "",
"industry_infos": mainIndustrys,
}
}
t.ServeJSON()
return
}
// 获取副行业列表
// @router /:id/deputy_industrys [GET]
func (t *IndustryCodeQuerysController) GetSecIndutryListNoLocks() {
id, _ := t.GetInt(":id")
if id <= 0 {
err := errors.New("param `:id` empty")
Logger.Error(err.Error())
t.Data["json"] = map[string]interface{}{
"err_code": consts.ERROR_CODE__SOURCE_DATA__ILLEGAL,
"err_msg": errors.Cause(err).Error(),
}
t.ServeJSON()
return
}
industryCodeQuery := &models.IndustryCodeQuerys{
MainType: id,
}
if secIndustrys, retcode, err := industryCodeQuery.GetSecIndutryListNoLocks(); err != nil {
Logger.Error(err.Error())
t.Data["json"] = map[string]interface{}{
"err_code": retcode,
"err_msg": errors.Cause(err).Error(),
}
t.ServeJSON()
return
} else {
t.Data["json"] = map[string]interface{}{
"err_code": 0,
"err_msg": "",
"industry_infos": secIndustrys,
}
}
t.ServeJSON()
return
}
|
package core
import "math"
/* Sigmoid implements methods for the vectorized sigmoid function,
s(x_i) = 1 / (1 + exp(-x_i))
*/
type Sigmoid struct{}
func (a Sigmoid) Name() string {
return "Sigmoid"
}
func (a Sigmoid) Eval(x, Fx []float32) {
for i, u := range x {
Fx[i] = float32(1.0 / (1.0 + math.Exp(-float64(u))))
}
}
func (a Sigmoid) DProd(x, Fx, y []float32) {
for i, v := range Fx {
y[i] *= v * (1.0 - v)
}
}
|
package string
import (
"fmt"
"github.com/project-flogo/core/data/coerce"
"strings"
"github.com/project-flogo/core/data"
"github.com/project-flogo/core/data/expression/function"
)
func init() {
function.Register(&fnTrim{})
}
type fnTrim struct {
}
func (fnTrim) Name() string {
return "trim"
}
func (fnTrim) Sig() (paramTypes []data.Type, isVariadic bool) {
return []data.Type{data.TypeString}, true
}
func (fnTrim) Eval(params ...interface{}) (interface{}, error) {
s1, err := coerce.ToString(params[0])
if err != nil {
return nil, fmt.Errorf("string.trim function first parameter [%+v] must be string", params[0])
}
if len(params) > 1 {
s2, err := coerce.ToString(params[1])
if err != nil {
return nil, fmt.Errorf("string.trim function second parameter [%+v] must be string", params[1])
}
return strings.Trim(s1, s2), nil
}
return strings.TrimSpace(s1), nil
}
|
// Package users provides a domain model for working with users
package users
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jceatwell/bookstore_users-api/domain/users"
"github.com/jceatwell/bookstore_users-api/services"
)
//CreateUser creates new user
func CreateUser(c *gin.Context) {
var user users.User
bytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
//TODO: Handle Error
return
}
if err := json.Unmarshal(bytes, &user); err != nil {
fmt.Println(err.Error())
//TODO: Handle json error
return
}
result, saveErr := services.CreateUser(user)
if saveErr != nil {
//TODO: handle user creation error
return
}
fmt.Println(err)
fmt.Println(string(bytes))
c.String(http.StatusNotImplemented, "TODO: Implement!")
}
//GetUser retrieve user details
func GetUser(c *gin.Context) {
c.String(http.StatusNotImplemented, "TODO: Implement!")
}
|
package discovery
import (
"errors"
"github.com/patrickmn/go-cache"
"github.com/prometheus/common/log"
LOG "github.com/sirupsen/logrus"
"github.com/thinker0/go-serversets"
"regexp"
"strings"
"time"
)
type (
ServiceSetsCache struct {
hosts []string
pathServerSet *cache.Cache
pathWatcher *cache.Cache
serviceSets *cache.Cache
match *regexp.Regexp
}
)
func New(hosts []string) *ServiceSetsCache {
c := new(ServiceSetsCache)
c.hosts = hosts
c.pathServerSet = cache.New(60*time.Minute, 10*time.Minute)
c.pathWatcher = cache.New(60*time.Minute, 10*time.Minute)
c.serviceSets = cache.New(60*time.Minute, 10*time.Minute)
c.match = regexp.MustCompile(`^[a-zA-Z0-9-_]+/(prod|release|releasedr|staging|devel|beta|alpha)/[a-zA-Z0-9-_]+$`)
c.pathServerSet.OnEvicted(func(k string, v interface{}) {
// set := v.(*serversets.ServerSet)
log.Infof("ServerSet Evicted: %s", k)
})
c.pathWatcher.OnEvicted(func(k string, v interface{}) {
watcher := v.(*serversets.Watch)
watcher.Close()
log.Infof("Watcher Evicted: %s", k)
})
c.serviceSets.OnEvicted(func(k string, v interface{}) {
// set := v.(*serversets.ServerSet)
log.Infof("Entity Evicted: %s", k)
})
LOG.Infof("Initialize ServiceSetsCache %s", c.hosts)
return c
}
func (c *ServiceSetsCache) GetServerSetEntity(servicePath string) ([]serversets.Entity, error) {
var serverSets *serversets.ServerSet = nil
var serviceWatch *serversets.Watch = nil
if len(servicePath) == 0 || !c.match.MatchString(servicePath) {
LOG.Errorf("Invalid Path: {}", servicePath)
return nil, errors.New("Service '" + servicePath + "', Not Match ")
}
if s, found := c.pathServerSet.Get(servicePath); found {
serverSets = s.(*serversets.ServerSet)
} else {
paths := strings.Split(servicePath, "/")
LOG.Infof("Initialize ServiceSets: %s/%s", c.hosts, servicePath)
serverSets = serversets.New(paths[0], paths[1], paths[2], c.hosts)
if serverSets == nil {
return nil, errors.New("serverSets nil")
}
c.pathServerSet.Set(servicePath, serverSets, 60*time.Minute)
}
if w, found := c.pathWatcher.Get(servicePath); found {
serviceWatch = w.(*serversets.Watch)
} else {
if serverSets == nil {
return nil, errors.New("serverSets nil")
}
LOG.Infof("Initialize ServiceSets.Watch: %s/%s", c.hosts, servicePath)
newServiceWatch, err := serverSets.Watch()
if err != nil || newServiceWatch == nil {
return nil, err
}
serviceWatch = newServiceWatch
c.pathWatcher.Set(servicePath, newServiceWatch, 60*time.Minute)
}
if serviceWatch == nil {
return nil, errors.New("serviceWatch nil")
}
LOG.Infof("Endpoints: %v", serviceWatch.Endpoints())
return serviceWatch.EndpointEntities(), nil
} |
package main
// TODO: go-doc
import (
"log"
"net"
"net/http"
"net/rpc"
"os"
"github.com/frncmx/screener-prezi/backend/prezidb"
)
const portEnvKey = "PREZI_BACKEND_PORT"
// Listener is a global, initialized before main(). That makes random port
// number accessible from tests.
// TODO: Think and ask for opinions!
// Pros: Truely random ports => portable, no random bind fails
// Cons: This solution feels leaky and hacky
var Listener = func() net.Listener {
port := os.Getenv(portEnvKey)
if port == "" {
log.Printf("WARNING: %v is unset, will use a random port",
portEnvKey)
}
l, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatal("error: ", err)
}
log.Printf("listening on %v", l.Addr())
return l
}()
func main() {
db, err := prezidb.New()
if err != nil {
log.Fatal("error: ", err)
}
rpc.Register(db)
rpc.HandleHTTP()
panic(http.Serve(Listener, nil))
}
|
package main
import "fmt"
type pc struct {
ram int
disk int
brand string
}
func (compt *pc) duplicateRAM() {
compt.ram = compt.ram * 2
}
func (compt pc) ping() {
fmt.Println(compt.brand, "Pong")
}
func main() {
a := 50
b := &a
fmt.Println(a, b)
fmt.Println(a, *b)
myPC := pc{ram: 16, disk: 1024, brand: "msi"}
fmt.Println(myPC)
myPC.ping()
fmt.Println(myPC)
myPC.duplicateRAM()
fmt.Println(myPC)
}
|
// 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 call provides methods for invoking C function pointers.
package call
import "unsafe"
// void V(void* f) { ((void (*)())(f))(); }
// int I(void* f) { return ((int (*)())(f))(); }
// int III(void* f, int a, int b) { return ((int (*)(int, int))(f))(a, b); }
import "C"
// V invokes the function f that has the signature void().
func V(f unsafe.Pointer) { C.V(f) }
// I invokes the function f that has the signature int().
func I(f unsafe.Pointer) int { return (int)(C.I(f)) }
// III invokes the function f that has the signature int(int, int).
func III(f unsafe.Pointer, a, b int) int { return (int)(C.III(f, (C.int)(a), (C.int)(b))) }
|
package models
import (
"strconv"
"../utils"
)
func GetKey() int64 {
var key int64
var val string
// 获取 key
err := db.QueryRow("SELECT `val` FROM `setting` WHERE `key` = 'key' LIMIT 1").Scan(&val)
utils.CheckErr(err)
key, err = strconv.ParseInt(val, 10, 64)
utils.CheckErr(err)
return key
}
|
// Copyright 2018 Authors of Cilium
//
// 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 identity
import (
"net"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/pkg/labels"
)
// Identity is the representation of the security context for a particular set of
// labels.
type Identity struct {
// Identity's ID.
ID NumericIdentity `json:"id"`
// Set of labels that belong to this Identity.
Labels labels.Labels `json:"labels"`
// SHA256 of labels.
LabelsSHA256 string `json:"labelsSHA256"`
}
// IPIdentityPair is a pairing of an IP and the security identity to which that
// IP corresponds.
//
// WARNING - STABLE API
// This structure is written as JSON to the key-value store. Do NOT modify this
// structure in ways which are not JSON forward compatible.
type IPIdentityPair struct {
IP net.IP `json:"IP"`
ID NumericIdentity `json:"ID"`
Metadata string `json:"Metadata"`
}
func NewIdentityFromModel(base *models.Identity) *Identity {
if base == nil {
return nil
}
id := &Identity{
ID: NumericIdentity(base.ID),
Labels: make(labels.Labels),
}
for _, v := range base.Labels {
lbl := labels.ParseLabel(v)
id.Labels[lbl.Key] = lbl
}
return id
}
// GetLabelsSHA256 returns the SHA256 of the labels associated with the
// identity. The SHA is calculated if not already cached.
func (id *Identity) GetLabelsSHA256() string {
if id.LabelsSHA256 == "" {
id.LabelsSHA256 = id.Labels.SHA256Sum()
}
return id.LabelsSHA256
}
// StringID returns the identity identifier as string
func (id *Identity) StringID() string {
return id.ID.StringID()
}
func (id *Identity) GetModel() *models.Identity {
if id == nil {
return nil
}
ret := &models.Identity{
ID: int64(id.ID),
Labels: []string{},
LabelsSHA256: "",
}
for _, v := range id.Labels {
ret.Labels = append(ret.Labels, v.String())
}
ret.LabelsSHA256 = id.GetLabelsSHA256()
return ret
}
// NewIdentity creates a new identity
func NewIdentity(id NumericIdentity, lbls labels.Labels) *Identity {
return &Identity{ID: id, Labels: lbls}
}
|
package server
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/ivan-kapelyukh/knock-knock-unlock/internal/app/server/mongo"
)
type Server struct {
port int
staticDir string
mongo *mongo.Mongo
}
func New(port int, staticDir string, mongo *mongo.Mongo) Server {
return Server{port, staticDir, mongo}
}
func (s *Server) Serve() error {
r := mux.NewRouter()
r.HandleFunc("/register", s.registerHandler)
r.HandleFunc("/login", s.loginHandler)
r.PathPrefix("/").Handler(http.FileServer(http.Dir(s.staticDir)))
http.Handle("/", r)
fmt.Printf("Listening on localhost:%v...\n", s.port)
return http.ListenAndServe(fmt.Sprintf(":%v", s.port), nil)
}
func (s *Server) status(w http.ResponseWriter, code int) {
body := fmt.Sprintf("%v %v", code, http.StatusText(code))
http.Error(w, body, code)
}
func (s *Server) registerHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
s.status(w, http.StatusMethodNotAllowed)
return
}
decoder := json.NewDecoder(r.Body)
var user mongo.User
err := decoder.Decode(&user)
if err != nil {
log.Printf("Error decoding `%v` into mongo.User: %v\n", r.Body, err)
s.status(w, http.StatusBadRequest)
return
}
err = user.Validate()
if err != nil {
s.status(w, http.StatusBadRequest)
return
}
err = s.mongo.Insert(user)
if err != nil {
log.Printf("Error storing %v into kku.users: %v\n", user, err)
// TODO: this might also be an internal server error
s.status(w, http.StatusBadRequest)
return
}
s.status(w, http.StatusOK)
}
func (s *Server) loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
s.status(w, http.StatusMethodNotAllowed)
return
}
decoder := json.NewDecoder(r.Body)
var login Login
err := decoder.Decode(&login)
if err != nil {
log.Printf("Error decoding `%v` into server.Login: %v\n", r.Body, err)
s.status(w, http.StatusBadRequest)
return
}
err = login.Validate()
if err != nil {
s.status(w, http.StatusBadRequest)
return
}
user, err := s.mongo.Find(login.Username)
if err != nil {
// FIXME: assuming the user does not exist
user := mongo.User{login.Username, [][]int{login.Knock, login.Knock, login.Knock}}
err = s.mongo.Insert(user)
if err != nil {
log.Printf("Error storing %v into kku.users: %v\n", user, err)
// TODO: this might also be an internal server error
s.status(w, http.StatusBadRequest)
return
}
fmt.Fprintf(w, "200 REGISTERED")
return
}
if !MatchesMajority(login.Knock, user.Knocks) {
s.status(w, http.StatusForbidden)
return
}
s.status(w, http.StatusOK)
}
|
package packet
import (
"bytes"
"testing"
)
func noop() {}
type TestPacket struct {
id uint
field uint8
}
func (tp *TestPacket) MarshalBinary() []byte {
return []byte{byte(tp.id), byte(tp.field)}
}
func (tp *TestPacket) UnmarshalBinary(data []byte) error {
return nil
}
func (tp *TestPacket) setHeader(h *HeaderPacket) {
}
func (tp *TestPacket) Header() *HeaderPacket {
return nil
}
type DummyLogger struct {
}
func (l DummyLogger) Infof(format string, args ...interface{}) {
noop()
}
func (l DummyLogger) Errorf(format string, args ...interface{}) {
noop()
}
func (l DummyLogger) Debugf(format string, args ...interface{}) {
noop()
}
func TestReadHead(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Fatalf("panic while reading HeaderPacket: %s", err.(error).Error())
}
}()
t.Parallel()
testPacket := []byte{0x10, 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}
emptyPacket := []byte{}
ph := GamePacketHandler{}
header, err := ph.ReadHead(bytes.NewBuffer(testPacket))
if err == nil {
t.Error("calling ReadHead with zero HeadLength yeilds no error")
}
if header != nil {
t.Error("calling ReadHead with zero HeadLength results in header not being nil")
}
ph = GamePacketHandler{HeadLength: 6}
header, err = ph.ReadHead(bytes.NewBuffer(emptyPacket))
if err == nil {
t.Error("reading empty packet yeilds no error")
}
if header != nil {
t.Error("reading empty packet results in in header not being nil")
}
header, err = ph.ReadHead(bytes.NewBuffer(testPacket))
if err != nil {
t.Errorf("error reading head: %s", err.Error())
}
if header.ID != 0x10 {
t.Errorf("wrong header.ID: expected %d, got %d", 16, header.ID)
}
}
|
/*
Copyright (c) 2019 The Helm 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 foundationdb
import (
"context"
"fmt"
"time"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const defaultTimeout = 30 * time.Second
// Config configures the database connection
type Config struct {
URL string
Database string
Timeout time.Duration
}
// Client is an interface for a MongoDB client
type Client interface {
Database(name string) (Database, func())
}
// Database is an interface for accessing a MongoDB database
type Database interface {
Collection(name string) Collection
}
// Collection is an interface for accessing a MongoDB collection
type Collection interface {
BulkWrite(ctxt context.Context, operations []mongo.WriteModel, options *options.BulkWriteOptions) (*mongo.BulkWriteResult, error)
DeleteMany(ctxt context.Context, filter interface{}, options *options.DeleteOptions) (*mongo.DeleteResult, error)
FindOne(ctxt context.Context, filter interface{}, result interface{}, options *options.FindOneOptions) error
InsertOne(ctxt context.Context, document interface{}, options *options.InsertOneOptions) (*mongo.InsertOneResult, error)
UpdateOne(ctxt context.Context, filter interface{}, update interface{}, options *options.UpdateOptions) (*mongo.UpdateResult, error)
}
// mongoDatabase wraps an mongo.Database and implements Database
type mongoDatabase struct {
Database *mongo.Database
}
// mongoClient wraps an mongo.Database and implements Database
type mongoClient struct {
Client *mongo.Client
}
//NewDocLayerClient creates a mongoDB client using the given options
func NewDocLayerClient(ctx context.Context, options *options.ClientOptions) (Client, error) {
client, err := mongo.Connect(ctx, options)
return &mongoClient{client}, err
}
//Database Creates a new interface for accessing the specified FDB Document-Layer database
func (c *mongoClient) Database(dbName string) (Database, func()) {
db := &mongoDatabase{c.Client.Database(dbName)}
return db, func() {
err := c.Client.Disconnect(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
}
//Collection returns a reference to a given collection in the FDB Document-layer
func (d *mongoDatabase) Collection(name string) Collection {
return &mongoCollection{d.Database.Collection(name)}
}
// mongoCollection wraps a mongo.Collection and implements Collection
type mongoCollection struct {
Collection *mongo.Collection
}
func (c *mongoCollection) BulkWrite(ctxt context.Context, operations []mongo.WriteModel, options *options.BulkWriteOptions) (*mongo.BulkWriteResult, error) {
res, err := c.Collection.BulkWrite(ctxt, operations, options)
return res, err
}
func (c *mongoCollection) DeleteMany(ctxt context.Context, filter interface{}, options *options.DeleteOptions) (*mongo.DeleteResult, error) {
res, err := c.Collection.DeleteMany(ctxt, filter, options)
return res, err
}
func (c *mongoCollection) FindOne(ctxt context.Context, filter interface{}, result interface{}, options *options.FindOneOptions) error {
res := c.Collection.FindOne(ctxt, filter, options)
return res.Decode(result)
}
func (c *mongoCollection) InsertOne(ctxt context.Context, document interface{}, options *options.InsertOneOptions) (*mongo.InsertOneResult, error) {
res, err := c.Collection.InsertOne(ctxt, document, options)
return res, err
}
func (c *mongoCollection) UpdateOne(ctxt context.Context, filter interface{}, document interface{}, options *options.UpdateOptions) (*mongo.UpdateResult, error) {
res, err := c.Collection.UpdateOne(ctxt, filter, document, options)
return res, err
}
|
package bot
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/bots-house/share-file-bot/pkg/log"
"github.com/bots-house/share-file-bot/pkg/tg"
"github.com/bots-house/share-file-bot/service"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/pkg/errors"
"github.com/tomasen/realip"
)
type Bot struct {
client *tgbotapi.BotAPI
authSrv *service.Auth
docSrv *service.Document
adminSrv *service.Admin
handler tg.Handler
}
func (bot *Bot) Self() tgbotapi.User {
return bot.client.Self
}
func New(token string, authSrv *service.Auth, docSrv *service.Document, adminSrv *service.Admin) (*Bot, error) {
client, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, errors.Wrap(err, "create bot api")
}
bot := &Bot{
client: client,
authSrv: authSrv,
docSrv: docSrv,
adminSrv: adminSrv,
}
// bot.client.Debug = true
bot.initHandler()
return bot, nil
}
func (bot *Bot) SetWebhookIfNeed(ctx context.Context, domain string, path string) error {
webhook, err := bot.client.GetWebhookInfo()
if err != nil {
return errors.Wrap(err, "get webhook info")
}
endpoint := strings.Join([]string{domain, path}, "/")
if webhook.URL != endpoint {
u, err := url.Parse(endpoint)
if err != nil {
return errors.Wrap(err, "invalid provided webhook url")
}
log.Info(ctx, "update bot webhook", "old", webhook.URL, "new", u.String())
if _, err := bot.client.SetWebhook(tgbotapi.WebhookConfig{
URL: u,
MaxConnections: 40,
}); err != nil {
return errors.Wrap(err, "update webhook")
}
}
return nil
}
func (bot *Bot) initHandler() {
authMiddleware := newAuthMiddleware(bot.authSrv)
handler := authMiddleware(tg.HandlerFunc(bot.onUpdate))
bot.handler = handler
}
var (
cbqDocumentRefresh = regexp.MustCompile(`^document:(\d+):refresh$`)
cbqDocumentDelete = regexp.MustCompile(`^document:(\d+):delete$`)
cbqDocumentDeleteConfirm = regexp.MustCompile(`^document:(\d+):delete:confirm$`)
)
func (bot *Bot) onUpdate(ctx context.Context, update *tgbotapi.Update) error {
// spew.Dump(update)
// handle message
if msg := update.Message; msg != nil {
go func() {
if _, err := bot.client.Send(tgbotapi.NewChatAction(msg.Chat.ID, tgbotapi.ChatTyping)); err != nil {
log.Warn(ctx, "cant send typing", "err", err)
}
}()
// handle command
switch msg.Command() {
case "start":
return bot.onStart(ctx, msg)
case "help":
return bot.onHelp(ctx, msg)
case "admin":
return bot.onAdmin(ctx, msg)
}
// handle other
if msg.Document != nil {
return bot.onDocument(ctx, msg)
} else {
return bot.onNotDocument(ctx, msg)
}
}
// handle callback queries
if cbq := update.CallbackQuery; cbq != nil {
data := cbq.Data
switch {
case len(cbqDocumentRefresh.FindStringIndex(data)) > 0:
result := cbqDocumentRefresh.FindStringSubmatch(data)
id, err := strconv.Atoi(result[1])
if err != nil {
return errors.Wrap(err, "parse cbq data")
}
return bot.onDocumentRefreshCBQ(ctx, cbq, id)
case len(cbqDocumentDelete.FindStringIndex(data)) > 0:
result := cbqDocumentDelete.FindStringSubmatch(data)
id, err := strconv.Atoi(result[1])
if err != nil {
return errors.Wrap(err, "parse cbq data")
}
return bot.onDocumentDeleteCBQ(ctx, cbq, id)
case len(cbqDocumentDeleteConfirm.FindStringIndex(data)) > 0:
result := cbqDocumentDeleteConfirm.FindStringSubmatch(data)
id, err := strconv.Atoi(result[1])
if err != nil {
return errors.Wrap(err, "parse cbq data")
}
return bot.onDocumentDeleteConfirmCBQ(ctx, cbq, id)
}
}
return nil
}
func (bot *Bot) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ip := realip.FromRequest(r)
if !isTelegramIP(ip) {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx := r.Context()
update := &tgbotapi.Update{}
// parse update
if err := json.NewDecoder(r.Body).Decode(update); err != nil {
http.Error(w, fmt.Sprintf("invalid payload: %v", err), http.StatusBadRequest)
return
}
// handle update
if err := bot.handler.HandleUpdate(ctx, update); err != nil {
log.Error(ctx, "handle update failed", "update_id", update.UpdateID, "err", err)
return
}
}
|
package perf
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/ghodss/yaml"
"github.com/gofrs/uuid"
"github.com/layer5io/meshery/mesheryctl/internal/cli/root/config"
"github.com/layer5io/meshery/mesheryctl/internal/cli/root/constants"
"github.com/layer5io/meshery/mesheryctl/pkg/utils"
"github.com/layer5io/meshery/models"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type profileStruct struct {
Name string
ID *uuid.UUID
Endpoints []string
QPS int
Duration string
Loadgenerators []string
}
type resultStruct struct {
Name string
StartTime *time.Time
LatenciesMs *models.LatenciesMs
QPS int
URL string
UserID *uuid.UUID
Duration int
MesheryID *uuid.UUID
LoadGenerator string
}
var viewCmd = &cobra.Command{
Use: "view",
Short: "view perf profile",
Long: `See the configuration of your performance profile`,
Example: `
View performance profile with
mesheryctl perf view <profile-name>
View performance results with
mesheryctl perf view <profile-id> <test-name>
`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// set default tokenpath for command.
if tokenPath == "" {
tokenPath = constants.GetCurrentAuthToken()
}
mctlCfg, err := config.GetMesheryCtl(viper.GetViper())
if err != nil {
return errors.Wrap(err, "error processing config")
}
if len(args) == 2 {
return viewResults(args, mctlCfg)
}
proName := args[0]
var req *http.Request
url := mctlCfg.GetBaseMesheryURL() + "/api/user/performance/profiles?page_size=25&search=" + proName
var response *models.PerformanceProfilePage
req, err = http.NewRequest("GET", url, nil)
if err != nil {
return errors.Wrapf(err, utils.PerfError("Failed to invoke performance test"))
}
err = utils.AddAuthDetails(req, tokenPath)
if err != nil {
return errors.New("authentication token not found. please supply a valid user token with the --token (or -t) flag")
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.Errorf("Performance profile `%s` not found. Please verify profile name and try again. Use `mesheryctl perf list` to see a list of performance profiles.", proName)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, utils.PerfError("failed to read response body"))
}
if err = json.Unmarshal(data, &response); err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
var a profileStruct
if response.TotalCount == 0 {
return errors.New("profile does not exit. Please get a profile name and try again. Use `mesheryctl perf list` to see a list of performance profiles")
}
for _, profile := range response.Profiles {
if response.Profiles == nil {
return errors.New("profile name not provide. Please get a profile name and try again. Use `mesheryctl perf list` to see a list of performance profiles")
}
a = profileStruct{
Name: profile.Name,
ID: profile.ID,
Endpoints: profile.Endpoints,
QPS: profile.QPS,
Duration: profile.Duration,
Loadgenerators: profile.LoadGenerators,
}
data, err = json.MarshalIndent(&profile, "", " ")
if err != nil {
return err
}
if outputFormatFlag == "yaml" {
data, err = yaml.JSONToYAML(data)
if err != nil {
return errors.Wrap(err, "failed to convert json to yaml")
}
} else if outputFormatFlag == "" {
fmt.Printf("Name: %v\n", a.Name)
fmt.Printf("ID: %s\n", a.ID.String())
fmt.Printf("Endpoint: %v\n", a.Endpoints[0])
fmt.Printf("Load Generators: %v\n", a.Loadgenerators[0])
fmt.Printf("Test run duration: %v\n", a.Duration)
fmt.Println("#####################")
continue
} else if outputFormatFlag != "json" {
return errors.New("output-format not supported, use [json|yaml]")
}
log.Info(string(data))
}
return nil
},
}
func viewResults(args []string, mctlCfg *config.MesheryCtlConfig) error {
profileID := args[0]
testName := args[1]
var req *http.Request
var response *models.PerformanceResultsAPIResponse
url := mctlCfg.GetBaseMesheryURL() + "/api/user/performance/profiles/" + profileID + "/results?pageSize=25&search=" + testName
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return errors.Wrapf(err, utils.PerfError("Failed to invoke performance test"))
}
err = utils.AddAuthDetails(req, tokenPath)
if err != nil {
return errors.New("authentication token not found. please supply a valid user token with the --token (or -t) flag")
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.Errorf("Profile id `%s` is invalid. Please verify profile-id and try again. Use `mesheryctl perf list` to see a list of performance profiles.", profileID)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, utils.PerfError("failed to read response body"))
}
if err = json.Unmarshal(data, &response); err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
var a resultStruct
if response.TotalCount == 0 {
return errors.New("results does not exit. Please run a profile test and try again. Use `mesheryctl perf list` to see a list of performance profiles")
}
for _, result := range response.Results {
if response.Results == nil {
return errors.New("profile name not provide. Please get a profile name and try again. Use `mesheryctl perf list` to see a list of performance profiles")
}
a = resultStruct{
Name: result.Name,
UserID: result.UserID,
URL: result.RunnerResults.URL,
QPS: int(result.RunnerResults.QPS),
Duration: int(result.RunnerResults.Duration),
LatenciesMs: &models.LatenciesMs{
Average: result.RunnerResults.DurationHistogram.Average,
Max: result.RunnerResults.DurationHistogram.Max,
Min: result.RunnerResults.DurationHistogram.Min,
P50: result.RunnerResults.DurationHistogram.Percentiles[0].Value,
P90: result.RunnerResults.DurationHistogram.Percentiles[2].Value,
P99: result.RunnerResults.DurationHistogram.Percentiles[3].Value,
},
StartTime: result.TestStartTime,
MesheryID: result.MesheryID,
LoadGenerator: result.RunnerResults.LoadGenerator,
}
data, err = json.MarshalIndent(&result, "", " ")
if err != nil {
return err
}
if outputFormatFlag == "yaml" {
data, err = yaml.JSONToYAML(data)
if err != nil {
return errors.Wrap(err, "failed to convert json to yaml")
}
} else if outputFormatFlag == "" {
fmt.Printf("Name: %v\n", a.Name)
fmt.Printf("UserID: %s\n", a.UserID.String())
fmt.Printf("Endpoint: %v\n", a.URL)
fmt.Printf("QPS: %v\n", a.QPS)
fmt.Printf("Test run duration: %v\n", a.Duration)
fmt.Printf("Latencies _ms: Avg: %v, Max: %v, Min: %v, P50: %v, P90: %v, P99: %v\n", a.LatenciesMs.Average, a.LatenciesMs.Max, a.LatenciesMs.Min, a.LatenciesMs.P50, a.LatenciesMs.P90, a.LatenciesMs.P99)
fmt.Printf("Start Time: %v\n", fmt.Sprintf("%d-%d-%d %d:%d:%d", int(a.StartTime.Month()), a.StartTime.Day(), a.StartTime.Year(), a.StartTime.Hour(), a.StartTime.Minute(), a.StartTime.Second()))
fmt.Printf("Meshery ID: %v\n", a.MesheryID.String())
fmt.Printf("Load Generator: %v\n", a.LoadGenerator)
fmt.Println("#####################")
continue
} else if outputFormatFlag != "json" {
return errors.New("output-format not supported, use [json|yaml]")
}
log.Info(string(data))
}
return nil
}
|
package client
import (
"encoding/json"
"net"
)
const (
EOL = "\n"
)
type Client interface {
Connect() error
Disconnect() error
Authorizate() error
TankCommand(message Message) error
SendMessage(message Message) error
ReadMessage() (Message, error)
ReadType(string) (Message, error)
ReadWorld() (Message, error)
ReadTank() (TankMessage, error)
}
type client struct {
ServerAddr string
Login string
Password string
connection *net.TCPConn
jsonDec *json.Decoder
}
func NewClient(login, pass, serverAddr string) Client {
return &client{
ServerAddr: serverAddr,
Login: login,
Password: pass,
}
}
func (c *client) Connect() error {
addr, err := net.ResolveTCPAddr("tcp", c.ServerAddr)
if err != nil {
return err
}
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
return err
}
c.connection = conn
c.jsonDec = json.NewDecoder(c.connection)
return nil
}
func (c *client) Disconnect() error {
return c.connection.Close()
}
func (c *client) Authorizate() error {
message := NewAuthMessage(c.Login, c.Password)
err := c.SendMessage(message)
return err
}
func (c *client) TankCommand(message Message) error {
message["Type"] = "TankCommand"
err := c.SendMessage(message)
return err
}
func (c *client) ReadMessage() (Message, error) {
var m Message
if err := c.jsonDec.Decode(&m); err != nil {
return nil, err
}
return m, nil
}
func (c *client) ReadType(typeStr string) (Message, error) {
for {
m, err := c.ReadMessage()
if err != nil {
return nil, err
}
if m["Type"] == typeStr {
return m, nil
}
}
}
func (c *client) ReadWorld() (Message, error) {
message, err := c.ReadType("World")
if err != nil {
return nil, err
}
return message, nil
}
func (c *client) ReadTank() (TankMessage, error) {
message, err := c.ReadType("Tank")
if err != nil {
return nil, err
}
return TankMessage(message), nil
}
func (c *client) SendMessage(message Message) error {
jsonStr, err := json.Marshal(message)
if err != nil {
return err
}
jsonStr = append(jsonStr, []byte(EOL)...)
for len(jsonStr) > 0 {
n, err := c.connection.Write(jsonStr)
if err != nil {
return err
}
jsonStr = jsonStr[n:]
}
return nil
}
|
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package consensus
import (
"bytes"
"errors"
"time"
"github.com/dusk-network/dusk-blockchain/pkg/config"
cfg "github.com/dusk-network/dusk-blockchain/pkg/config"
"github.com/dusk-network/dusk-blockchain/pkg/core/consensus/header"
"github.com/dusk-network/dusk-blockchain/pkg/core/consensus/key"
"github.com/dusk-network/dusk-blockchain/pkg/core/consensus/user"
"github.com/dusk-network/dusk-blockchain/pkg/core/data/block"
"github.com/dusk-network/dusk-blockchain/pkg/core/data/ipc/transactions"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/message"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/message/payload"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/topics"
"github.com/dusk-network/dusk-blockchain/pkg/util/nativeutils/eventbus"
"github.com/dusk-network/dusk-blockchain/pkg/util/nativeutils/rpcbus"
"github.com/dusk-network/dusk-crypto/bls"
)
type (
// Results carries the eventual consensus results.
Results struct {
Blk block.Block
Err error
}
// CandidateVerificationFunc is a callback used to verify candidate blocks
// after the conclusion of the first reduction step.
CandidateVerificationFunc func(block.Block) error
// Emitter is a simple struct to pass the communication channels that the steps should be
// able to emit onto.
Emitter struct {
EventBus *eventbus.EventBus
RPCBus *rpcbus.RPCBus
Keys key.Keys
Proxy transactions.Proxy
TimerLength time.Duration
}
// RoundUpdate carries the data about the new Round, such as the active
// Provisioners, the BidList, the Seed and the Hash.
RoundUpdate struct {
Round uint64
P user.Provisioners
Seed []byte
Hash []byte
LastCertificate *block.Certificate
}
// InternalPacket is a specialization of the Payload of message.Message. It is used to
// unify messages used by the consensus, which need to carry the header.Header
// for consensus specific operations.
InternalPacket interface {
payload.Safe
State() header.Header
}
)
// Copy complies with message.Safe interface. It returns a deep copy of
// the message safe to publish to multiple subscribers.
func (r RoundUpdate) Copy() payload.Safe {
ru := RoundUpdate{
Round: r.Round,
P: r.P.Copy(),
Seed: make([]byte, len(r.Seed)),
Hash: make([]byte, len(r.Hash)),
LastCertificate: r.LastCertificate.Copy(),
}
copy(ru.Seed, r.Seed)
copy(ru.Hash, r.Hash)
return ru
}
type (
acceptedBlockCollector struct {
blockChan chan<- block.Block
}
)
// InitAcceptedBlockUpdate init listener to get updates about lastly accepted block in the chain.
func InitAcceptedBlockUpdate(subscriber eventbus.Subscriber) (chan block.Block, uint32) {
acceptedBlockChan := make(chan block.Block, cfg.MaxInvBlocks)
collector := &acceptedBlockCollector{acceptedBlockChan}
collectListener := eventbus.NewSafeCallbackListener(collector.Collect)
id := subscriber.Subscribe(topics.AcceptedBlock, collectListener)
return acceptedBlockChan, id
}
// Collect as defined in the EventCollector interface. It reconstructs the bidList and notifies about it.
func (c *acceptedBlockCollector) Collect(m message.Message) {
c.blockChan <- m.Payload().(block.Block)
}
// Sign a header.
func (e *Emitter) Sign(h header.Header) ([]byte, error) {
preimage := new(bytes.Buffer)
if err := header.MarshalSignableVote(preimage, h); err != nil {
return nil, err
}
signedHash, err := bls.Sign(e.Keys.BLSSecretKey, e.Keys.BLSPubKey, preimage.Bytes())
if err != nil {
return nil, err
}
return signedHash.Compress(), nil
}
// Gossip concatenates the topic, the header and the payload,
// and gossips it to the rest of the network.
func (e *Emitter) Gossip(msg message.Message) error {
// message.Marshal takes care of prepending the topic, marshaling the
// header, etc
buf, err := message.Marshal(msg)
if err != nil {
return err
}
serialized := message.New(msg.Category(), buf)
// gossip away
_ = e.EventBus.Publish(topics.Gossip, serialized)
return nil
}
// Kadcast propagates a message in Kadcast network.
func (e *Emitter) Kadcast(msg message.Message, h byte) error {
buf, err := message.Marshal(msg)
if err != nil {
return err
}
serialized := message.NewWithHeader(msg.Category(), buf, []byte{h})
e.EventBus.Publish(topics.Kadcast, serialized)
return nil
}
// Republish reroutes message propagation to either Gossip or Kadcast network.
func (e *Emitter) Republish(msg message.Message, header []byte) error {
if config.Get().Kadcast.Enabled {
if len(header) > 0 && header[0] <= config.KadcastInitialHeight {
h := header[0]
return e.Kadcast(msg, h)
}
return errors.New("unknown kadcast height")
}
return e.Gossip(msg)
}
|
package version
import (
"fmt"
"runtime"
)
// The current version of remote-structure-test
// This is a private field and is set through a compilation flag from the Makefile
var version = "v0.0.0-unset"
var buildDate string
var platform = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
type Info struct {
Version string
GitVersion string
BuildDate string
GoVersion string
Compiler string
Platform string
}
// Get returns the version and buildtime information about the binary
func GetVersion() *Info {
// These variables typically come from -ldflags settings to `go build`
return &Info{
Version: version,
BuildDate: buildDate,
GoVersion: runtime.Version(),
Compiler: runtime.Compiler,
Platform: platform,
}
}
|
package main
import "fmt"
func main() {
fmt.Println(myPow(244, 3243))
}
func Pow(x float64, n int) float64 {
return myPow(x, n)
}
func myPow(x float64, n int) float64 {
if n == 0 {
return 1
}
if n%2 == 0 {
return myPow(x*x, n>>1)
} else {
return myPow(x, n-1) * x
}
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package provisioner
import (
"context"
"fmt"
"strings"
"time"
"github.com/mattermost/mattermost-cloud/k8s"
"github.com/mattermost/mattermost-cloud/model"
"github.com/mattermost/mattermost-operator/pkg/resources"
"github.com/pborman/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes/scheme"
)
const (
ciExecJobTTLSeconds int32 = 180
)
// ExecMMCTL runs the given MMCTL command against the given cluster installation.
// Setup and exec errors both result in a single return error.
func (provisioner Provisioner) ExecMMCTL(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) ([]byte, error) {
output, execErr, err := provisioner.ExecClusterInstallationCLI(cluster, clusterInstallation, append([]string{"./bin/mmctl"}, args...)...)
if err != nil {
return output, errors.Wrap(err, "failed to run mmctl command")
}
if execErr != nil {
return output, errors.Wrap(execErr, "mmctl command encountered an error")
}
return output, nil
}
// ExecClusterInstallationCLI execs the provided command on the defined cluster
// installation and returns both exec preparation errors as well as errors from
// the exec command itself.
func (provisioner Provisioner) ExecClusterInstallationCLI(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) ([]byte, error, error) {
logger := provisioner.logger.WithFields(log.Fields{
"cluster": clusterInstallation.ClusterID,
"installation": clusterInstallation.InstallationID,
})
k8sClient, err := provisioner.k8sClient(cluster)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to get kube client")
}
return execClusterInstallationCLI(k8sClient, clusterInstallation, logger, args...)
}
// ExecMattermostCLI invokes the Mattermost CLI for the given cluster installation
// with the given args. Setup and exec errors both result in a single return error.
func (provisioner Provisioner) ExecMattermostCLI(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) ([]byte, error) {
output, execErr, err := provisioner.ExecClusterInstallationCLI(cluster, clusterInstallation, append([]string{"./bin/mattermost"}, args...)...)
if err != nil {
return output, errors.Wrap(err, "failed to run mattermost command")
}
if execErr != nil {
return output, errors.Wrap(execErr, "mattermost command encountered an error")
}
return output, nil
}
// ExecClusterInstallationJob creates job executing command on cluster installation.
func (provisioner Provisioner) ExecClusterInstallationJob(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) error {
logger := provisioner.logger.WithFields(log.Fields{
"cluster": clusterInstallation.ClusterID,
"installation": clusterInstallation.InstallationID,
})
logger.Info("Executing job with CLI command on cluster installation")
k8sClient, err := provisioner.k8sClient(cluster)
if err != nil {
return errors.Wrap(err, "failed to get kube client")
}
ctx := context.TODO()
deploymentList, err := k8sClient.Clientset.AppsV1().Deployments(clusterInstallation.Namespace).List(ctx, metav1.ListOptions{
LabelSelector: "app=mattermost",
})
if err != nil {
return errors.Wrap(err, "failed to get installation deployments")
}
if len(deploymentList.Items) == 0 {
return errors.New("no mattermost deployments found")
}
jobName := fmt.Sprintf("command-%s", uuid.New()[:6])
job := resources.PrepareMattermostJobTemplate(jobName, clusterInstallation.Namespace, &deploymentList.Items[0], nil)
// TODO: refactor above method in Mattermost Operator to take command and handle this logic inside.
for i := range job.Spec.Template.Spec.Containers {
job.Spec.Template.Spec.Containers[i].Command = args
// We want to match bifrost network policy so that server can come up quicker.
job.Spec.Template.Labels["app"] = "mattermost"
}
jobTTL := ciExecJobTTLSeconds
job.Spec.TTLSecondsAfterFinished = &jobTTL
jobsClient := k8sClient.Clientset.BatchV1().Jobs(clusterInstallation.Namespace)
defer func() {
errDefer := jobsClient.Delete(ctx, jobName, metav1.DeleteOptions{})
if errDefer != nil && !k8sErrors.IsNotFound(errDefer) {
logger.Errorf("Failed to cleanup exec job: %q", jobName)
}
}()
job, err = jobsClient.Create(ctx, job, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create CLI command job")
}
err = wait.Poll(time.Second, 10*time.Minute, func() (done bool, err error) {
job, err = jobsClient.Get(ctx, jobName, metav1.GetOptions{})
if err != nil {
return false, errors.Wrapf(err, "failed to get %q job", jobName)
}
if job.Status.Succeeded < 1 {
logger.Infof("job %q not yet finished, waiting up to 10 minute", jobName)
return false, nil
}
return true, nil
})
if err != nil {
return errors.Wrapf(err, "job %q did not finish in expected time", jobName)
}
return nil
}
func execClusterInstallationCLI(k8sClient *k8s.KubeClient, clusterInstallation *model.ClusterInstallation, logger log.FieldLogger, args ...string) ([]byte, error, error) {
ctx := context.TODO()
podList, err := k8sClient.Clientset.CoreV1().Pods(clusterInstallation.Namespace).List(ctx, metav1.ListOptions{
LabelSelector: "app=mattermost",
FieldSelector: "status.phase=Running",
})
if err != nil {
return nil, nil, errors.Wrap(err, "failed to query mattermost pods")
}
// In the future, we'd ideally just spin our own container on demand, allowing
// configuration changes even if the pods are failing to start the server. For now,
// we find the first pod running Mattermost, and pick the first container therein.
if len(podList.Items) == 0 {
return nil, nil, errors.New("failed to find mattermost pods on which to exec")
}
pod := podList.Items[0]
if len(pod.Spec.Containers) == 0 {
return nil, nil, errors.Errorf("failed to find containers in pod %s", pod.Name)
}
container := pod.Spec.Containers[0]
logger.Debugf("Executing `%s` on pod %s: container=%s, image=%s, phase=%s", strings.Join(args, " "), pod.Name, container.Name, container.Image, pod.Status.Phase)
now := time.Now()
output, execErr := execCLI(k8sClient, clusterInstallation.Namespace, pod.Name, container.Name, args...)
if execErr != nil {
logger.WithError(execErr).Warnf("Command `%s` on pod %s finished in %.0f seconds, but encountered an error", strings.Join(args, " "), pod.Name, time.Since(now).Seconds())
} else {
logger.Debugf("Command `%s` on pod %s finished in %.0f seconds", strings.Join(args, " "), pod.Name, time.Since(now).Seconds())
}
return output, execErr, nil
}
func execCLI(k8sClient *k8s.KubeClient, namespace, podName, containerName string, args ...string) ([]byte, error) {
execRequest := k8sClient.Clientset.CoreV1().RESTClient().Post().
Resource("pods").
Name(podName).
Namespace(namespace).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: args,
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
return k8sClient.RemoteCommand("POST", execRequest.URL())
}
|
package main
import (
"fmt"
"github.com/Snaxai/IS105/ICA02/Oppg3/unicode"
)
func main() {
unicode.SkrivUT()
fmt.Println()
unicode.SkrivUTx()
fmt.Println()
unicode.Printunicode()
fmt.Println()
unicode.SkrivUTotherunicode()
}
|
package Next_Permutation
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNextPermutation(t *testing.T) {
ast := assert.New(t)
case0 := []int{1, 1}
nextPermutation(case0)
ast.Equal([]int{1, 1}, case0)
case1 := []int{1, 2, 3}
nextPermutation(case1)
ast.Equal([]int{1, 3, 2}, case1)
case2 := []int{1}
nextPermutation(case2)
ast.Equal([]int{1}, case2)
case3 := []int{}
nextPermutation(case3)
ast.Equal([]int{}, case3)
case4 := []int{1, 1, 5}
nextPermutation(case4)
ast.Equal([]int{1, 5, 1}, case4)
case5 := []int{1, 2, 5, 4, 3, 2, 1}
nextPermutation(case5)
ast.Equal([]int{1, 3, 1, 2, 2, 4, 5}, case5)
}
|
package main
import (
"sort"
"strconv"
"strings"
"github.com/innermond/pak"
)
func boxesFromString(dimensions []string, extra float64) (boxes []*pak.Box) {
for _, dd := range dimensions {
d := strings.Split(dd, "x")
if len(d) == 2 {
d = append(d, "1", "1") // repeat 1 time
} else if len(d) == 3 {
d = append(d, "1") // can rotate
}
w, err := strconv.ParseFloat(d[0], 64)
if err != nil {
panic(err)
}
h, err := strconv.ParseFloat(d[1], 64)
if err != nil {
panic(err)
}
n, err := strconv.Atoi(d[2])
if err != nil {
panic(err)
}
r, err := strconv.ParseBool(d[3])
if err != nil {
panic(err)
}
for n != 0 {
boxes = append(boxes, &pak.Box{W: w + extra, H: h + extra, CanRotate: r})
n--
}
// sort descending by area
sort.Slice(boxes, func(i, j int) bool {
return boxes[i].W*boxes[i].H > boxes[j].W*boxes[j].H
})
}
return
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// http server
func main(){
http.HandleFunc("/",f1)
http.HandleFunc("/api",f2)
http.ListenAndServe("127.0.0.1:9091",nil)
// http.ListenAndServe("0.0.0.0:9091",nil) //上服务器时写
}
func f2(w http.ResponseWriter,reve *http.Request){
receContent := reve.URL.Query()
fmt.Println(receContent) //get 在这里 收取
// 根据请求body创建一个json解析器实例
decoder := json.NewDecoder(reve.Body) //post 在这里 收取
fmt.Println(decoder)
// 处理逻辑
// 返回数据
// str := `get it xxxx `
// w.Write( []byte(str) )
}
func f1(w http.ResponseWriter,r *http.Request){
// str := `<h1 style="color:red">hello kelvin</h1>`
// w.Write( []byte(str) )
b,err:=ioutil.ReadFile("./templete/index.html")
if err!=nil{
fmt.Println("read file fail ,err",err)
w.Write( []byte( fmt.Sprintf("%v",err) ) )
}
w.Write( b )
} |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package model
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var nilHuv *HelmUtilityVersion // provides a typed nil; never initialize this
func TestSetUtilityVersion(t *testing.T) {
u := &UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: ""},
Nginx: &HelmUtilityVersion{Chart: ""},
Fluentbit: &HelmUtilityVersion{Chart: ""},
}
setUtilityVersion(u, NginxCanonicalName, &HelmUtilityVersion{Chart: "0.9"})
assert.Equal(t, &HelmUtilityVersion{Chart: "0.9"}, u.Nginx)
setUtilityVersion(u, "an_error", &HelmUtilityVersion{Chart: "9"})
assert.Equal(t, &HelmUtilityVersion{Chart: "0.9"}, u.Nginx)
}
func TestGetUtilityVersion(t *testing.T) {
u := UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: "3"},
Thanos: &HelmUtilityVersion{Chart: "4"},
Nginx: &HelmUtilityVersion{Chart: "5"},
Fluentbit: &HelmUtilityVersion{Chart: "6"},
NodeProblemDetector: &HelmUtilityVersion{Chart: "7"},
MetricsServer: &HelmUtilityVersion{Chart: "8"},
Velero: &HelmUtilityVersion{Chart: "9"},
Cloudprober: &HelmUtilityVersion{Chart: "10"},
}
assert.Equal(t, &HelmUtilityVersion{Chart: "3"}, getUtilityVersion(u, PrometheusOperatorCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "4"}, getUtilityVersion(u, ThanosCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "5"}, getUtilityVersion(u, NginxCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "6"}, getUtilityVersion(u, FluentbitCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "7"}, getUtilityVersion(u, NodeProblemDetectorCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "8"}, getUtilityVersion(u, MetricsServerCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "9"}, getUtilityVersion(u, VeleroCanonicalName))
assert.Equal(t, &HelmUtilityVersion{Chart: "10"}, getUtilityVersion(u, CloudproberCanonicalName))
assert.Equal(t, nilHuv, getUtilityVersion(u, "anything else"))
}
func TestSetActualVersion(t *testing.T) {
c := &Cluster{}
assert.Nil(t, c.UtilityMetadata)
err := c.SetUtilityActualVersion(NginxCanonicalName, &HelmUtilityVersion{Chart: "1.9.9"})
require.NoError(t, err)
assert.NotNil(t, c.UtilityMetadata)
version := c.ActualUtilityVersion(NginxCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "1.9.9"}, version)
}
func TestSetDesired(t *testing.T) {
for _, testCase := range []struct {
description string
currentMetadata *UtilityMetadata
desiredVersions map[string]*HelmUtilityVersion
expectedDesiredVersions UtilityGroupVersions
}{
{
description: "set desired utility without actual",
currentMetadata: nil,
desiredVersions: map[string]*HelmUtilityVersion{
NginxCanonicalName: {Chart: "1.9.9", ValuesPath: "vals"},
},
expectedDesiredVersions: UtilityGroupVersions{
Nginx: &HelmUtilityVersion{Chart: "1.9.9", ValuesPath: "vals"},
},
},
{
description: "set single desired utility, don't inherit from actual",
currentMetadata: &UtilityMetadata{
ActualVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{ValuesPath: "prom", Chart: "1.0.0"},
Nginx: &HelmUtilityVersion{ValuesPath: "nginx", Chart: "2.0.0"},
},
},
desiredVersions: map[string]*HelmUtilityVersion{
NginxCanonicalName: {Chart: "3.0.0", ValuesPath: "nginx"},
},
expectedDesiredVersions: UtilityGroupVersions{
Nginx: &HelmUtilityVersion{ValuesPath: "nginx", Chart: "3.0.0"},
},
},
{
description: "use all actual to override current desired",
currentMetadata: &UtilityMetadata{
ActualVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{ValuesPath: "prom", Chart: "1.0.0"},
Nginx: &HelmUtilityVersion{ValuesPath: "nginx", Chart: "2.0.0"},
Teleport: &HelmUtilityVersion{ValuesPath: "teleport-kube-agent", Chart: "5.0.0"},
},
DesiredVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{ValuesPath: "desired-prometheus", Chart: "0.1"},
Nginx: &HelmUtilityVersion{ValuesPath: "desired-nginx", Chart: "120.0.0"},
Teleport: &HelmUtilityVersion{ValuesPath: "desired-teleport-kube-agent", Chart: "15.0.0"},
},
},
desiredVersions: nil,
expectedDesiredVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{ValuesPath: "desired-prometheus", Chart: "0.1"},
Nginx: &HelmUtilityVersion{ValuesPath: "desired-nginx", Chart: "120.0.0"},
Teleport: &HelmUtilityVersion{ValuesPath: "desired-teleport-kube-agent", Chart: "15.0.0"},
},
},
} {
t.Run(testCase.description, func(t *testing.T) {
c := &Cluster{
UtilityMetadata: testCase.currentMetadata,
}
c.SetUtilityDesiredVersions(testCase.desiredVersions)
assert.Equal(t, testCase.expectedDesiredVersions, c.UtilityMetadata.DesiredVersions)
})
}
}
func TestGetActualVersion(t *testing.T) {
c := &Cluster{
UtilityMetadata: &UtilityMetadata{
DesiredVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: ""},
Thanos: &HelmUtilityVersion{Chart: ""},
Nginx: &HelmUtilityVersion{Chart: "10.3"},
Fluentbit: &HelmUtilityVersion{Chart: "1337"},
Teleport: &HelmUtilityVersion{Chart: "12345"},
Pgbouncer: &HelmUtilityVersion{Chart: "123456"},
Promtail: &HelmUtilityVersion{Chart: "123456"},
Rtcd: &HelmUtilityVersion{Chart: "123456"},
NodeProblemDetector: &HelmUtilityVersion{Chart: "123456789"},
MetricsServer: &HelmUtilityVersion{Chart: "1234567899"},
Velero: &HelmUtilityVersion{Chart: "12345678910"},
Cloudprober: &HelmUtilityVersion{Chart: "123456789101"},
},
ActualVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: "kube-prometheus-stack-9.4"},
Thanos: &HelmUtilityVersion{Chart: "thanos-2.4"},
Nginx: &HelmUtilityVersion{Chart: "nginx-10.2"},
Fluentbit: &HelmUtilityVersion{Chart: "fluent-bit-0.9"},
Teleport: &HelmUtilityVersion{Chart: "teleport-kube-agent-7.3.26"},
Pgbouncer: &HelmUtilityVersion{Chart: "pgbouncer-1.2.1"},
Promtail: &HelmUtilityVersion{Chart: "promtail-6.2.2"},
Rtcd: &HelmUtilityVersion{Chart: "rtcd-1.3.0"},
NodeProblemDetector: &HelmUtilityVersion{Chart: "node-problem-detector-2.3.5"},
MetricsServer: &HelmUtilityVersion{Chart: "metrics-server-3.10.0"},
Velero: &HelmUtilityVersion{Chart: "velero-3.1.2"},
Cloudprober: &HelmUtilityVersion{Chart: "cloudprober-0.1.3"},
},
},
}
version := c.ActualUtilityVersion(PrometheusOperatorCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "kube-prometheus-stack-9.4"}, version)
version = c.ActualUtilityVersion(ThanosCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "thanos-2.4"}, version)
version = c.ActualUtilityVersion(NginxCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "nginx-10.2"}, version)
version = c.ActualUtilityVersion(FluentbitCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "fluent-bit-0.9"}, version)
version = c.ActualUtilityVersion(TeleportCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "teleport-kube-agent-7.3.26"}, version)
version = c.ActualUtilityVersion(PgbouncerCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "pgbouncer-1.2.1"}, version)
version = c.ActualUtilityVersion(PromtailCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "promtail-6.2.2"}, version)
version = c.ActualUtilityVersion(RtcdCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "rtcd-1.3.0"}, version)
version = c.ActualUtilityVersion(NodeProblemDetectorCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "node-problem-detector-2.3.5"}, version)
version = c.ActualUtilityVersion(MetricsServerCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "metrics-server-3.10.0"}, version)
version = c.ActualUtilityVersion(VeleroCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "velero-3.1.2"}, version)
version = c.ActualUtilityVersion(CloudproberCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "cloudprober-0.1.3"}, version)
version = c.ActualUtilityVersion("something else that doesn't exist")
assert.Equal(t, version, nilHuv)
}
func TestGetDesiredVersion(t *testing.T) {
c := &Cluster{
UtilityMetadata: &UtilityMetadata{
DesiredVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: ""},
Thanos: &HelmUtilityVersion{Chart: ""},
Nginx: &HelmUtilityVersion{Chart: "10.3"},
Fluentbit: &HelmUtilityVersion{Chart: "1337"},
Teleport: &HelmUtilityVersion{Chart: "12345"},
Pgbouncer: &HelmUtilityVersion{Chart: "123456"},
Promtail: &HelmUtilityVersion{Chart: "123456"},
Rtcd: &HelmUtilityVersion{Chart: "123456"},
NodeProblemDetector: &HelmUtilityVersion{Chart: "123456789"},
MetricsServer: &HelmUtilityVersion{Chart: "1234567899"},
Velero: &HelmUtilityVersion{Chart: "12345678910"},
Cloudprober: &HelmUtilityVersion{Chart: "123456789101"},
},
ActualVersions: UtilityGroupVersions{
PrometheusOperator: &HelmUtilityVersion{Chart: "kube-prometheus-stack-9.4"},
Thanos: &HelmUtilityVersion{Chart: "thanos-2.4"},
Nginx: &HelmUtilityVersion{Chart: "nginx-10.2"},
Fluentbit: &HelmUtilityVersion{Chart: "fluent-bit-0.9"},
Teleport: &HelmUtilityVersion{Chart: "teleport-kube-agent-7.3.26"},
Pgbouncer: &HelmUtilityVersion{Chart: "pgbouncer-1.2.1"},
Promtail: &HelmUtilityVersion{Chart: "promtail-6.2.2"},
Rtcd: &HelmUtilityVersion{Chart: "rtcd-1.3.0"},
NodeProblemDetector: &HelmUtilityVersion{Chart: "node-problem-detector-2.3.5"},
MetricsServer: &HelmUtilityVersion{Chart: "metrics-server-3.10.0"},
Velero: &HelmUtilityVersion{Chart: "velero-3.1.2"},
Cloudprober: &HelmUtilityVersion{Chart: "cloudprober-0.1.3"},
},
},
}
version := c.DesiredUtilityVersion(PrometheusOperatorCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: ""}, version)
version = c.DesiredUtilityVersion(ThanosCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: ""}, version)
version = c.DesiredUtilityVersion(NginxCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "10.3"}, version)
version = c.DesiredUtilityVersion(FluentbitCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "1337"}, version)
version = c.DesiredUtilityVersion(TeleportCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "12345"}, version)
version = c.DesiredUtilityVersion(PgbouncerCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "123456"}, version)
version = c.DesiredUtilityVersion(PromtailCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "123456"}, version)
version = c.DesiredUtilityVersion(RtcdCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "123456"}, version)
version = c.DesiredUtilityVersion(NodeProblemDetectorCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "123456789"}, version)
version = c.DesiredUtilityVersion(MetricsServerCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "1234567899"}, version)
version = c.DesiredUtilityVersion(VeleroCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "12345678910"}, version)
version = c.DesiredUtilityVersion(CloudproberCanonicalName)
assert.Equal(t, &HelmUtilityVersion{Chart: "123456789101"}, version)
version = c.DesiredUtilityVersion("something else that doesn't exist")
assert.Equal(t, nilHuv, version)
}
func TestUnmarshallUtilityVersion(t *testing.T) {
version := "0.9.0"
t.Run("new format", func(t *testing.T) {
// new format
versions := &UtilityGroupVersions{}
str := `{"nginx":{"chart":"` + version + `"}}`
err := json.Unmarshal([]byte(str), versions)
assert.NoError(t, err)
require.Equal(t, version, versions.Nginx.Chart)
})
t.Run("old format", func(t *testing.T) {
// old format
versions := &UtilityGroupVersions{}
str := `{"nginx":"` + version + `"}`
err := json.Unmarshal([]byte(str), versions)
assert.NoError(t, err)
require.Equal(t, version, versions.Nginx.Chart)
})
t.Run("nil", func(t *testing.T) {
// old format
versions := &UtilityGroupVersions{}
str := `{"nginx":null}`
err := json.Unmarshal([]byte(str), versions)
assert.NoError(t, err)
require.Equal(t, (*HelmUtilityVersion)(nil), versions.Nginx)
})
t.Run("empty object", func(t *testing.T) {
// old format
versions := &UtilityGroupVersions{}
str := `{"nginx":{}}`
err := json.Unmarshal([]byte(str), versions)
assert.NoError(t, err)
require.Equal(t, &HelmUtilityVersion{}, versions.Nginx)
})
t.Run("malformed", func(t *testing.T) {
// old format
versions := &UtilityGroupVersions{}
str := `{"nginx":'}`
err := json.Unmarshal([]byte(str), versions)
assert.Error(t, err, "error unmarshalling HelmUtilityVersion")
require.Equal(t, (*HelmUtilityVersion)(nil), versions.Nginx)
})
}
func TestUtilityIsUnmanaged(t *testing.T) {
tests := []struct {
name string
desired *HelmUtilityVersion
actual *HelmUtilityVersion
unmanaged bool
}{
{"nil, nil", nil, nil, false},
{"nil, not unmanaged", nil, &HelmUtilityVersion{Chart: "v1"}, false},
{"nil, unmanaged", nil, &HelmUtilityVersion{Chart: UnmanagedUtilityVersion}, true},
{"unmanaged, nil", &HelmUtilityVersion{Chart: UnmanagedUtilityVersion}, nil, true},
{"unmanaged, unmanaged",
&HelmUtilityVersion{Chart: UnmanagedUtilityVersion},
&HelmUtilityVersion{Chart: UnmanagedUtilityVersion},
true,
},
{"v1.0.0, unmanaged",
&HelmUtilityVersion{Chart: "v1.0.0"},
&HelmUtilityVersion{Chart: UnmanagedUtilityVersion},
false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.unmanaged, UtilityIsUnmanaged(test.desired, test.actual))
})
}
}
func TestUtilityIsEmpty(t *testing.T) {
tests := []struct {
name string
helm *HelmUtilityVersion
empty bool
}{
{"nil", nil, true},
{"chart unmanaged, values empty", &HelmUtilityVersion{Chart: UnmanagedUtilityVersion}, false},
{"chart unmanaged, values not empty", &HelmUtilityVersion{Chart: UnmanagedUtilityVersion, ValuesPath: "test"}, false},
{"chart empty, values empty", &HelmUtilityVersion{}, true},
{"chart not empty, values empty", &HelmUtilityVersion{Chart: "test"}, true},
{"chart empty, values not empty", &HelmUtilityVersion{ValuesPath: "test"}, true},
{"chart not empty, values not empty", &HelmUtilityVersion{Chart: "test", ValuesPath: "test"}, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.empty, test.helm.IsEmpty())
})
}
}
|
package main
import (
"fmt"
"net"
"net/url"
)
func main() {
u := "http://admin:12345@localhost:8080/eureka?opt=add#k"
uurl, err := url.Parse(u)
defer func() {
if err!=nil{
panic(err)
}
}()
fmt.Printf("%p \n",uurl)
fmt.Println(uurl)
fmt.Println(*uurl)
fmt.Println("-----------------------")
fmt.Println(uurl.Scheme)
fmt.Println(uurl.User)
fmt.Println(uurl.User.Username())
fmt.Println(uurl.User.Password())
fmt.Println(uurl.Host)
fmt.Println(net.SplitHostPort(uurl.Host))
fmt.Println(uurl.Fragment)
fmt.Println(uurl.RawQuery)
//params map
query, err := url.ParseQuery(uurl.RawQuery)
fmt.Println(query)
}
|
package goserver
import (
"errors"
"fmt"
"log"
"sync"
"testing"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
pb "github.com/brotherlogic/discovery/proto"
pbg "github.com/brotherlogic/goserver/proto"
pbd "github.com/brotherlogic/monitor/proto"
)
type basicGetter struct{}
func (hostGetter basicGetter) Hostname() (string, error) {
return "basic", nil
}
type failingGetter struct{}
func (hostGetter failingGetter) Hostname() (string, error) {
return "", errors.New("Built to Fail")
}
type passingDialler struct{}
func (dialler passingDialler) Dial(host string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
return nil, nil
}
type failingDialler struct{}
func (dialler failingDialler) Dial(host string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
return nil, errors.New("Built to fail")
}
type passingDiscoveryServiceClient struct {
upreregister int32
returnWeakMaster bool
returnMaster bool
}
func (DiscoveryServiceClient passingDiscoveryServiceClient) RegisterService(ctx context.Context, in *pb.RegisterRequest, opts ...grpc.CallOption) (*pb.RegisterResponse, error) {
return &pb.RegisterResponse{Service: &pb.RegistryEntry{Port: 35 + DiscoveryServiceClient.upreregister, Identifier: in.GetService().Identifier, WeakMaster: DiscoveryServiceClient.returnWeakMaster, Master: DiscoveryServiceClient.returnMaster}}, nil
}
func (DiscoveryServiceClient passingDiscoveryServiceClient) Discover(ctx context.Context, in *pb.DiscoverRequest, opts ...grpc.CallOption) (*pb.DiscoverResponse, error) {
return &pb.DiscoverResponse{Service: &pb.RegistryEntry{Ip: "10.10.10.10", Port: 23}}, nil
}
func (DiscoveryServiceClient passingDiscoveryServiceClient) ListAllServices(ctx context.Context, in *pb.ListRequest, opts ...grpc.CallOption) (*pb.ListResponse, error) {
return &pb.ListResponse{}, nil
}
func (DiscoveryServiceClient passingDiscoveryServiceClient) State(ctx context.Context, in *pb.StateRequest, opts ...grpc.CallOption) (*pb.StateResponse, error) {
return &pb.StateResponse{}, nil
}
type failPassDiscoveryServiceClient struct {
fails int
}
func (DiscoveryServiceClient failPassDiscoveryServiceClient) RegisterService(ctx context.Context, in *pb.RegisterRequest, opts ...grpc.CallOption) (*pb.RegisterResponse, error) {
return &pb.RegisterResponse{Service: &pb.RegistryEntry{Port: 35, Identifier: in.GetService().Identifier}}, nil
}
func (DiscoveryServiceClient *failPassDiscoveryServiceClient) Discover(ctx context.Context, in *pb.DiscoverRequest, opts ...grpc.CallOption) (*pb.DiscoverResponse, error) {
if DiscoveryServiceClient.fails > 0 {
DiscoveryServiceClient.fails--
return nil, grpc.Errorf(codes.Unavailable, "Made up failure %v", 23)
}
return &pb.DiscoverResponse{Service: &pb.RegistryEntry{Ip: "10.10.10.10", Port: 23}}, nil
}
func (DiscoveryServiceClient failPassDiscoveryServiceClient) ListAllServices(ctx context.Context, in *pb.ListRequest, opts ...grpc.CallOption) (*pb.ListResponse, error) {
return &pb.ListResponse{}, nil
}
func (DiscoveryServiceClient failPassDiscoveryServiceClient) State(ctx context.Context, in *pb.StateRequest, opts ...grpc.CallOption) (*pb.StateResponse, error) {
return &pb.StateResponse{}, nil
}
type failingDiscoveryServiceClient struct{}
func (DiscoveryServiceClient failingDiscoveryServiceClient) RegisterService(ctx context.Context, in *pb.RegisterRequest, opts ...grpc.CallOption) (*pb.RegisterResponse, error) {
return &pb.RegisterResponse{}, grpc.Errorf(codes.Internal, "Built to Fail")
}
func (DiscoveryServiceClient failingDiscoveryServiceClient) Discover(ctx context.Context, in *pb.DiscoverRequest, opts ...grpc.CallOption) (*pb.DiscoverResponse, error) {
return &pb.DiscoverResponse{}, errors.New("Built to fail")
}
func (DiscoveryServiceClient failingDiscoveryServiceClient) ListAllServices(ctx context.Context, in *pb.ListRequest, opts ...grpc.CallOption) (*pb.ListResponse, error) {
return &pb.ListResponse{}, nil
}
func (DiscoveryServiceClient failingDiscoveryServiceClient) State(ctx context.Context, in *pb.StateRequest, opts ...grpc.CallOption) (*pb.StateResponse, error) {
return &pb.StateResponse{}, nil
}
type passingBuilder struct {
returnMaster bool
returnWeakMaster bool
}
func (clientBuilder passingBuilder) NewDiscoveryServiceClient(conn *grpc.ClientConn) pb.DiscoveryServiceClient {
return passingDiscoveryServiceClient{returnMaster: clientBuilder.returnMaster, returnWeakMaster: clientBuilder.returnWeakMaster}
}
type passingFailBuilder struct{}
func (clientBuilder passingFailBuilder) NewDiscoveryServiceClient(conn *grpc.ClientConn) pb.DiscoveryServiceClient {
return &failPassDiscoveryServiceClient{fails: 1}
}
type failingBuilder struct{}
func (clientBuilder failingBuilder) NewDiscoveryServiceClient(conn *grpc.ClientConn) pb.DiscoveryServiceClient {
return failingDiscoveryServiceClient{}
}
type passingMonitorServiceClient struct {
failLog bool
}
func (MonitorServiceClient passingMonitorServiceClient) ReadMessageLogs(ctx context.Context, in *pb.RegistryEntry, opts ...grpc.CallOption) (*pbd.MessageLogReadResponse, error) {
return &pbd.MessageLogReadResponse{}, nil
}
func (MonitorServiceClient passingMonitorServiceClient) WriteMessageLog(ctx context.Context, in *pbd.MessageLog, opts ...grpc.CallOption) (*pbd.LogWriteResponse, error) {
if MonitorServiceClient.failLog {
return &pbd.LogWriteResponse{}, grpc.Errorf(codes.Internal, "Built to fail")
}
return &pbd.LogWriteResponse{}, nil
}
type passingMonitorBuilder struct {
failLog bool
}
func (monitorBuilder passingMonitorBuilder) NewMonitorServiceClient(conn *grpc.ClientConn) pbd.MonitorServiceClient {
return passingMonitorServiceClient{failLog: monitorBuilder.failLog}
}
func run(ctx context.Context) error {
log.Printf("Run")
return nil
}
func TestRegister(t *testing.T) {
server := GoServer{}
server.SkipLog = true
server.PrepServer()
server.RegisterRepeatingTask(run, "test_task", time.Second*5)
}
func TestNoRegister(t *testing.T) {
server := GoServer{}
server.SkipLog = true
server.PrepServerNoRegister(int32(50055))
}
func TestCPUGet(t *testing.T) {
server := GoServer{}
server.cpuMutex = &sync.Mutex{}
cpu, mem := server.getCPUUsage()
if cpu <= 0 || mem <= 0 {
t.Errorf("Bad pull from cpu or mem: %v and %v", cpu, mem)
}
}
func TestToggleSudo(t *testing.T) {
server := GoServer{}
server.RunSudo()
if !server.Sudo {
t.Errorf("Sudo not enabled")
}
}
func TestFailToDial(t *testing.T) {
server := GoServer{SkipIssue: true}
madeupport, _ := server.registerServer("madeup", "madeup", false, false, false, failingDialler{}, passingBuilder{}, basicGetter{})
if madeupport > 0 {
t.Errorf("Dial failure did not lead to bad port")
}
}
func TestFailToRegister(t *testing.T) {
server := GoServer{SkipIssue: true}
madeupport, _ := server.registerServer("madeup", "madeup", false, false, false, passingDialler{}, failingBuilder{}, basicGetter{})
if madeupport > 0 {
t.Errorf("Dial failure did not lead to bad port")
}
}
func TestFailToGet(t *testing.T) {
server := GoServer{SkipIssue: true}
server.registerServer("madeup", "madeup", false, false, false, passingDialler{}, passingBuilder{}, failingGetter{})
if server.Registry.Identifier != "Server-madeup" {
t.Errorf("Server has not registered correctly: %v", server.Registry)
}
}
func TestStraightDial(t *testing.T) {
server := GoServer{SkipIssue: true}
_, err := server.Dial("madeup", passingDialler{}, passingBuilder{})
if err != nil {
t.Errorf("Dial has failed: %v", err)
}
}
func TestFailedDialler(t *testing.T) {
server := GoServer{SkipIssue: true}
_, err := server.Dial("madeup", failingDialler{}, passingBuilder{})
if err == nil {
t.Errorf("Dial has failed: %v", err)
}
}
func TestBadRegistry(t *testing.T) {
server := GoServer{SkipIssue: true}
_, err := server.Dial("madeup", passingDialler{}, failingBuilder{})
if err == nil {
t.Errorf("Dial has failed: %v", err)
}
}
func TestGetIPSuccess(t *testing.T) {
server := GoServer{SkipIssue: true}
server.clientBuilder = passingBuilder{}
server.dialler = passingDialler{}
_, port := server.GetIP("madeup")
if port < 0 {
t.Errorf("Get IP has failed")
}
}
func TestGetIPOneFail(t *testing.T) {
server := GoServer{SkipIssue: true}
server.clientBuilder = passingFailBuilder{}
server.dialler = passingDialler{}
_, port := server.GetIP("madeup")
if port < 0 {
t.Errorf("Get IP has failed")
}
}
func TestGetIPFail(t *testing.T) {
server := GoServer{SkipIssue: true}
server.clientBuilder = failingBuilder{}
server.dialler = passingDialler{}
_, port := server.GetIP("madeup")
if port >= 0 {
t.Errorf("Failing builder has not failed")
}
}
func TestBadRegister(t *testing.T) {
server := GoServer{SkipIssue: true}
server.reregister(failingDialler{}, passingBuilder{})
}
func TestLameDuckRegister(t *testing.T) {
server := GoServer{SkipIssue: true}
server.SkipLog = true
server.PrepServer()
server.Registry = &pb.RegistryEntry{Port: 23, Master: true}
server.LameDuck = true
server.reregister(passingDialler{}, passingBuilder{})
if server.Registry.Master {
t.Errorf("Server is still master")
}
}
func TestBadReregister(t *testing.T) {
server := GoServer{SkipIssue: true}
server.Registry = &pb.RegistryEntry{Port: 23}
server.reregister(passingDialler{}, passingBuilder{})
if server.badPorts != 1 {
t.Errorf("Port failed: %v", server.Registry)
}
}
func TestRegisterServer(t *testing.T) {
server := GoServer{SkipIssue: true}
madeupport, _ := server.registerServer("madeup", "madeup", false, false, false, passingDialler{}, passingBuilder{}, basicGetter{})
if madeupport != 35 {
t.Errorf("Port number is wrong: %v", madeupport)
}
server.reregister(passingDialler{}, passingBuilder{})
if server.Registry.GetPort() != 35 {
t.Errorf("Not stored registry info: %v", server.Registry)
}
}
func TestRegisterDemoteServer(t *testing.T) {
server := GoServer{SkipLog: true, SkipIssue: true}
madeupport, _ := server.registerServer("madeup", "madeup", false, false, false, passingDialler{}, passingBuilder{}, basicGetter{})
if madeupport != 35 {
t.Errorf("Port number is wrong: %v", madeupport)
}
//Re-register as Master
server.Registry.Master = true
server.reregister(passingDialler{}, passingBuilder{})
//Re-register and fail heartbeatTime
server.reregister(passingDialler{}, failingBuilder{})
if server.Registry.Master {
t.Errorf("Registry has not demoted: %v", server.Registry)
}
}
func TestLog(t *testing.T) {
server := InitTestServer()
server.Log("MadeUpLog")
}
func TestGetIP(t *testing.T) {
ip := getLocalIP()
if ip == "" || ip == "127.0.0.1" {
t.Errorf("Get IP is returning the wrong address: %v", ip)
}
}
type TestServer struct {
*GoServer
failMote bool
}
func (s TestServer) DoRegister(server *grpc.Server) {
//Do Nothing
}
func (s TestServer) ReportHealth() bool {
return true
}
func (s TestServer) Mote(ctx context.Context, master bool) error {
if s.failMote {
return fmt.Errorf("Built to fail")
}
return nil
}
func (s TestServer) Shutdown(ctx context.Context) error {
return nil
}
func (s TestServer) GetState() []*pbg.State {
return []*pbg.State{}
}
func InitTestServer() TestServer {
s := TestServer{&GoServer{}, false}
s.Register = s
s.SkipLog = true
s.PrepServer()
s.monitorBuilder = passingMonitorBuilder{}
s.dialler = passingDialler{}
s.heartbeatTime = time.Millisecond
s.clientBuilder = passingBuilder{}
s.Registry = &pb.RegistryEntry{Name: "testserver"}
log.Printf("Set heartbeat time")
s.SkipLog = true
return s
}
func InitTestServerWithOptions(failMote bool) TestServer {
s := TestServer{&GoServer{}, failMote}
s.Register = s
s.SkipLog = true
s.PrepServer()
s.monitorBuilder = passingMonitorBuilder{}
s.dialler = passingDialler{}
s.heartbeatTime = time.Millisecond
s.clientBuilder = passingBuilder{}
s.Registry = &pb.RegistryEntry{Name: "testserver"}
log.Printf("Set heartbeat time")
return s
}
func TestHeartbeat(t *testing.T) {
server := InitTestServer()
server.SkipLog = true
go server.Serve()
log.Printf("Done Serving")
time.Sleep(20 * time.Millisecond)
log.Printf("Tearing Down")
server.teardown()
}
func TestMasterRegister(t *testing.T) {
server := InitTestServer()
server.PrepServer()
server.Registry = &pb.RegistryEntry{Port: 23, Master: false}
server.reregister(passingDialler{}, passingBuilder{returnWeakMaster: true})
if server.Registry.Master {
t.Errorf("Master has been recorded")
}
}
func TestMasterRegisterFailMote(t *testing.T) {
server := InitTestServerWithOptions(true)
server.PrepServer()
server.Registry = &pb.RegistryEntry{Port: 23, Master: false}
server.reregister(passingDialler{}, passingBuilder{returnWeakMaster: true})
if server.Registry.Master {
t.Errorf("Master has been recorded")
}
}
func TestDoLog(t *testing.T) {
server := InitTestServer()
server.Log("hello")
server.Log("hello")
if server.logsSkipped != 0 {
t.Errorf("Missed double log skip")
}
}
|
/*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package deepcopy
import (
"reflect"
"github.com/sirupsen/logrus"
)
// MergeInterface can be implemented by types to have custom deep copy logic.
type MergeInterface interface {
Merge(interface{}) interface{}
}
// Merge returns a merge of x and y.
// Supports everything except Chan, Func and UnsafePointer.
func Merge(x interface{}, y interface{}) interface{} {
return mergeRecursively(reflect.ValueOf(DeepCopy(x)), reflect.ValueOf(DeepCopy(y))).Interface()
}
func mergeRecursively(xV reflect.Value, yV reflect.Value) reflect.Value {
if !yV.IsValid() {
logrus.Debugf("invalid value given to merge recursively value: %+v", yV)
return xV
}
if !xV.IsValid() {
logrus.Debugf("invalid value given to merge recursively value: %+v", xV)
return yV
}
xT := xV.Type()
xK := xV.Kind()
yK := yV.Kind()
if xK != yK {
logrus.Debugf("Unable to merge due to varying types : %s & %s", xK, yK)
return yV
}
if xV.CanInterface() {
if mergable, ok := xV.Interface().(MergeInterface); ok {
nV := reflect.ValueOf(mergable.Merge(yV.Interface()))
if !nV.IsValid() {
return yV
}
return nV
}
}
switch xK {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
return yV
case reflect.Array, reflect.Slice:
nV := reflect.MakeSlice(xT, xV.Len()+yV.Len(), xV.Cap()+yV.Cap())
itemsYetToBeMerged := map[int]bool{}
for i := 0; i < yV.Len(); i++ {
itemsYetToBeMerged[i] = true
}
for i := 0; i < xV.Len(); i++ {
merged := false
for j := 0; j < yV.Len(); j++ {
if compare(xV.Index(i), yV.Index(j)) {
nV.Index(i).Set(mergeRecursively(xV.Index(i), yV.Index(j)))
merged = true
itemsYetToBeMerged[j] = false
break
}
}
if !merged {
nV.Index(i).Set(copyRecursively(xV.Index(i)))
}
}
for i := 0; i < yV.Len(); i++ {
if itemsYetToBeMerged[i] {
nV.Index(xV.Len() + i).Set(copyRecursively(yV.Index(i)))
}
}
return nV
case reflect.Interface:
return mergeRecursively(xV.Elem(), yV.Elem())
case reflect.Map:
nV := reflect.MakeMapWithSize(xT, xV.Len()+yV.Len())
for _, key := range xV.MapKeys() {
if yV.MapIndex(key) == reflect.Zero(reflect.TypeOf(xV)).Interface() {
nV.SetMapIndex(copyRecursively(key), copyRecursively(xV.MapIndex(key)))
continue
}
nV.SetMapIndex(copyRecursively(key), mergeRecursively(xV.MapIndex(key), yV.MapIndex(key)))
}
for _, key := range yV.MapKeys() {
if xV.MapIndex(key) == reflect.Zero(reflect.TypeOf(yV)).Interface() {
nV.SetMapIndex(copyRecursively(key), copyRecursively(yV.MapIndex(key)))
continue
}
nV.SetMapIndex(copyRecursively(key), mergeRecursively(xV.MapIndex(key), yV.MapIndex(key)))
}
return nV
case reflect.Ptr:
if xV.IsNil() {
return xV
}
nV := reflect.New(xV.Elem().Type())
nV.Elem().Set(mergeRecursively(xV.Elem(), yV.Elem()))
return yV
case reflect.Struct:
nV := reflect.New(xT).Elem()
for i := 0; i < xV.NumField(); i++ {
if !nV.Field(i).CanSet() {
continue
}
nV.Field(i).Set(mergeRecursively(xV.Field(i), yV.Field(i)))
}
return nV
default:
logrus.Debugf("unsupported for deep copy kind: %+v type: %+v value: %+v", xK, xT, xV)
return xV
}
}
// CompareInterface can be implemented by types to have custom deep copy logic.
type CompareInterface interface {
Compare(interface{}, interface{}) bool
}
func compare(xV reflect.Value, yV reflect.Value) bool {
if !yV.IsValid() {
logrus.Debugf("invalid value given to merge recursively value: %+v", yV)
return false
}
if !xV.IsValid() {
logrus.Debugf("invalid value given to merge recursively value: %+v", xV)
return false
}
xT := xV.Type()
xK := xV.Kind()
yK := yV.Kind()
if xK != yK {
logrus.Debugf("Unable to merge due to varying types : %s & %s", xK, yK)
return false
}
if xV.CanInterface() {
if comparable, ok := xV.Interface().(CompareInterface); ok {
return comparable.Compare(xV.Interface(), yV.Interface())
}
}
switch xK {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
return xV == yV
case reflect.Array:
// TODO: Check this is the required behaviour
return true
case reflect.Slice:
// TODO: Check this is the required behaviour
return true
case reflect.Interface:
return compare(xV.Elem(), yV.Elem())
case reflect.Map:
// TODO: Check this is the required behaviour
return true
case reflect.Ptr:
return compare(xV.Elem(), yV.Elem())
case reflect.Struct:
nV := reflect.New(xT).Elem()
for i := 0; i < xV.NumField(); i++ {
if nV.Type().Field(i).Name == "name" || nV.Type().Field(i).Name == "id" {
return compare(xV.Field(i), yV.Field(i))
}
}
return true
default:
logrus.Debugf("unsupported for deep compare kind: %+v type: %+v value: %+v", xK, xT, xV)
return true
}
}
|
package tally
import (
"errors"
"os"
"path"
)
func workspacePath() (string, error) {
wsPath, ok := os.LookupEnv("HOME")
if !ok {
return wsPath, errors.New("$HOME is not set")
}
wsPath = path.Join(wsPath, ".config/tally")
return wsPath, nil
}
|
package main
import "sort"
// Leetcode 435. (medium)
func eraseOverlapIntervals(intervals [][]int) int {
if len(intervals) <= 1 {
return 0
}
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][1] < intervals[j][1]
})
save := 1
right := intervals[0][1]
for _, tmp := range intervals[1:] {
if tmp[0] >= right {
save++
right = tmp[1]
}
}
return len(intervals) - save
}
|
// @author Couchbase <info@couchbase.com>
// @copyright 2015 Couchbase, 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 cbauthimpl contains internal implementation details of
// cbauth. It's APIs are subject to change without notice.
package cbauthimpl
import (
"bytes"
"crypto/md5"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"sync"
"time"
)
// TLSRefreshCallback type describes callback for reinitializing TLSConfig when ssl certificate
// or client cert auth setting changes.
type TLSRefreshCallback func() error
// ErrNoAuth is an error that is returned when the user credentials
// are not recognized
var ErrNoAuth = errors.New("Authentication failure")
// ErrNotInitialized is used to signal that certificate refresh callback is already registered
var ErrCallbackAlreadyRegistered = errors.New("Certificate refresh callback is already registered")
// ErrUserNotFound is used to signal when username can't be extracted from client certificate.
var ErrUserNotFound = errors.New("Username not found")
// Node struct is used as part of Cache messages to describe creds and
// ports of some cluster node.
type Node struct {
Host string
User string
Password string
Ports []int
Local bool
}
func matchHost(n Node, host string) bool {
NodeHostIP := net.ParseIP(n.Host)
HostIP := net.ParseIP(host)
if NodeHostIP.IsLoopback() {
return true
}
if HostIP.IsLoopback() && n.Local {
return true
}
// If both are IP addresses then use the standard API to check if they are equal.
if NodeHostIP != nil && HostIP != nil {
return HostIP.Equal(NodeHostIP)
} else {
return host == n.Host
}
}
func getMemcachedCreds(n Node, host string, port int) (user, password string) {
if !matchHost(n, host) {
return "", ""
}
for _, p := range n.Ports {
if p == port {
return n.User, n.Password
}
}
return "", ""
}
type credsDB struct {
nodes []Node
authCheckURL string
permissionCheckURL string
specialUser string
specialPassword string
permissionsVersion string
authVersion string
certVersion int
extractUserFromCertURL string
clientCertAuthState string
clientCertAuthVersion string
}
// Cache is a structure into which the revrpc json is unmarshalled
type Cache struct {
Nodes []Node
AuthCheckURL string `json:"authCheckUrl"`
PermissionCheckURL string `json:"permissionCheckUrl"`
SpecialUser string `json:"specialUser"`
PermissionsVersion string
AuthVersion string
CertVersion int
ExtractUserFromCertURL string `json:"extractUserFromCertURL"`
ClientCertAuthState string `json:"clientCertAuthState"`
ClientCertAuthVersion string `json:"clientCertAuthVersion"`
}
// CredsImpl implements cbauth.Creds interface.
type CredsImpl struct {
name string
domain string
password string
db *credsDB
s *Svc
}
// Name method returns user name (e.g. for auditing)
func (c *CredsImpl) Name() string {
return c.name
}
// Domain method returns user domain (for auditing)
func (c *CredsImpl) Domain() string {
switch c.domain {
case "admin", "ro_admin":
return "builtin"
}
return c.domain
}
// IsAllowed method returns true if the permission is granted
// for these credentials
func (c *CredsImpl) IsAllowed(permission string) (bool, error) {
return checkPermission(c.s, c.name, c.domain, permission)
}
func verifySpecialCreds(db *credsDB, user, password string) bool {
return len(user) > 0 && user[0] == '@' && password == db.specialPassword
}
type semaphore chan int
func (s semaphore) signal() {
<-s
}
func (s semaphore) wait() {
s <- 1
}
type certNotifier struct {
l sync.Mutex
ch chan struct{}
callback TLSRefreshCallback
}
func newCertNotifier() *certNotifier {
return &certNotifier{
ch: make(chan struct{}, 1),
}
}
func (n *certNotifier) notifyCertChangeLocked() {
select {
case n.ch <- struct{}{}:
default:
}
}
func (n *certNotifier) notifyCertChange() {
n.l.Lock()
defer n.l.Unlock()
n.notifyCertChangeLocked()
}
func (n *certNotifier) registerCallback(callback TLSRefreshCallback) error {
n.l.Lock()
defer n.l.Unlock()
if n.callback != nil {
return ErrCallbackAlreadyRegistered
}
n.callback = callback
n.notifyCertChangeLocked()
return nil
}
func (n *certNotifier) getCallback() TLSRefreshCallback {
n.l.Lock()
defer n.l.Unlock()
return n.callback
}
func (n *certNotifier) maybeExecuteCallback() error {
callback := n.getCallback()
if callback != nil {
return callback()
}
return nil
}
func (n *certNotifier) loop() {
retry := (<-chan time.Time)(nil)
for {
select {
case <-retry:
retry = nil
case <-n.ch:
}
err := n.maybeExecuteCallback()
if err == nil {
retry = nil
continue
}
if retry == nil {
retry = time.After(5 * time.Second)
}
}
}
// Svc is a struct that holds state of cbauth service.
type Svc struct {
l sync.Mutex
db *credsDB
staleErr error
freshChan chan struct{}
upCache *LRUCache
upCacheOnce sync.Once
authCache *LRUCache
authCacheOnce sync.Once
clientCertCache *LRUCache
clientCertCacheOnce sync.Once
httpClient *http.Client
semaphore semaphore
certNotifier *certNotifier
}
func cacheToCredsDB(c *Cache) (db *credsDB) {
db = &credsDB{
nodes: c.Nodes,
authCheckURL: c.AuthCheckURL,
permissionCheckURL: c.PermissionCheckURL,
specialUser: c.SpecialUser,
permissionsVersion: c.PermissionsVersion,
authVersion: c.AuthVersion,
certVersion: c.CertVersion,
extractUserFromCertURL: c.ExtractUserFromCertURL,
clientCertAuthState: c.ClientCertAuthState,
clientCertAuthVersion: c.ClientCertAuthVersion,
}
for _, node := range db.nodes {
if node.Local {
db.specialPassword = node.Password
break
}
}
return
}
func updateDBLocked(s *Svc, db *credsDB) {
s.db = db
if s.freshChan != nil {
close(s.freshChan)
s.freshChan = nil
}
}
// UpdateDB is a revrpc method that is used by ns_server update cbauth
// state.
func (s *Svc) UpdateDB(c *Cache, outparam *bool) error {
if outparam != nil {
*outparam = true
}
// BUG(alk): consider some kind of CAS later
db := cacheToCredsDB(c)
s.l.Lock()
s.maybeRefreshCert(db)
updateDBLocked(s, db)
s.l.Unlock()
return nil
}
// ResetSvc marks service's db as stale.
func ResetSvc(s *Svc, staleErr error) {
if staleErr == nil {
panic("staleErr must be non-nil")
}
s.l.Lock()
s.staleErr = staleErr
updateDBLocked(s, nil)
s.l.Unlock()
}
func staleError(s *Svc) error {
if s.staleErr == nil {
panic("impossible Svc state where staleErr is nil!")
}
return s.staleErr
}
// NewSVC constructs Svc instance. Period is initial period of time
// where attempts to access stale DB won't cause DBStaleError responses,
// but service will instead wait for UpdateDB call.
func NewSVC(period time.Duration, staleErr error) *Svc {
return NewSVCForTest(period, staleErr, func(period time.Duration, freshChan chan struct{}, body func()) {
time.AfterFunc(period, body)
})
}
// NewSVCForTest constructs Svc isntance.
func NewSVCForTest(period time.Duration, staleErr error, waitfn func(time.Duration, chan struct{}, func())) *Svc {
if staleErr == nil {
panic("staleErr must be non-nil")
}
s := &Svc{
staleErr: staleErr,
semaphore: make(semaphore, 10),
certNotifier: newCertNotifier(),
}
dt, ok := http.DefaultTransport.(*http.Transport)
if !ok {
panic("http.DefaultTransport not an *http.Transport")
}
tr := &http.Transport{
Proxy: dt.Proxy,
DialContext: dt.DialContext,
MaxIdleConns: dt.MaxIdleConns,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: dt.IdleConnTimeout,
ExpectContinueTimeout: dt.ExpectContinueTimeout,
}
SetTransport(s, tr)
if period != time.Duration(0) {
s.freshChan = make(chan struct{})
waitfn(period, s.freshChan, func() {
s.l.Lock()
if s.freshChan != nil {
close(s.freshChan)
s.freshChan = nil
}
s.l.Unlock()
})
}
go s.certNotifier.loop()
return s
}
// SetTransport allows to change RoundTripper for Svc
func SetTransport(s *Svc, rt http.RoundTripper) {
s.httpClient = &http.Client{Transport: rt}
}
func (s *Svc) maybeRefreshCert(db *credsDB) {
if s.db == nil || s.db.certVersion != db.certVersion ||
s.db.clientCertAuthState != db.clientCertAuthState {
s.certNotifier.notifyCertChange()
}
}
func fetchDB(s *Svc) *credsDB {
s.l.Lock()
db := s.db
c := s.freshChan
s.l.Unlock()
if db != nil || c == nil {
return db
}
// if db is stale try to wait a bit
<-c
// double receive doesn't change anything from correctness
// standpoint (we close channel), but helps a lot for tests
<-c
s.l.Lock()
db = s.db
s.l.Unlock()
return db
}
const tokenHeader = "ns-server-ui"
// IsAuthTokenPresent returns true iff ns_server's ui token header
// ("ns-server-ui") is set to "yes". UI is using that header to
// indicate that request is using so called token auth.
func IsAuthTokenPresent(req *http.Request) bool {
return req.Header.Get(tokenHeader) == "yes"
}
func copyHeader(name string, from, to http.Header) {
if val := from.Get(name); val != "" {
to.Set(name, val)
}
}
func verifyPasswordOnServer(s *Svc, user, password string) (*CredsImpl, error) {
req, err := http.NewRequest("GET", "http://host/", nil)
if err != nil {
panic("Must not happen: " + err.Error())
}
req.SetBasicAuth(user, password)
return VerifyOnServer(s, req.Header)
}
// VerifyOnServer authenticates http request by calling POST /_cbauth REST endpoint
func VerifyOnServer(s *Svc, reqHeaders http.Header) (*CredsImpl, error) {
db := fetchDB(s)
if db == nil {
return nil, staleError(s)
}
if s.db.authCheckURL == "" {
return nil, ErrNoAuth
}
s.semaphore.wait()
defer s.semaphore.signal()
req, err := http.NewRequest("POST", db.authCheckURL, nil)
if err != nil {
panic(err)
}
copyHeader(tokenHeader, reqHeaders, req.Header)
copyHeader("ns-server-auth-token", reqHeaders, req.Header)
copyHeader("Cookie", reqHeaders, req.Header)
copyHeader("Authorization", reqHeaders, req.Header)
rv, err := executeReqAndGetCreds(s, db, req)
if err != nil {
return nil, err
}
return rv, nil
}
func executeReqAndGetCreds(s *Svc, db *credsDB, req *http.Request) (*CredsImpl, error) {
hresp, err := s.httpClient.Do(req)
if err != nil {
return nil, err
}
defer hresp.Body.Close()
defer io.Copy(ioutil.Discard, hresp.Body)
if hresp.StatusCode == 401 {
return nil, ErrNoAuth
}
if hresp.StatusCode != 200 {
err = fmt.Errorf("Expecting 200 or 401 from ns_server auth endpoint. Got: %s", hresp.Status)
return nil, err
}
body, err := ioutil.ReadAll(hresp.Body)
if err != nil {
return nil, err
}
resp := struct {
User, Domain string
}{}
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, err
}
rv := CredsImpl{name: resp.User, domain: resp.Domain, db: db, s: s}
return &rv, nil
}
type userPermission struct {
version string
user string
domain string
permission string
}
func checkPermission(s *Svc, user, domain, permission string) (bool, error) {
db := fetchDB(s)
if db == nil {
return false, staleError(s)
}
s.upCacheOnce.Do(func() { s.upCache = NewLRUCache(1024) })
key := userPermission{db.permissionsVersion, user, domain, permission}
allowed, found := s.upCache.Get(key)
if found {
return allowed.(bool), nil
}
allowedOnServer, err := checkPermissionOnServer(s, db, user, domain, permission)
if err != nil {
return false, err
}
s.upCache.Set(key, allowedOnServer)
return allowedOnServer, nil
}
func checkPermissionOnServer(s *Svc, db *credsDB, user, domain, permission string) (bool, error) {
s.semaphore.wait()
defer s.semaphore.signal()
req, err := http.NewRequest("GET", db.permissionCheckURL, nil)
if err != nil {
return false, err
}
req.SetBasicAuth(db.specialUser, db.specialPassword)
v := url.Values{}
v.Set("user", user)
v.Set("domain", domain)
v.Set("permission", permission)
req.URL.RawQuery = v.Encode()
hresp, err := s.httpClient.Do(req)
if err != nil {
return false, err
}
defer hresp.Body.Close()
defer io.Copy(ioutil.Discard, hresp.Body)
switch hresp.StatusCode {
case 200:
return true, nil
case 401:
return false, nil
}
return false, fmt.Errorf("Unexpected return code %v", hresp.StatusCode)
}
type userPassword struct {
version string
user string
password string
}
type userIdentity struct {
user string
domain string
}
// VerifyPassword verifies given user/password creds against cbauth
// password database. Returns nil, nil if given creds are not
// recognised at all.
func VerifyPassword(s *Svc, user, password string) (*CredsImpl, error) {
db := fetchDB(s)
if db == nil {
return nil, staleError(s)
}
if verifySpecialCreds(db, user, password) {
return &CredsImpl{
name: user,
password: password,
db: db,
s: s,
domain: "admin"}, nil
}
s.authCacheOnce.Do(func() { s.authCache = NewLRUCache(256) })
key := userPassword{db.authVersion, user, password}
id, found := s.authCache.Get(key)
if found {
identity := id.(userIdentity)
return &CredsImpl{
name: identity.user,
password: password,
db: db,
s: s,
domain: identity.domain}, nil
}
rv, err := verifyPasswordOnServer(s, user, password)
if err != nil {
return nil, err
}
if rv.domain == "admin" || rv.domain == "local" {
s.authCache.Set(key, userIdentity{rv.name, rv.domain})
}
return rv, nil
}
// GetCreds returns service password for given host and port
// together with memcached admin name and http special user.
// Or "", "", "", nil if host/port represents unknown service.
func GetCreds(s *Svc, host string, port int) (memcachedUser, user, pwd string, err error) {
db := fetchDB(s)
if db == nil {
return "", "", "", staleError(s)
}
for _, n := range db.nodes {
memcachedUser, pwd = getMemcachedCreds(n, host, port)
if memcachedUser != "" {
user = db.specialUser
return
}
}
return
}
// RegisterTLSRefreshCallback registers callback for refreshing TLS config
func RegisterTLSRefreshCallback(s *Svc, callback TLSRefreshCallback) error {
return s.certNotifier.registerCallback(callback)
}
func GetClientCertAuthType(s *Svc) (tls.ClientAuthType, error) {
db := fetchDB(s)
if db == nil {
return tls.NoClientCert, staleError(s)
}
return getAuthType(db.clientCertAuthState), nil
}
func getAuthType(state string) tls.ClientAuthType {
if state == "enable" {
return tls.VerifyClientCertIfGiven
} else if state == "mandatory" {
return tls.RequireAndVerifyClientCert
} else {
return tls.NoClientCert
}
}
type clienCertHash struct {
hash string
version string
}
func MaybeGetCredsFromCert(s *Svc, req *http.Request) (*CredsImpl, error) {
db := fetchDB(s)
if db == nil {
return nil, staleError(s)
}
// If TLS is nil, then do nothing as it's an http request and not https.
if req.TLS == nil {
return nil, nil
}
s.clientCertCacheOnce.Do(func() { s.clientCertCache = NewLRUCache(256) })
state := db.clientCertAuthState
if state == "disable" || state == "" {
return nil, nil
} else if state == "enable" && len(req.TLS.PeerCertificates) == 0 {
return nil, nil
} else {
// The leaf certificate is the one which will have the username
// encoded into it and it's the first entry in 'PeerCertificates'.
cert := req.TLS.PeerCertificates[0]
h := md5.New()
h.Write(cert.Raw)
key := clienCertHash{
hash: string(h.Sum(nil)),
version: db.clientCertAuthVersion,
}
val, found := s.clientCertCache.Get(key)
if found {
ui, _ := val.(*userIdentity)
creds := &CredsImpl{name: ui.user, domain: ui.domain, db: db, s: s}
return creds, nil
}
creds, _ := getUserIdentityFromCert(cert, db, s)
if creds != nil {
ui := &userIdentity{user: creds.name, domain: creds.domain}
s.clientCertCache.Set(key, interface{}(ui))
return creds, nil
}
return nil, ErrUserNotFound
}
}
func getUserIdentityFromCert(cert *x509.Certificate, db *credsDB, s *Svc) (*CredsImpl, error) {
if db.authCheckURL == "" {
return nil, ErrNoAuth
}
s.semaphore.wait()
defer s.semaphore.signal()
req, err := http.NewRequest("POST", db.extractUserFromCertURL, bytes.NewReader(cert.Raw))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/octet-stream")
req.SetBasicAuth(db.specialUser, db.specialPassword)
rv, err := executeReqAndGetCreds(s, db, req)
if err != nil {
return nil, err
}
return rv, nil
}
|
// Copyright 2019 Liquidata, 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 commands
import (
"context"
"github.com/dolthub/dolt/go/libraries/utils/filesys"
"github.com/dolthub/dolt/go/cmd/dolt/cli"
"github.com/dolthub/dolt/go/libraries/doltcore/env"
)
type VersionCmd struct {
VersionStr string
}
// Name is returns the name of the Dolt cli command. This is what is used on the command line to invoke the command
func (cmd VersionCmd) Name() string {
return "version"
}
// Description returns a description of the command
func (cmd VersionCmd) Description() string {
return "Displays the current Dolt cli version."
}
// RequiresRepo should return false if this interface is implemented, and the command does not have the requirement
// that it be run from within a data repository directory
func (cmd VersionCmd) RequiresRepo() bool {
return false
}
// CreateMarkdown creates a markdown file containing the helptext for the command at the given path
func (cmd VersionCmd) CreateMarkdown(fs filesys.Filesys, path, commandStr string) error {
return nil
}
// Version displays the version of the running dolt client
// Exec executes the command
func (cmd VersionCmd) Exec(ctx context.Context, commandStr string, args []string, dEnv *env.DoltEnv) int {
cli.Println("dolt version", cmd.VersionStr)
return 0
}
|
package main
func main() {
// For
sum := 0
for i := 0; i < 6; i++ {
if sum += i; sum < 5 {
continue
}
println("for 1", i, sum)
}
println("for 2", sum)
// For existing var
i := 0
for i = 0; i < 6; i++ {
println("for 3", i)
}
println("for 4", i)
// For condition only
i = 0
for i < 6 {
i++
println("for 5", i)
}
println("for 6", i)
// Infinite
i = 0
for {
println("for 7", i)
if i++; i >= 6 {
break
}
}
println("for 8", i)
// Array range
arr := [...]int{1, 2, 3, 4}
for k, v := range arr {
if v%2 == 0 {
continue
}
println("for 9", k, v)
}
// Array existing vars and break
k, v := -5, -5
for k, v = range arr {
if v > 3 {
break
}
println("for 10", k, v)
}
println("for 11", k, v)
// Array ignoring parts
for _, v := range arr {
println("for 12", v)
}
for k := range arr {
println("for 13", k)
}
for range arr {
println("for 15")
}
// Slice
slice := []int{1, 2, 3, 4}
for k, v := range slice {
if v%2 == 0 {
continue
}
println("for 16", k, v)
}
// Map
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
for k, v := range m {
if v%2 == 0 {
continue
}
println("for 17", len(k), v%2)
}
// Map existing vars and break
mapK, mapV := "", -5
for mapK, mapV = range m {
if mapV > 3 {
break
}
}
println("for 18", len(mapK), mapV > 3)
// Map ignoring parts
for _, v := range m {
println("for 19", v > 0)
}
for k := range m {
println("for 20", len(k))
}
for range m {
println("for 21")
}
// String range
str := "test"
for k, v := range str {
if k%2 == 0 {
continue
}
println("for 22", k, v)
}
// String existing vars and break
strK, strV := -5, '5'
for strK, strV = range str {
if strK > 3 {
break
}
println("for 23", strK, strV)
}
println("for 24", strK, strV)
// String ignoring parts
for _, v := range str {
println("for 25", v)
}
for k := range str {
println("for 26", k)
}
for range str {
println("for 27")
}
// String w/ unicode chars
str = "foo日本語bar🎄baz"
for _, v := range str {
println("for 28", v)
}
for k, v := range str {
println("for 29", k, v)
}
// TODO: chan
// TODO: labeled complex breaks and continues and gotos
}
|
package main
import (
"flag"
"log"
"github.com/engelsjk/faadb/rpc/reserved"
"github.com/engelsjk/faadb/servers/reservedserver"
"github.com/engelsjk/faadb/twirpserver"
)
func main() {
var flagPort = flag.String("p", "8084", "port")
var flagDataPath = flag.String("d", "", "data path")
var flagDBPath = flag.String("b", "", "database path")
var flagReloadDB = flag.Bool("r", false, "reload database")
flag.Parse()
r, err := reservedserver.NewReserved(*flagDataPath, *flagDBPath, *flagReloadDB)
if err != nil {
log.Fatal(err)
}
twirpHandler := reserved.NewReservedServer(reservedserver.NewServer(r))
twirpserver.Start(*flagPort, r.Name, twirpHandler)
}
|
package stdlib_test
import (
"sync"
"testing"
"github.com/niolabs/gonio-framework"
)
func put(t *testing.T, b nio.Block, terminal string, signals ...nio.Signal) {
if err := b.Enqueue(nio.Terminal(terminal), signals); err != nil {
t.Error(err)
}
}
func takeOne(t *testing.T, b <-chan nio.SignalGroup, wg *sync.WaitGroup) nio.SignalGroup {
wg.Wait()
select {
case signals := <-b:
return signals
default:
t.Error("channel has no signals")
}
return nil
}
func takeNone(t *testing.T, b <-chan nio.SignalGroup, wg *sync.WaitGroup) nio.SignalGroup {
wg.Wait()
select {
case signals := <-b:
t.Errorf("channel has %d signals", len(signals))
return signals
default:
return nil
}
}
|
package httputil
import (
"net/url"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
)
func utf8ToGBK(utf8str string) string {
result, _, _ := transform.String(simplifiedchinese.GBK.NewEncoder(), utf8str)
return result
}
func gbkToUtf8(gbKstr []byte) []byte {
result, _, _ := transform.Bytes(simplifiedchinese.GBK.NewDecoder(), gbKstr)
return result
}
func EscapeKeywordByGBK(keyword string) string {
return url.QueryEscape(utf8ToGBK(keyword))
}
|
package hash
var sha256K = []uint32{0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138,
0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624,
0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f,
0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}
// SHA256 implements the NIST SHA2-256 cryptographic hashsum
func SHA256(message []byte) [32]byte {
h := []uint32{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f,
0x9b05688c, 0x1f83d9ab, 0x5be0cd19}
// original length in bits
l := uint64(len(message)) * 8
// pad message
message = append(message, 0x80)
for (len(message) % 64) < 56 {
message = append(message, 0x00)
}
// append length information
for j := uint(0); j < 64; j += 8 {
message = append(message, byte(l>>(56-j)))
}
// chunk message
for i := 0; i < len(message); i += 64 {
// initialize words (first 16 words copied over from current chunk)
w := [64]uint32{}
for j := 0; j < 16; j++ {
for n := 0; n < 4; n++ {
w[j] |= uint32(message[i+(j*4)+n]) << uint(24-n*8)
}
}
// extend words (word 16 to 63 computed based on first 16 words)
for j := 16; j < 64; j++ {
s0 := (w[j-15]>>7 | w[j-15]<<25) ^ (w[j-15]>>18 | w[j-15]<<14)
s0 ^= w[j-15] >> 3
s1 := (w[j-2]>>17 | w[j-2]<<15) ^ (w[j-2]>>19 | w[j-2]<<13)
s1 ^= w[j-2] >> 10
w[j] = w[j-16] + s0 + w[j-7] + s1
}
// init working variables
v := [8]uint32{}
for j := 0; j < 8; j++ {
v[j] = h[j]
}
// main compression loop (variable names loosely based on NIST document)
for j := 0; j < 64; j++ {
s1 := (v[4]>>6 | v[4]<<26) ^ (v[4]>>11 | v[4]<<21) ^ (v[4]>>25 | v[4]<<7)
ch := (v[4] & v[5]) ^ ((^v[4]) & v[6])
t1 := v[7] + s1 + ch + sha256K[j] + w[j]
s0 := (v[0]>>2 | v[0]<<30) ^ (v[0]>>13 | v[0]<<19) ^ (v[0]>>22 | v[0]<<10)
maj := (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2])
t2 := s0 + maj
// rotate working variables around
for j := 7; j > 0; j-- {
v[j] = v[j-1]
}
v[4] += t1
v[0] = t1 + t2
}
// add compression result
for j := 0; j < 8; j++ {
h[j] += v[j]
}
}
// move sums bytewise to digest slice
var digest [32]byte
for i, s := range h {
digest[i*4] = byte(s >> 24)
digest[i*4+1] = byte(s >> 16)
digest[i*4+2] = byte(s >> 8)
digest[i*4+3] = byte(s)
}
return digest
}
|
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// creamos un waitgroup
var wg sync.WaitGroup
// esto le va a indicar el numero de hilos que va a usar el programa,
// aqui esta puesto al maximo que soporta la cpu. Desde go 1.5 este es el
// valor por defecto y por tanto no es necesario especificarlo, pero puede
// ser util si quieres limitar el numero de hilos
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func creiker() {
for i := 0; i < 50; i++ {
fmt.Println("creiker")
// añadimos una pausa para que de tiempo a que se intercalen los procesos
time.Sleep(20 * time.Millisecond)
}
// le decimos que reste uno al waitgroup
wg.Done()
}
func crispy() {
for i := 0; i < 50; i++ {
fmt.Println("crispy")
time.Sleep(20 * time.Millisecond)
}
wg.Done()
}
func main() {
// añadimos 2 al waitgroup, esto se hace para que el hilo que ejecuta el main
// espere a que se ejecuten los hilos de crispy y creiker, si no hacemos esto
// el main va a correr sin esperar a que finalicen esos hilos
wg.Add(2)
// para indicar que deseamos ejecutar metodos de manera concurrente se les personaje
// delante go (goroutines)
go crispy()
go creiker()
// aqui le decimos que espere hasta que wg este a 0 para continuar
wg.Wait()
}
|
// This file contains the types describing the map data.
package rep
import "github.com/icza/screp/rep/repcore"
// MapData describes the map and objects on it.
type MapData struct {
// Version of the map.
// 0x2f: StarCraft beta
// 0x3b: 1.00-1.03 StarCraft and above ("hybrid")
// 0x3f: 1.04 StarCraft and above ("hybrid")
// 0x40: StarCraft Remastered
// 0xcd: Brood War
// 0xce: Brood War Remastered
Version uint16
// TileSet defines the tile set used on the map.
TileSet *repcore.TileSet
// Scenario name
Name string
// Scenario description
Description string
// PlayerOwners defines the player types (player owners).
PlayerOwners []*repcore.PlayerOwner
// PlayerSides defines the player sides (player races).
PlayerSides []*repcore.PlayerSide
// Tiles is the tile data of the map (within the tile set): width x height elements.
// 1 Tile is 32 units (pixel)
Tiles []uint16 `json:",omitempty"`
// Mineral field locations on the map
MineralFields []Resource `json:",omitempty"`
// Geyser locations on the map
Geysers []Resource `json:",omitempty"`
// StartLocations on the map
StartLocations []StartLocation
// MapGraphics holds data for map image rendering.
MapGraphics *MapGraphics `json:",omitempty"`
// Debug holds optional debug info.
Debug *MapDataDebug `json:"-"`
}
// MaxHumanPlayers returns the max number of human players on the map.
func (md *MapData) MaxHumanPlayers() (count int) {
for _, owner := range md.PlayerOwners {
if owner == repcore.PlayerOwnerHumanOpenSlot {
count++
}
}
return
}
// Resource describes a resource (mineral field of vespene geyser).
type Resource struct {
// Location of the resource
repcore.Point
// Amount of the resource
Amount uint32
}
// StartLocation describes a player start location on the map
type StartLocation struct {
repcore.Point
// SlotID of the owner of this start location;
// Belongs to the Player with matching Player.SlotID
SlotID byte
}
// MapDataDebug holds debug info for the map data section.
type MapDataDebug struct {
// Data is the raw, uncompressed data of the section.
Data []byte
}
// MapGraphics holds info usually required only for map image rendering.
type MapGraphics struct {
// PlacedUnits contains all placed units on the map.
// This includes mineral fields, geysers and startlocations too.
// This also includes unit sprites.
PlacedUnits []*PlacedUnit
// Sprites contains additional visual sprites on the map.
Sprites []*Sprite
}
type PlacedUnit struct {
repcore.Point
// UnitID is the unit id. This value is used in repcmd.Unit.UnitID.
UnitID uint16
// SlotID of the owner of this unit.
// Belongs to the Player with matching Player.SlotID
SlotID byte
// ResourceAmount of if it's a resource
ResourceAmount uint32 `json:",omitempty"`
// Sprite tells if this unit is a sprite.
Sprite bool `json:",omitempty"`
}
type Sprite struct {
repcore.Point
// SpriteID is the sprite id.
SpriteID uint16
}
|
package ffmpeg
/*
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavutil/error.h>
#include <libavutil/avstring.h>
char errbuf[AV_ERROR_MAX_STRING_SIZE] = {0};
char *av_err(int errnum) {
av_strerror(errnum, errbuf, AV_ERROR_MAX_STRING_SIZE);
return errbuf;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
const (
AVFMT_FLAG_CUSTOM_IO = 0x0080
AV_NOPTS_VALUE = C.ulong(0x8000000000000000)
)
type FormatContext C.struct_AVFormatContext
func NewOutputFormatContext(output *IOContext, oFormat *OutputFormat) (*FormatContext, error) {
context := (*FormatContext)(unsafe.Pointer(C.avformat_alloc_context()))
// C.av_strlcpy(&(context.ctype().filename[0]), C.CString(filename), C.ulong(len(filename)+1))
// context.url = C.av_strdup(C.CString(filename))
context.oformat = oFormat.ctype()
context.priv_data = nil
if context.oformat.priv_data_size != C.int(0) {
context.priv_data = C.av_mallocz(C.ulong(context.oformat.priv_data_size))
if context.oformat.priv_class != nil {
*((**C.struct_AVClass)(context.priv_data)) = context.oformat.priv_class
C.av_opt_set_defaults(context.priv_data)
}
}
context.ctype().pb = output.ctype()
return context, nil
}
func NewInputFormatContext(input *IOContext, iFormat *InputFormat) (*FormatContext, error) {
context := (*FormatContext)(unsafe.Pointer(C.avformat_alloc_context()))
context.ctype().iformat = iFormat.ctype()
context.ctype().pb = input.ctype()
context.ctype().flags |= AVFMT_FLAG_CUSTOM_IO
// C.av_strlcpy(&(context.ctype().filename[0]), C.CString(filename), C.ulong(len(filename)+1))
// context.ctype().url = C.av_strdup(C.CString(filename))
v := AV_NOPTS_VALUE
context.ctype().duration = *(*C.int64_t)(unsafe.Pointer(&v))
context.ctype().start_time = *(*C.int64_t)(unsafe.Pointer(&v))
context.priv_data = nil
if context.iformat.priv_data_size != C.int(0) {
context.priv_data = C.av_mallocz(C.ulong(context.oformat.priv_data_size))
if context.oformat.priv_class != nil {
*((**C.struct_AVClass)(context.priv_data)) = context.oformat.priv_class
C.av_opt_set_defaults(context.priv_data)
}
}
//call static int update_stream_avctx(AVFormatContext *s)
panic("not implemented")
return nil, nil
}
func (context *FormatContext) StreamExists() bool {
return C.avformat_find_stream_info(context.ctype(), nil) >= 0
}
func (context *FormatContext) Release() {
C.avformat_free_context(context.ctype())
}
func (context *FormatContext) DumpFormat() {
C.av_dump_format(context.ctype(), 0, &(context.ctype().filename[0]), 1)
}
// func (context *FormatContext) OpenIO() error {
// if (context.ctype().oformat.flags & C.AVFMT_NOFILE) != 0 {
// return nil
// }
// ret := C.avio_open(&(context.ctype().pb), context.ctype().url, C.AVIO_FLAG_WRITE)
// if ret < 0 {
// return fmt.Errorf("open %q error, %s", context.ctype().filename, C.av_err(C.int(ret)))
// }
// return nil
// }
// func (context *FormatContext) Close() {
// C.avio_closep(&(context.ctype().pb))
// }
func (context *FormatContext) WriteHeader(opts map[string]string) error {
// var opt C.struct_AVDictionary
// p := &opt
// for k, v := range opts {
// C.av_dict_set(&p, C.CString(k), C.CString(v), 0)
// }
ret := C.avformat_write_header(context.ctype(), nil)
if int(ret) < 0 {
return fmt.Errorf("write header error, %s", C.av_err(ret))
}
return nil
}
func (context *FormatContext) WriteTrailer() error {
ret := C.av_write_trailer(context.ctype())
if int(ret) < 0 {
return fmt.Errorf("write trailer error, %s", C.av_err(ret))
}
return nil
}
func (context *FormatContext) WritePacket(packet *Packet) error {
ret := C.av_interleaved_write_frame(context.ctype(), packet.ctype())
if int(ret) < 0 {
return fmt.Errorf("write packet error, %s", C.av_err(ret))
}
return nil
}
func (context *FormatContext) Streams() []*Stream {
var s *C.struct_AVStream
streamSize := unsafe.Sizeof(s)
//TODO simplify it
streams := make([]*Stream, context.ctype().nb_streams)
for i := 0; i < len(streams); i++ {
offset := uintptr(i) * streamSize
streams[i] = (*Stream)(*(**C.struct_AVStream)(unsafe.Pointer(uintptr(unsafe.Pointer(context.ctype().streams)) + offset)))
}
return streams
}
func (context *FormatContext) ReadPacket(packet *Packet) error {
ret := C.av_read_frame(context.ctype(), packet.ctype())
if int(ret) < 0 {
return fmt.Errorf("read packet error, %s", C.av_err(ret))
}
return nil
}
func (context *FormatContext) ctype() *C.struct_AVFormatContext {
return (*C.struct_AVFormatContext)(unsafe.Pointer(context))
}
|
//go:generate stringer -type=QRS
package heartbeat
// QRS is the event describing the activity of a heartbeat
type QRS int
const (
A QRS = iota
V
N
F
P
X
)
// validQRS contains only valid heartbeat QRS
var validQRS = []QRS{A, V, N, F, P}
func randomQRS() QRS {
return validQRS[randomInt(0, len(validQRS)-1)]
}
|
package tui
import "github.com/nsf/termbox-go"
type sidebarScreen struct {
cursor Point
}
func (scr *sidebarScreen) title() string {
return "Menu"
}
func (scr *sidebarScreen) draw(lt Point, rb Point) {
var i int
var entry iScreen
for i, entry = range availScreens {
var title string = shrink(entry.title(), rb.X-lt.X)
if scr.cursor != InvalidPoint && scr.cursor.Y == i {
tbprint(lt.X, lt.Y+i, colcur, coldef, title)
} else {
tbprint(lt.X, lt.Y+i, coldef, coldef, title)
}
}
}
func (scr *sidebarScreen) event(ev termbox.Event) bool {
if ev.Type == termbox.EventKey {
if ev.Key == termbox.KeyArrowRight {
scr.unfocus()
currentScreen.focus()
return true
} else if ev.Key == termbox.KeyArrowDown {
if scr.cursor.Y < len(availScreens)-1 {
scr.cursor.Y = scr.cursor.Y + 1
availScreens[scr.cursor.Y].show()
return true
}
} else if ev.Key == termbox.KeyArrowUp {
if scr.cursor.Y > 0 {
scr.cursor.Y = scr.cursor.Y - 1
availScreens[scr.cursor.Y].show()
return true
}
}
}
return false
}
func (scr *sidebarScreen) show() {
sidebar = scr
}
func (scr *sidebarScreen) hide() {
}
func (scr *sidebarScreen) focus() {
focusScreen = scr
scr.cursor = Point{0, 0}
}
func (scr *sidebarScreen) unfocus() {
scr.cursor = InvalidPoint
}
|
// Copyright 2018 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.
//
// This file implements data structures used by index constraints generation.
package constraint
import (
"fmt"
"math"
"strconv"
"testing"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
)
func TestSpanSet(t *testing.T) {
testCases := []struct {
start Key
startBoundary SpanBoundary
end Key
endBoundary SpanBoundary
expected string
}{
{ // 0
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(5)), IncludeBoundary,
"[/1 - /5]",
},
{ // 1
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(5)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("mango"), tree.NewDInt(1)), ExcludeBoundary,
"[/'cherry'/5 - /'mango'/1)",
},
{ // 2
MakeCompositeKey(tree.NewDInt(5), tree.NewDInt(1)), ExcludeBoundary,
MakeKey(tree.NewDInt(5)), IncludeBoundary,
"(/5/1 - /5]",
},
{ // 3
MakeKey(tree.NewDInt(5)), IncludeBoundary,
MakeCompositeKey(tree.NewDInt(5), tree.NewDInt(1)), ExcludeBoundary,
"[/5 - /5/1)",
},
{ // 4
MakeKey(tree.DNull), IncludeBoundary,
MakeCompositeKey(tree.NewDInt(5), tree.NewDInt(1)), ExcludeBoundary,
"[/NULL - /5/1)",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
var sp Span
sp.Init(tc.start, tc.startBoundary, tc.end, tc.endBoundary)
if sp.String() != tc.expected {
t.Errorf("expected: %s, actual: %s", tc.expected, sp.String())
}
})
}
testPanic := func(t *testing.T, fn func(), expected string) {
t.Helper()
defer func() {
if r := recover(); r == nil {
t.Errorf("panic expected with message: %s", expected)
} else if fmt.Sprint(r) != expected {
t.Errorf("expected: %s, actual: %v", expected, r)
}
}()
fn()
}
var sp Span
// Create exclusive empty start boundary.
testPanic(t, func() {
sp.Init(EmptyKey, ExcludeBoundary, MakeKey(tree.DNull), IncludeBoundary)
}, "an empty start boundary must be inclusive")
// Create exclusive empty end boundary.
testPanic(t, func() {
sp.Init(MakeKey(tree.DNull), IncludeBoundary, EmptyKey, ExcludeBoundary)
}, "an empty end boundary must be inclusive")
}
func TestSpanUnconstrained(t *testing.T) {
// Test unconstrained span.
unconstrained := Span{}
if !unconstrained.IsUnconstrained() {
t.Errorf("default span is not unconstrained")
}
if unconstrained.String() != "[ - ]" {
t.Errorf("unexpected string value for unconstrained span: %s", unconstrained.String())
}
unconstrained.startBoundary = IncludeBoundary
unconstrained.start = MakeKey(tree.DNull)
if !unconstrained.IsUnconstrained() {
t.Errorf("span beginning with NULL is not unconstrained")
}
// Test constrained span's IsUnconstrained method.
var sp Span
sp.Init(MakeKey(tree.NewDInt(5)), IncludeBoundary, MakeKey(tree.NewDInt(5)), IncludeBoundary)
if sp.IsUnconstrained() {
t.Errorf("IsUnconstrained should have returned false")
}
}
func TestSpanSingleKey(t *testing.T) {
testCases := []struct {
start Key
startBoundary SpanBoundary
end Key
endBoundary SpanBoundary
expected bool
}{
{ // 0
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(1)), IncludeBoundary,
true,
},
{ // 1
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(2)), IncludeBoundary,
false,
},
{ // 2
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(1)), ExcludeBoundary,
false,
},
{ // 3
MakeKey(tree.NewDInt(1)), ExcludeBoundary,
MakeKey(tree.NewDInt(1)), IncludeBoundary,
false,
},
{ // 4
EmptyKey, IncludeBoundary,
MakeKey(tree.NewDInt(1)), IncludeBoundary,
false,
},
{ // 5
MakeKey(tree.NewDInt(1)), IncludeBoundary,
EmptyKey, IncludeBoundary,
false,
},
{ // 6
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.DNull), IncludeBoundary,
false,
},
{ // 7
MakeKey(tree.NewDString("a")), IncludeBoundary,
MakeKey(tree.NewDString("ab")), IncludeBoundary,
false,
},
{ // 8
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1)), IncludeBoundary,
true,
},
{ // 9
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("mango"), tree.NewDInt(1)), IncludeBoundary,
false,
},
{ // 10
MakeCompositeKey(tree.NewDString("cherry")), IncludeBoundary,
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1)), IncludeBoundary,
false,
},
{ // 11
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1), tree.DNull), IncludeBoundary,
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(1), tree.DNull), IncludeBoundary,
true,
},
}
for i, tc := range testCases {
st := cluster.MakeTestingClusterSettings()
evalCtx := tree.MakeTestingEvalContext(st)
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
var sp Span
sp.Init(tc.start, tc.startBoundary, tc.end, tc.endBoundary)
if sp.HasSingleKey(&evalCtx) != tc.expected {
t.Errorf("expected: %v, actual: %v", tc.expected, !tc.expected)
}
})
}
}
func TestSpanCompare(t *testing.T) {
keyCtx := testKeyContext(1, 2)
testComp := func(t *testing.T, left, right Span, expected int) {
t.Helper()
if actual := left.Compare(keyCtx, &right); actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
}
one := MakeKey(tree.NewDInt(1))
two := MakeKey(tree.NewDInt(2))
oneone := MakeCompositeKey(tree.NewDInt(1), tree.NewDInt(1))
twoone := MakeCompositeKey(tree.NewDInt(2), tree.NewDInt(1))
var spans [17]Span
// [ - /2)
spans[0].Init(EmptyKey, IncludeBoundary, two, ExcludeBoundary)
// [ - /2/1)
spans[1].Init(EmptyKey, IncludeBoundary, twoone, ExcludeBoundary)
// [ - /2/1]
spans[2].Init(EmptyKey, IncludeBoundary, twoone, IncludeBoundary)
// [ - /2]
spans[3].Init(EmptyKey, IncludeBoundary, two, IncludeBoundary)
// [ - ]
spans[4] = Span{}
// [/1 - /2/1)
spans[5].Init(one, IncludeBoundary, twoone, ExcludeBoundary)
// [/1 - /2/1]
spans[6].Init(one, IncludeBoundary, twoone, IncludeBoundary)
// [/1 - ]
spans[7].Init(one, IncludeBoundary, EmptyKey, IncludeBoundary)
// [/1/1 - /2)
spans[8].Init(oneone, IncludeBoundary, two, ExcludeBoundary)
// [/1/1 - /2]
spans[9].Init(oneone, IncludeBoundary, two, IncludeBoundary)
// [/1/1 - ]
spans[10].Init(oneone, IncludeBoundary, EmptyKey, IncludeBoundary)
// (/1/1 - /2)
spans[11].Init(oneone, ExcludeBoundary, two, ExcludeBoundary)
// (/1/1 - /2]
spans[12].Init(oneone, ExcludeBoundary, two, IncludeBoundary)
// (/1/1 - ]
spans[13].Init(oneone, ExcludeBoundary, EmptyKey, IncludeBoundary)
// (/1 - /2/1)
spans[14].Init(one, ExcludeBoundary, twoone, ExcludeBoundary)
// (/1 - /2/1]
spans[15].Init(one, ExcludeBoundary, twoone, IncludeBoundary)
// (/1 - ]
spans[16].Init(one, ExcludeBoundary, EmptyKey, IncludeBoundary)
for i := 0; i < len(spans)-1; i++ {
testComp(t, spans[i], spans[i+1], -1)
testComp(t, spans[i+1], spans[i], 1)
testComp(t, spans[i], spans[i], 0)
testComp(t, spans[i+1], spans[i+1], 0)
}
keyCtx = testKeyContext(-1, 2)
// [ - /1)
spans[0].Init(EmptyKey, IncludeBoundary, one, ExcludeBoundary)
// [ - /1/1)
spans[1].Init(EmptyKey, IncludeBoundary, oneone, ExcludeBoundary)
// [ - /1/1]
spans[2].Init(EmptyKey, IncludeBoundary, oneone, IncludeBoundary)
// [ - /1]
spans[3].Init(EmptyKey, IncludeBoundary, one, IncludeBoundary)
// [ - ]
spans[4] = Span{}
// [/2 - /1/1)
spans[5].Init(two, IncludeBoundary, oneone, ExcludeBoundary)
// [/2 - /1/1]
spans[6].Init(two, IncludeBoundary, oneone, IncludeBoundary)
// [/2 - ]
spans[7].Init(two, IncludeBoundary, EmptyKey, IncludeBoundary)
// [/2/1 - /1)
spans[8].Init(twoone, IncludeBoundary, one, ExcludeBoundary)
// [/2/1 - /1]
spans[9].Init(twoone, IncludeBoundary, one, IncludeBoundary)
// [/2/1 - ]
spans[10].Init(twoone, IncludeBoundary, EmptyKey, IncludeBoundary)
// (/2/1 - /1)
spans[11].Init(twoone, ExcludeBoundary, one, ExcludeBoundary)
// (/2/1 - /1]
spans[12].Init(twoone, ExcludeBoundary, one, IncludeBoundary)
// (/2/1 - ]
spans[13].Init(twoone, ExcludeBoundary, EmptyKey, IncludeBoundary)
// (/2 - /1/1)
spans[14].Init(two, ExcludeBoundary, oneone, ExcludeBoundary)
// (/2 - /1/1]
spans[15].Init(two, ExcludeBoundary, oneone, IncludeBoundary)
// (/2 - ]
spans[16].Init(two, ExcludeBoundary, EmptyKey, IncludeBoundary)
for i := 0; i < len(spans)-1; i++ {
testComp(t, spans[i], spans[i+1], -1)
testComp(t, spans[i+1], spans[i], 1)
testComp(t, spans[i], spans[i], 0)
testComp(t, spans[i+1], spans[i+1], 0)
}
}
func TestSpanCompareStarts(t *testing.T) {
keyCtx := testKeyContext(1, 2)
test := func(left, right Span, expected int) {
t.Helper()
if actual := left.CompareStarts(keyCtx, &right); actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
}
one := MakeKey(tree.NewDInt(1))
two := MakeKey(tree.NewDInt(2))
five := MakeKey(tree.NewDInt(5))
nine := MakeKey(tree.NewDInt(9))
var onefive Span
onefive.Init(one, IncludeBoundary, five, IncludeBoundary)
var twonine Span
twonine.Init(two, ExcludeBoundary, nine, ExcludeBoundary)
// Same span.
test(onefive, onefive, 0)
// Different spans.
test(onefive, twonine, -1)
test(twonine, onefive, 1)
}
func TestSpanCompareEnds(t *testing.T) {
keyCtx := testKeyContext(1, 2)
test := func(left, right Span, expected int) {
t.Helper()
if actual := left.CompareEnds(keyCtx, &right); actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
}
one := MakeKey(tree.NewDInt(1))
two := MakeKey(tree.NewDInt(2))
five := MakeKey(tree.NewDInt(5))
nine := MakeKey(tree.NewDInt(9))
var onefive Span
onefive.Init(one, IncludeBoundary, five, IncludeBoundary)
var twonine Span
twonine.Init(two, ExcludeBoundary, nine, ExcludeBoundary)
// Same span.
test(onefive, onefive, 0)
// Different spans.
test(onefive, twonine, -1)
test(twonine, onefive, 1)
}
func TestSpanStartsAfter(t *testing.T) {
keyCtx := testKeyContext(1, 2)
test := func(left, right Span, expected, expectedStrict bool) {
t.Helper()
if actual := left.StartsAfter(keyCtx, &right); actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
if actual := left.StartsStrictlyAfter(keyCtx, &right); actual != expectedStrict {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expectedStrict, actual)
}
}
// Same span.
var banana Span
banana.Init(
MakeCompositeKey(tree.DNull, tree.NewDInt(100)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("banana"), tree.NewDInt(50)), IncludeBoundary,
)
test(banana, banana, false, false)
// Right span's start equal to left span's end.
var cherry Span
cherry.Init(
MakeCompositeKey(tree.NewDString("banana"), tree.NewDInt(50)), ExcludeBoundary,
MakeKey(tree.NewDString("cherry")), ExcludeBoundary,
)
test(banana, cherry, false, false)
test(cherry, banana, true, false)
// Right span's start greater than left span's end, and inverse.
var cherry2 Span
cherry2.Init(
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(0)), IncludeBoundary,
MakeKey(tree.NewDString("mango")), ExcludeBoundary,
)
test(cherry, cherry2, false, false)
test(cherry2, cherry, true, true)
}
func TestSpanIntersect(t *testing.T) {
keyCtx := testKeyContext(1, 2)
testInt := func(left, right Span, expected string) {
t.Helper()
sp := left
ok := sp.TryIntersectWith(keyCtx, &right)
var actual string
if ok {
actual = sp.String()
}
if actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
}
// Same span.
var banana Span
banana.Init(
MakeCompositeKey(tree.DNull, tree.NewDInt(100)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("banana"), tree.NewDInt(50)), IncludeBoundary,
)
testInt(banana, banana, "[/NULL/100 - /'banana'/50]")
// One span immediately after the other.
var grape Span
grape.Init(
MakeCompositeKey(tree.NewDString("banana"), tree.NewDInt(50)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("grape")), ExcludeBoundary,
)
testInt(banana, grape, "")
testInt(grape, banana, "")
// Partial overlap.
var apple Span
apple.Init(
MakeCompositeKey(tree.NewDString("apple"), tree.NewDInt(200)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(300)), ExcludeBoundary,
)
testInt(banana, apple, "(/'apple'/200 - /'banana'/50]")
testInt(apple, banana, "(/'apple'/200 - /'banana'/50]")
// One span is subset of other.
var mango Span
mango.Init(
MakeCompositeKey(tree.NewDString("apple"), tree.NewDInt(200)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("mango")), ExcludeBoundary,
)
testInt(apple, mango, "(/'apple'/200 - /'cherry'/300)")
testInt(mango, apple, "(/'apple'/200 - /'cherry'/300)")
testInt(Span{}, mango, "(/'apple'/200 - /'mango')")
testInt(mango, Span{}, "(/'apple'/200 - /'mango')")
// Spans are disjoint.
var pear Span
pear.Init(
MakeCompositeKey(tree.NewDString("mango"), tree.NewDInt(0)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("pear"), tree.NewDInt(10)), IncludeBoundary,
)
testInt(mango, pear, "")
testInt(pear, mango, "")
// Ensure that if TryIntersectWith results in empty set, that it does not
// update either span.
mango2 := mango
pear2 := pear
mango2.TryIntersectWith(keyCtx, &pear2)
if mango2.Compare(keyCtx, &mango) != 0 {
t.Errorf("mango2 was incorrectly updated during TryIntersectWith")
}
if pear2.Compare(keyCtx, &pear) != 0 {
t.Errorf("pear2 was incorrectly updated during TryIntersectWith")
}
// Partial overlap on second key.
pear2.Init(
MakeCompositeKey(tree.NewDString("pear"), tree.NewDInt(5), tree.DNull), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("raspberry"), tree.NewDInt(100)), IncludeBoundary,
)
testInt(pear, pear2, "(/'pear'/5/NULL - /'pear'/10]")
testInt(pear2, pear, "(/'pear'/5/NULL - /'pear'/10]")
// Unconstrained (uninitialized) span.
testInt(banana, Span{}, "[/NULL/100 - /'banana'/50]")
testInt(Span{}, banana, "[/NULL/100 - /'banana'/50]")
}
func TestSpanUnion(t *testing.T) {
keyCtx := testKeyContext(1, 2)
testUnion := func(left, right Span, expected string) {
t.Helper()
sp := left
ok := sp.TryUnionWith(keyCtx, &right)
var actual string
if ok {
actual = sp.String()
}
if actual != expected {
format := "left: %s, right: %s, expected: %v, actual: %v"
t.Errorf(format, left.String(), right.String(), expected, actual)
}
}
// Same span.
var banana Span
banana.Init(
MakeCompositeKey(tree.DNull, tree.NewDInt(100)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("banana"), tree.NewDInt(50)), IncludeBoundary,
)
testUnion(banana, banana, "[/NULL/100 - /'banana'/50]")
// Partial overlap.
var apple Span
apple.Init(
MakeCompositeKey(tree.NewDString("apple"), tree.NewDInt(200)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(300)), ExcludeBoundary,
)
testUnion(banana, apple, "[/NULL/100 - /'cherry'/300)")
testUnion(apple, banana, "[/NULL/100 - /'cherry'/300)")
// One span is subset of other.
var mango Span
mango.Init(
MakeCompositeKey(tree.NewDString("apple"), tree.NewDInt(200)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("mango")), ExcludeBoundary,
)
testUnion(apple, mango, "(/'apple'/200 - /'mango')")
testUnion(mango, apple, "(/'apple'/200 - /'mango')")
testUnion(Span{}, mango, "[ - ]")
testUnion(mango, Span{}, "[ - ]")
// Spans are disjoint.
var pear Span
pear.Init(
MakeCompositeKey(tree.NewDString("mango"), tree.NewDInt(0)), IncludeBoundary,
MakeCompositeKey(tree.NewDString("pear"), tree.NewDInt(10)), IncludeBoundary,
)
testUnion(mango, pear, "")
testUnion(pear, mango, "")
// Ensure that if TryUnionWith fails to merge, that it does not update
// either span.
mango2 := mango
pear2 := pear
mango2.TryUnionWith(keyCtx, &pear2)
if mango2.Compare(keyCtx, &mango) != 0 {
t.Errorf("mango2 was incorrectly updated during TryUnionWith")
}
if pear2.Compare(keyCtx, &pear) != 0 {
t.Errorf("pear2 was incorrectly updated during TryUnionWith")
}
// Partial overlap on second key.
pear2.Init(
MakeCompositeKey(tree.NewDString("pear"), tree.NewDInt(5), tree.DNull), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("raspberry"), tree.NewDInt(100)), IncludeBoundary,
)
testUnion(pear, pear2, "[/'mango'/0 - /'raspberry'/100]")
testUnion(pear, pear2, "[/'mango'/0 - /'raspberry'/100]")
// Unconstrained (uninitialized) span.
testUnion(banana, Span{}, "[ - ]")
testUnion(Span{}, banana, "[ - ]")
}
func TestSpanPreferInclusive(t *testing.T) {
keyCtx := testKeyContext(1, 2)
testCases := []struct {
start Key
startBoundary SpanBoundary
end Key
endBoundary SpanBoundary
expected string
}{
{ // 0
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(5)), IncludeBoundary,
"[/1 - /5]",
},
{ // 1
MakeKey(tree.NewDInt(1)), IncludeBoundary,
MakeKey(tree.NewDInt(5)), ExcludeBoundary,
"[/1 - /4]",
},
{ // 2
MakeKey(tree.NewDInt(1)), ExcludeBoundary,
MakeKey(tree.NewDInt(5)), IncludeBoundary,
"[/2 - /5]",
},
{ // 3
MakeKey(tree.NewDInt(1)), ExcludeBoundary,
MakeKey(tree.NewDInt(5)), ExcludeBoundary,
"[/2 - /4]",
},
{ // 4
MakeCompositeKey(tree.NewDInt(1), tree.NewDInt(math.MaxInt64)), ExcludeBoundary,
MakeCompositeKey(tree.NewDInt(2), tree.NewDInt(math.MinInt64)), ExcludeBoundary,
"(/1/9223372036854775807 - /2/-9223372036854775808)",
},
{ // 5
MakeCompositeKey(tree.NewDString("cherry"), tree.NewDInt(5)), ExcludeBoundary,
MakeCompositeKey(tree.NewDString("mango"), tree.NewDInt(1)), ExcludeBoundary,
"[/'cherry'/6 - /'mango'/0]",
},
{ // 6
MakeCompositeKey(tree.NewDInt(1), tree.NewDString("cherry")), ExcludeBoundary,
MakeCompositeKey(tree.NewDInt(2), tree.NewDString("mango")), ExcludeBoundary,
"[/1/e'cherry\\x00' - /2/'mango')",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
var sp Span
sp.Init(tc.start, tc.startBoundary, tc.end, tc.endBoundary)
sp.PreferInclusive(keyCtx)
if sp.String() != tc.expected {
t.Errorf("expected: %s, actual: %s", tc.expected, sp.String())
}
})
}
}
func TestSpan_KeyCount(t *testing.T) {
evalCtx := tree.MakeTestingEvalContext(cluster.MakeTestingClusterSettings())
kcAscAsc := testKeyContext(1, 2)
kcDescDesc := testKeyContext(-1, -2)
testCases := []struct {
keyCtx *KeyContext
length int
span Span
expected string
}{
{ // 0
// Single key span with DString datum type.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/US_WEST - /US_WEST]"),
expected: "1",
},
{ // 1
// Multiple key span with DInt datum type.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-5 - /5]"),
expected: "11",
},
{ // 2
// Multiple key span with DOid datum type.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-5 - /5]", types.OidFamily),
expected: "11",
},
{ // 3
// Multiple key span with DDate datum type.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/2000-1-1 - /2000-1-2]", types.DateFamily),
expected: "2",
},
{ // 4
// Single-key span with multiple-column key.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/item - /US_WEST/item]"),
expected: "1",
},
{ // 5
// Fails because the span is multiple-key and the type is not enumerable.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/item - /US_WEST/object]"),
expected: "FAIL",
},
{ // 6
// Descending multiple-key span.
keyCtx: kcDescDesc,
length: 1,
span: ParseSpan(&evalCtx, "[/5 - /-5]"),
expected: "11",
},
{ // 7
// Descending multiple-key span with multiple-column keys.
keyCtx: kcDescDesc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/5 - /US_WEST/-5]"),
expected: "11",
},
{ // 8
// Fails because the keys can only differ in the last column.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/1 - /US_EAST/1]"),
expected: "FAIL",
},
{ // 9
// Fails because both keys must be at least as long as the given length.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/1/1 - /1]"),
expected: "FAIL",
},
{ // 10
// Fails because both keys must be at least as long as the given length.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/1 - ]"),
expected: "FAIL",
},
{ // 11
// Fails because the given prefix length must be larger than zero.
keyCtx: kcAscAsc,
length: 0,
span: ParseSpan(&evalCtx, "[/1 - ]"),
expected: "FAIL",
},
{ // 12
// Case with postfix values beyond the given prefix length. Key count is
// calculated only between the prefixes; postfixes are ignored.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/1/post - /5/fix]"),
expected: "5",
},
{ // 13
// Case with postfix for the start key, but not the end key.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/1/post - /5]"),
expected: "5",
},
{ // 14
// Case with postfix for the end key, but not the start key.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/1 - /5/fix]"),
expected: "5",
},
{ // 15
// Fails because of overflow.
keyCtx: kcAscAsc,
length: 1,
span: Span{
start: MakeKey(tree.NewDInt(math.MinInt64)),
end: MakeKey(tree.NewDInt(math.MaxInt64)),
startBoundary: false,
endBoundary: false,
},
expected: "FAIL",
},
{ // 16
// Fails because of underflow.
keyCtx: kcDescDesc,
length: 1,
span: Span{
start: MakeKey(tree.NewDInt(math.MaxInt64)),
end: MakeKey(tree.NewDInt(math.MinInt64)),
startBoundary: false,
endBoundary: false,
},
expected: "FAIL",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
toStr := func(cnt int64, ok bool) string {
if !ok {
return "FAIL"
}
return strconv.FormatInt(cnt, 10 /* base */)
}
if res := toStr(tc.span.KeyCount(tc.keyCtx, tc.length)); res != tc.expected {
t.Errorf("expected: %s, actual: %s", tc.expected, res)
}
})
}
}
func TestSpan_SplitSpan(t *testing.T) {
evalCtx := tree.MakeTestingEvalContext(cluster.MakeTestingClusterSettings())
kcAscAsc := testKeyContext(1, 2)
kcDescDesc := testKeyContext(-1, -2)
testCases := []struct {
keyCtx *KeyContext
length int
span Span
expected string
}{
{ // 0
// Single-key span with multiple-column key.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/item - /US_WEST/item]"),
expected: "[/'US_WEST'/'item' - /'US_WEST'/'item']",
},
{ // 1
// Fails because the datum type is not enumerable.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/item - /US_WEST/object]"),
expected: "FAIL",
},
{ // 2
// Fails because only the last datums can differ, and only if they are
// enumerable.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_EAST/item - /US_WEST/item]"),
expected: "FAIL",
},
{ // 3
// Ascending multiple-key span.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-1 - /1]"),
expected: "[/-1 - /-1] [/0 - /0] [/1 - /1]",
},
{ // 4
// Descending multiple-key span.
keyCtx: kcDescDesc,
length: 1,
span: ParseSpan(&evalCtx, "[/1 - /-1]"),
expected: "[/1 - /1] [/0 - /0] [/-1 - /-1]",
},
{ // 5
// Ascending multiple-key span with multiple-column keys.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/US_WEST/-1 - /US_WEST/1]"),
expected: "[/'US_WEST'/-1 - /'US_WEST'/-1] [/'US_WEST'/0 - /'US_WEST'/0] " +
"[/'US_WEST'/1 - /'US_WEST'/1]",
},
{ // 6
// Fails because the keys are different lengths.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[ - /'US_WEST']"),
expected: "FAIL",
},
{ // 7
// Single span with 10 keys (equal to maxKeyCount).
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(
&evalCtx,
"[/0 - /9]",
),
expected: "[/0 - /0] [/1 - /1] [/2 - /2] [/3 - /3] [/4 - /4] [/5 - /5] [/6 - /6] [/7 - /7] " +
"[/8 - /8] [/9 - /9]",
},
{ // 8
// Postfix values beyond the given prefix length. Postfixes are applied to
// the start key of the first Span, and the end key of the last Span.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-1/post - /5/fix]"),
expected: "[/-1/'post' - /-1] [/0 - /0] [/1 - /1] [/2 - /2] " +
"[/3 - /3] [/4 - /4] [/5 - /5/'fix']",
},
{ // 9
// Postfix for start key, but not end key.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-1/post/fix - /5]"),
expected: "[/-1/'post'/'fix' - /-1] [/0 - /0] [/1 - /1] [/2 - /2] " +
"[/3 - /3] [/4 - /4] [/5 - /5]",
},
{ // 10
// Postfix for end key, but not start key.
keyCtx: kcAscAsc,
length: 1,
span: ParseSpan(&evalCtx, "[/-1 - /5/post/fix]"),
expected: "[/-1 - /-1] [/0 - /0] [/1 - /1] [/2 - /2] [/3 - /3] " +
"[/4 - /4] [/5 - /5/'post'/'fix']",
},
{ // 11
// Fails because prefix length is zero.
keyCtx: kcAscAsc,
length: 0,
span: ParseSpan(&evalCtx, "[/-1 - /5]"),
expected: "FAIL",
},
{ // 12
// Fails because the end key is not as long as the given prefix length.
keyCtx: kcAscAsc,
length: 2,
span: ParseSpan(&evalCtx, "[/-1/1 - /5]"),
expected: "FAIL",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
toStr := func(spans *Spans, ok bool) string {
if !ok {
return "FAIL"
}
return spans.String()
}
if res := toStr(tc.span.Split(tc.keyCtx, tc.length)); res != tc.expected {
t.Errorf("expected: %s, actual: %s", tc.expected, res)
}
})
}
}
|
package service
import (
"context"
proto "go-micro-demos/circuitbreaker/hystrixdo/proto/house"
"strconv"
"time"
)
type HouseService struct {
}
func newHouse(id int32, name string, floor int32) *proto.RequestData {
return &proto.RequestData{Name:name, Id:id, Floor:floor}
}
func (*HouseService) GetHouse(ctx context.Context, req *proto.RequestData, resp *proto.ResponseMsg) error {
// hystrix 超时测试
time.Sleep(time.Second * 5)
reqdata := make([]*proto.RequestData, 0)
for i := 1; i < 6;i++ {
reqdata = append(reqdata, newHouse(int32(i), "name"+strconv.Itoa(i), int32(i)))
}
return nil
}
func (*HouseService) Build(ctx context.Context, req *proto.RequestData, resp *proto.ResponseMsg) error {
return nil
} |
// The entry point function is GenerateC
// GenerateC setups the head and foot of the C program then
// the function calls GenNode which recursively visits each node
// of the parse tree generated by the parser.
// Functions such as GenExpression or GenVariableDeclaration
// are called depending on the visited node's production type.
// These functions generate the appropraite C code.
package codegen
import (
"compiler/src/types"
"log"
"os"
"strconv"
)
var program = ""
var sp = 1024
var fp = 0
var sdp = 0
var tvc = 0
var globalSymbolTable = map[string]types.STEntry{}
var builtinSymbolTable = map[string]types.STEntry{}
func GenerateC(node *types.ParseNode, parseGlobalSymbolTable map[string]types.STEntry, parseBuiltinSymbolTable map[string]types.STEntry) {
globalSymbolTable = parseGlobalSymbolTable
builtinSymbolTable = parseBuiltinSymbolTable
GenerateHead()
GenNode(node, &globalSymbolTable, types.STEntry{})
GenerateFoot()
err := os.WriteFile("c/out.c", []byte(program), 0777)
if err != nil {
log.Fatal(err)
}
}
func GenerateHead() {
program += "#include <stdio.h>\n"
program += "#include <string.h>\n"
program += "#include <math.h>\n"
program += "\n"
program += "int main () {\n"
program += " float R[16];\n"
program += " float MM[1024 * 1024];\n"
}
func GenerateFoot() {
program += " return 0;\n"
program += "}"
}
func GenNode(node *types.ParseNode, localSymbolTable *map[string]types.STEntry, stEntry types.STEntry) {
var localST map[string]types.STEntry
localST = *localSymbolTable
if node.Production == types.ProcedureDeclarationProd {
localST = node.ProcLocalSymbolTable
}
var entry types.STEntry
entry = stEntry
var identifier types.ParseNode
if node.Production == types.ProcedureDeclarationProd {
header := node.ChildNodes[0]
// if header.ChildNodes[0].TerminalToken.TokenType == types.GlobalKeyword {
// identifier = node.ChildNodes[2]
// } else {
// identifier = node.ChildNodes[1]
// }
identifier = header.ChildNodes[1]
entry = localST[identifier.TerminalToken.StringValue]
}
for _, child := range node.ChildNodes {
GenNode(&child, &localST, entry)
}
// if node.Production == types.DeclarationProd {
// GenDeclaration(node, &localST)
// }
if node.Production == types.VariableDeclarationProd {
GenVariableDeclaration(node, &localST)
}
if node.Production == types.ProcedureDeclarationProd {
GenProcedureDeclaration(node, &localST)
}
if node.Production == types.AssignmentStatementProd {
// for rule 14
GenAssignmentStatement(node, &localST)
}
if node.Production == types.LoopStatementProd {
// for rule 15
// check assignment statement
GenLoopStatement(node, &localST, entry)
}
if node.Production == types.IfStatementProd {
// for rule 15
// check assignment statement
GenIfStatement(node, &localST, entry)
}
if node.Production == types.ReturnStatementProd {
// for rule 15
// check assignment statement
GenReturnStatement(node, &localST, entry)
}
}
func GenDeclaration(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) {
}
func GenVariableDeclaration(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) {
// errString := "Code Generation Error: "
identifier := node.ChildNodes[1].TerminalToken.StringValue
var stEntry types.STEntry
stEntryLocal, existsLocal := (*localSymbolTable)[identifier]
stEntryGlobal, existsGlobal := globalSymbolTable[identifier]
if existsLocal {
stEntry = stEntryLocal
} else if existsGlobal {
stEntry = stEntryGlobal
}
stEntry.Pointer = sp
if existsLocal {
(*localSymbolTable)[identifier] = stEntry
} else if existsGlobal {
globalSymbolTable[identifier] = stEntry
}
sp += 1
}
func GenProcedureDeclaration(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) {
}
func GenAssignmentStatement(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) {
identifier := node.ChildNodes[0].ChildNodes[0].TerminalToken.StringValue
var stEntry types.STEntry
stEntryLocal, existsLocal := (*localSymbolTable)[identifier]
stEntryGlobal, existsGlobal := globalSymbolTable[identifier]
if existsLocal {
stEntry = stEntryLocal
} else if existsGlobal {
stEntry = stEntryGlobal
}
if stEntry.IsArray {
if len(node.ChildNodes[0].ChildNodes) > 1 {
GenExpression(&node.ChildNodes[0].ChildNodes[2], localSymbolTable)
offset := sp - 1
GenExpression(&node.ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "MM[" + strconv.Itoa(stEntry.Pointer) + " + (int)MM[" + strconv.Itoa(offset) + "]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
} else {
// full array
}
} else {
GenExpression(&node.ChildNodes[2], localSymbolTable)
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "MM[" + strconv.Itoa(stEntry.Pointer) + "] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
}
func GenLoopStatement(node *types.ParseNode, localSymbolTable *map[string]types.STEntry, stEntry types.STEntry) {
}
func GenIfStatement(node *types.ParseNode, localSymbolTable *map[string]types.STEntry, stEntry types.STEntry) {
}
func GenReturnStatement(node *types.ParseNode, localSymbolTable *map[string]types.STEntry, stEntry types.STEntry) {
}
func GenExpression(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
stEntry, stType := GenArithOp(&node.ChildNodes[0], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 1 {
operation := string(node.ChildNodes[1].ChildNodes[0].TerminalToken.TokenType)
GenExpressionPrime(&node.ChildNodes[1].ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenExpressionPrime(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
operation := string(node.ChildNodes[0].TerminalToken.TokenType)
stEntry, stType := GenArithOp(&node.ChildNodes[1], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 2 {
GenExpressionPrime(&node.ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenArithOp(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
stEntry, stType := GenRelation(&node.ChildNodes[0], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 1 {
operation := string(node.ChildNodes[1].ChildNodes[0].TerminalToken.TokenType)
GenArithOpPrime(&node.ChildNodes[1].ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenArithOpPrime(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
operation := string(node.ChildNodes[0].TerminalToken.TokenType)
stEntry, stType := GenRelation(&node.ChildNodes[1], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 2 {
GenArithOpPrime(&node.ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenRelation(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
stEntry, stType := GenTerm(&node.ChildNodes[0], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 1 {
operation := string(node.ChildNodes[1].ChildNodes[0].TerminalToken.TokenType)
GenRelationPrime(&node.ChildNodes[1].ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenRelationPrime(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
operation := string(node.ChildNodes[0].TerminalToken.TokenType)
stEntry, stType := GenTerm(&node.ChildNodes[1], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 2 {
GenRelationPrime(&node.ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenTerm(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
stEntry, stType := GenFactor(&node.ChildNodes[0], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 1 {
operation := string(node.ChildNodes[1].ChildNodes[0].TerminalToken.TokenType)
GenTermPrime(&node.ChildNodes[1].ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenTermPrime(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
operation := string(node.ChildNodes[0].TerminalToken.TokenType)
stEntry, stType := GenFactor(&node.ChildNodes[1], localSymbolTable)
offset := sp - 1
if len(node.ChildNodes) > 2 {
GenTermPrime(&node.ChildNodes[2], localSymbolTable)
offset = (sp - 1) - offset
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + "];\n"
program += "R[3] = MM[(int)R[0] - 1];\n"
program += "R[4] = R[2] " + operation + " R[3];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
return stEntry, stType
}
func GenFactor(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
var stType types.STType
var stEntry types.STEntry
if node.ChildNodes[0].TerminalToken.TokenType == types.SubtractionOperator {
if node.ChildNodes[1].Production == types.NameProd {
stEntry, stType = GenName(&node.ChildNodes[1], localSymbolTable)
if stType != types.STVarBoolArray && stType != types.STVarFloatArray && stType != types.STVarInteger && stType != types.STVarStringArray {
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "R[2] = R[2] * -1;\n"
program += "MM[(int)R[0] - 1] = R[2];\n"
} else {
offset := stEntry.ArraySize
for i := 0; i < stEntry.ArraySize; i++ {
program += "R[2] = MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + " + " + strconv.Itoa(i) + "];\n"
program += "R[2] = R[2] * -1;\n"
program += "MM[(int)R[0] - 1 - " + strconv.Itoa(offset) + " + " + strconv.Itoa(i) + "] = R[2];\n"
}
}
} else if node.ChildNodes[1].Production == types.NumberProd {
if node.ChildNodes[1].TerminalToken.TokenType == types.FloatToken {
program += "R[2] = " + strconv.FormatFloat(node.ChildNodes[0].TerminalToken.FloatValue, 'f', 10, 64) + ";\n"
program += "R[2] = R[2] * -1;\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarFloat
} else if node.ChildNodes[1].TerminalToken.TokenType == types.IntegerToken {
program += "R[2] = " + strconv.FormatInt(node.ChildNodes[0].TerminalToken.IntValue, 10) + ";\n"
program += "R[2] = R[2] * -1;\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarInteger
}
}
} else if node.ChildNodes[0].TerminalToken.TokenType == types.OpenRoundBracket {
stEntry, stType = GenExpression(&node.ChildNodes[1], localSymbolTable)
} else if node.ChildNodes[0].Production == types.ProcedureCallProd {
stEntry, stType = GenProcedureCall(&node.ChildNodes[0], localSymbolTable)
} else if node.ChildNodes[0].Production == types.NameProd {
stEntry, stType = GenName(&node.ChildNodes[0], localSymbolTable)
} else if node.ChildNodes[0].Production == types.NumberProd {
if node.ChildNodes[0].TerminalToken.TokenType == types.FloatToken {
program += "R[2] = " + strconv.FormatFloat(node.ChildNodes[0].TerminalToken.FloatValue, 'f', 10, 64) + ";\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarFloat
} else if node.ChildNodes[0].TerminalToken.TokenType == types.IntegerToken {
program += "R[2] = " + strconv.FormatInt(node.ChildNodes[0].TerminalToken.IntValue, 10) + ";\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarInteger
}
} else if node.ChildNodes[0].Production == types.StringProd {
program += "strcpy((char *)(MM+" + strconv.Itoa(sdp) + "),\"" + node.ChildNodes[0].TerminalToken.StringValue + "\");\n"
program += "R[2] = " + strconv.Itoa(sdp) + ";\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sdp += len(node.ChildNodes[0].TerminalToken.StringValue)
sp += 1
stType = types.STVarString
} else if node.ChildNodes[0].TerminalToken.TokenType == types.TrueKeyword {
program += "R[2] = 1;\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarBool
} else if node.ChildNodes[0].TerminalToken.TokenType == types.FalseKeyword {
program += "R[2] = 0;\n"
program += "MM[(int)R[0]] = R[2];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
stType = types.STVarBool
}
return stEntry, stType
}
func GenProcedureCall(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
lbst := builtinSymbolTable
var stType types.STType
identifier := node.ChildNodes[0].TerminalToken.StringValue
var stEntry types.STEntry
stEntryLocal, existsLocal := (*localSymbolTable)[identifier]
stEntryGlobal, existsGlobal := globalSymbolTable[identifier]
_, existsBuiltin := lbst[identifier]
if existsLocal {
stEntry = stEntryLocal
} else if existsGlobal {
stEntry = stEntryGlobal
} else if existsBuiltin {
if len(node.ChildNodes) > 3 {
GenExpression(&node.ChildNodes[2], localSymbolTable)
}
if identifier == "putbool" {
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "printf(\"%d\\n\", (int)R[2]);\n"
} else if identifier == "putinteger" {
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "printf(\"%d\\n\", (int)R[2]);\n"
} else if identifier == "putfloat" {
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "printf(\"%f\\n\", R[2]);\n"
} else if identifier == "putstring" {
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "printf(\"%s\\n\", (char *)(MM+(int)R[2]));\n"
} else if identifier == "getbool" {
temp := "tmp_" + strconv.Itoa(tvc)
program += "int " + temp + ";\n"
program += "scanf(\"%d\", &" + temp + ");\n"
program += "R[3] = " + temp + ";\n"
program += "MM[(int)R[0]] = R[3];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
tvc += 1
} else if identifier == "getinteger" {
temp := "tmp_" + strconv.Itoa(tvc)
program += "int " + temp + ";\n"
program += "scanf(\"%d\", &" + temp + ");\n"
program += "R[3] = " + temp + ";\n"
program += "MM[(int)R[0]] = R[3];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
tvc += 1
} else if identifier == "getfloat" {
temp := "tmp_" + strconv.Itoa(tvc)
program += "float " + temp + ";\n"
program += "scanf(\"%f\", &" + temp + ");\n"
program += "R[3] = " + temp + ";\n"
program += "MM[(int)R[0]] = R[3];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
tvc += 1
} else if identifier == "getstring" {
temp := "tmp_" + strconv.Itoa(tvc)
program += "char " + temp + "[80];\n"
program += "scanf(\"%s\", " + temp + ");\n"
program += "strcpy((char *)(MM+" + strconv.Itoa(sdp) + "), " + temp + ");\n"
program += "R[3] = " + strconv.Itoa(sdp) + ";\n"
program += "MM[(int)R[0]] = R[3];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
tvc += 1
} else if identifier == "sqrt" {
temp := "tmp_" + strconv.Itoa(tvc)
program += "float " + temp + ";\n"
program += "R[2] = MM[(int)R[0] - 1];\n"
program += "R[3] = " + "(float) sqrt((int)R[2]);\n"
program += "MM[(int)R[0]] = R[3];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
tvc += 1
}
}
return stEntry, stType
}
func GenName(node *types.ParseNode, localSymbolTable *map[string]types.STEntry) (types.STEntry, types.STType) {
identifier := node.ChildNodes[0].TerminalToken.StringValue
var stEntry types.STEntry
stEntryLocal, existsLocal := (*localSymbolTable)[identifier]
stEntryGlobal, existsGlobal := globalSymbolTable[identifier]
if existsLocal {
stEntry = stEntryLocal
} else if existsGlobal {
stEntry = stEntryGlobal
}
pointer := stEntry.Pointer
program += "R[2] = " + strconv.Itoa(pointer) + ";\n"
if len(node.ChildNodes) > 1 {
GenExpression(&node.ChildNodes[2], localSymbolTable)
program += "R[3] = MM[(int)R[0] - 1];\n"
} else {
program += "R[3] = 0;\n"
}
if len(node.ChildNodes) == 1 && stEntry.IsArray {
for i := 0; i < stEntry.ArraySize; i++ {
program += "R[4] = MM[(int)R[2] + " + strconv.Itoa(i) + "];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
} else {
program += "R[4] = MM[(int)R[2] + (int)R[3]];\n"
program += "MM[(int)R[0]] = R[4];\n"
program += "R[0] = R[0] + 1;\n"
sp += 1
}
if len(node.ChildNodes) > 1 {
if stEntry.EntryType == types.STVarBoolArray {
return stEntry, types.STVarBool
} else if stEntry.EntryType == types.STVarFloatArray {
return stEntry, types.STVarFloat
} else if stEntry.EntryType == types.STVarIntegerArray {
return stEntry, types.STVarInteger
} else if stEntry.EntryType == types.STVarStringArray {
return stEntry, types.STVarString
}
} else {
return stEntry, stEntry.EntryType
}
return stEntry, stEntry.EntryType
}
|
package cmd
import (
"os"
"os/signal"
"github.com/7phs/coding-challenge-search/config"
"github.com/7phs/coding-challenge-search/db"
"github.com/7phs/coding-challenge-search/logger"
"github.com/7phs/coding-challenge-search/model"
"github.com/7phs/coding-challenge-search/nlp"
"github.com/7phs/coding-challenge-search/restapi"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var RunCmd = &cobra.Command{
Use: "run",
Short: "Run a server",
Run: func(cmd *cobra.Command, args []string) {
logger.Init()
log.Info(ApplicationInfo())
config.Init()
nlp.Init()
db.Init(config.Conf.DatabaseUrl, db.Dependencies{
Lem: nlp.Lem,
})
model.Init(model.Dependencies{
SearchDataSource: db.MemoryItems,
Lem: nlp.Lem,
})
restapi.Init(config.Conf.Stage)
srv := restapi.
NewServer(config.Conf).
Run()
stop := make(chan os.Signal)
signal.Notify(stop, os.Interrupt)
<-stop
log.Info("interrupt signal")
srv.Shutdown()
db.Shutdown()
log.Info("finish")
},
}
|
package Wiggle_Subsequence
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestWiggle(t *testing.T) {
ast := assert.New(t)
ast.Equal(0,wiggleMaxLength([]int{}))
ast.Equal(1, wiggleMaxLength([]int{0, 0}))
ast.Equal(6, wiggleMaxLength([]int{1, 7, 4, 9, 2, 5}))
ast.Equal(7, wiggleMaxLength([]int{1, 17, 5, 10, 13, 15, 10, 5, 16, 8}))
ast.Equal(2, wiggleMaxLength([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.