text stringlengths 11 4.05M |
|---|
// Copyright 2022 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.
// Package gib heuristic.go implements heuristic pattern matching on strings.
package gib
import (
"regexp"
"strings"
)
var simplePatterns = []string{
`\A[^eariotnslcu]+`, // Lack of any of the first 10 most-used letters in English.
`(.){5,}`, // Repeated single characters: 5 or more in row.
`(.){2,}(.){2,}`, // repeated sequences
"abcdef",
"bcdefg",
"cdefgh",
"defghi",
"efghij",
"fghijk",
"ghijkl",
"hijklm",
"ijklmn",
"jklmno",
"klmnop",
"lmnopq",
"mnopqr",
"nopqrs",
"opqrst",
"pqrstu",
"qrstuv",
"rstuvw",
"stuvwx",
"tuvwxy",
"uvwxyz",
"|[asdfjkl]{8}",
}
func sanitize(s string) string {
// Make a Regex to say we only want letters and numbers.
s = strings.ToLower(s)
reg := regexp.MustCompile("[^a-zA-Z]+")
processedString := reg.ReplaceAllString(s, "")
return processedString
}
func simpleNonSense(text string) bool {
matchers := make([]*regexp.Regexp, 0, len(simplePatterns))
for _, pattern := range simplePatterns {
p := regexp.MustCompile(pattern)
matchers = append(matchers, p)
}
for _, matcher := range matchers {
if matcher.MatchString(text) {
return true
}
}
return false
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package netconfig
// A simplified version of the types in cros_network_config.mojom and
// network_types.mojom to be used in tests. The JSON marshalling comments are
// required for passing structs to javascript.
// There are fields that should not be included in the json object at all (not
// even as an empty object). Setting the optional fields that are of the type
// struct as a pointer allows them to be nullable and to not appear in the json
// object if not provided.
// TODO(b:223867178) Add a function to convert constants to strings to use in logging.
// Types from ip_address.mojom
// IPAddress represents IP address
type IPAddress struct {
AddressBytes []uint8
}
// Types from network_types.mojom
// NetworkType is the network technology type.
type NetworkType int
// Types of networks. Note that All and Wireless are only used for filtering.
const (
All NetworkType = iota
Cellular
Ethernet
Mobile
Tether
VPN
Wireless
WiFi
)
// DeviceStateType : Device / Technology state for devices.
type DeviceStateType int
const (
// UninitializedDST : The device is available but not yet initialized and can not be enabled.
UninitializedDST DeviceStateType = iota
// DisabledDST : The device is initialized but disabled.
DisabledDST
// DisablingDST : The device is in the process of disabling. Enable calls may fail until disabling has completed.
DisablingDST
// EnablingDST : The device is in the process of enabling. Disable calls may fail until enabling has completed.
EnablingDST
// EnabledDST : The device is enabled. Networks can be configured and connected.
EnabledDST
// ProhibitedDST : The device is disabled and enabling the device is prohibited by policy.
ProhibitedDST
// UnavailableDST : Not used in DeviceStateProperties, but useful when querying by type.
UnavailableDST
)
// ConnectionStateType : Connection state of visible networks.
type ConnectionStateType int
const (
// OnlineCST : The network is connected and internet connectivity is available.
OnlineCST ConnectionStateType = iota
// ConnectedCST : The network is connected and not in a detected portal state, but internet connectivity may not be available.
ConnectedCST
// PortalCST : The network is connected but a portal state was detected. Internet connectivity may be limited. Additional details are in PortalState.
PortalCST
// ConnectingCST : The network is in the process of connecting.
ConnectingCST
// NotConnectedCST : The network is not connected.
NotConnectedCST
)
// PortalState : The captive portal state. Provides additional details when the connection state is kPortal.
type PortalState int
const (
// UnknownPS : The network is not connected or the portal state is not available.
UnknownPS PortalState = iota
// OnlinePS : The network is connected and no portal is detected.
OnlinePS
// PortalSuspectedPS :A portal is suspected but no redirect was provided.
PortalSuspectedPS
// PortalPS : The network is in a portal state with a redirect URL.
PortalPS
// ProxyAuthRequiredPS :A proxy requiring authentication is detected.
ProxyAuthRequiredPS
// NoInternetPS : The network is connected but no internet is available and no proxy was detected.
NoInternetPS
)
// ProxyMode is affecting this network. Includes any settings that affect a given network (i.e. global proxy settings are also considered)
type ProxyMode int
const (
// DirectPM :Direct connection to the network.
DirectPM ProxyMode = iota
// AutoDetectPM :Try to retrieve a PAC script from http://wpad/wpad.dat.
AutoDetectPM
// PacScriptPM :Try to retrieve a PAC script from kProxyPacURL.
PacScriptPM
// FixedServersPM :Use a specified list of servers.
FixedServersPM
// SystemPM :Use the system's proxy settings.
SystemPM
)
// Types from cros_network_config.mojom
// OncSource : The ONC source for the network configuration, i.e. whether it is stored in the User or Device profile and whether it was configured by policy.
type OncSource int
const (
// NoneOS : The network is not remembered, or the property is not configurable.
NoneOS OncSource = iota
// UserOS : The configuration is saved in the user profile.
UserOS
// DeviceOS : The configuration is saved in the device profile.
DeviceOS
// UserPolicyOS : The configuration came from a user policy and is saved in the user profile.
UserPolicyOS
// DevicePolicyOS : The configuration came from a device policy and is saved in the device profile.
DevicePolicyOS
)
// SecurityType is the security for WiFi and Ethernet.
type SecurityType int
// Security types.
const (
None SecurityType = iota
Wep8021x
WepPsk
WpaEap
WpaPsk
)
// AuthenticationType : The authentication type for Ethernet networks.
type AuthenticationType int
// Ethernet Authenticationtype
const (
NoneAT AuthenticationType = iota
K8021x
)
// HiddenSsidMode is the tri-state status of hidden SSID.
type HiddenSsidMode int
// Whether SSID is hidden.
const (
Automatic HiddenSsidMode = iota
Disabled
Enabled
)
// ActivationStateType : Activation state for Cellular networks.
type ActivationStateType int
// ActivationStateType values
const (
UnknownAST ActivationStateType = iota
NotActivatedAST
ActivatingAST
PartiallyActivatedAST
ActivatedAST
// NoServiceAST : A cellular modem exists, but no network service is available.
NoServiceAST
)
// CellularStateProperties is member of NetworkTypeStateProperties
type CellularStateProperties struct {
Iccid string `json:"iccid"`
Eid string `json:"eid"`
ActivationState ActivationStateType `json:"activationSstate"`
NetworkTechnology string `json:"networkTechnology"`
Roaming bool `json:"roaming"`
SignalStrength int32 `json:"signalStrength"`
SimLocked bool `json:"simLocked"`
}
// WiFiStateProperties is member of NetworkTypeStateProperties
type WiFiStateProperties struct {
Bssid string `json:"bssid"`
Frequency int32 `json:"frequency"`
HexSsid string `json:"hexSsid"`
Security SecurityType `json:"security"`
SignalStrength int32 `json:"signalStrength"`
Ssid string `json:"ssid"`
HiddenSsid bool `json:"hiddenSsid"`
}
// EthernetStateProperties is member of NetworkTypeStateProperties
type EthernetStateProperties struct {
Authentication AuthenticationType `json:"authentication"`
}
// NetworkTypeStateProperties is union which is member of NetworkTypeStateProperties
type NetworkTypeStateProperties struct {
Cellular CellularStateProperties `json:"cellular,omitempty"`
Ethernet EthernetStateProperties `json:"ethernet,omitempty"`
// Tether TetherStateProperties `json:"tether,omitempty"`
// VPN VPNStateProperties `json:"vpn,omitempty"`
WiFi WiFiStateProperties `json:"wifi,omitempty"`
}
// NetworkStateProperties is returned by GetNetworkStateList
type NetworkStateProperties struct {
Connectable bool `json:"connnectable"`
ConnectRequested bool `json:"connectRequested"`
ConnectionState ConnectionStateType `json:"connectionState"`
ErrorState string `json:"errorState,omitempty"`
GUID string `json:"guid"`
Name string `json:"name"`
PortalState PortalState `json:"portalState"`
Priority int32 `json:"priority"`
ProxyMode ProxyMode `json:"proxyMode"`
ProhibitedByPolicy bool `json:"prohibitedByPolicy"`
Source OncSource `json:"source"`
Type NetworkType `json:"type"`
TypeState NetworkTypeStateProperties `json:"typeState"`
}
// ManagedString contains active value, if required one may add policy value
// and source.
type ManagedString struct {
ActiveValue string `json:"activeValue"`
}
// ManagedStringList contains active value, if required one may add policy value
// and source.
type ManagedStringList struct {
ActiveValue []string `json:"activeValue"`
}
// ManagedBoolean contains active value, if required one may add policy value
// and source.
type ManagedBoolean struct {
ActiveValue bool `json:"activeValue"`
}
// ManagedSubjectAltNameMatchList contains active value, if required one may add
// policy value and source.
type ManagedSubjectAltNameMatchList struct {
ActiveValue []SubjectAltName `json:"activeValue"`
}
// ManagedEAPProperties contains properties for EAP networks.
// Currently only PEAP networks without CA certificates are supported.
// We include the same fields as EAPConfigProperties.
type ManagedEAPProperties struct {
AnonymousIdentity ManagedString `json:"anonymousIdentity,omitempty"`
Identity ManagedString `json:"identity,omitempty"`
Inner ManagedString `json:"inner,omitempty"`
Outer ManagedString `json:"outer,omitempty"`
Password ManagedString `json:"password,omitempty"`
SaveCredentials ManagedBoolean `json:"saveCredentials,omitempty"`
ClientCertType ManagedString `json:"clientCertType,omitempty"`
DomainSuffixMatch ManagedStringList `json:"domainSuffixMatch,omitempty"`
SubjectAltNameMatch ManagedSubjectAltNameMatchList `json:"subjectAltNameMatch,omitempty"`
UseSystemCAs ManagedBoolean `json:"useSystemCas,omitempty"`
}
// ManagedWiFiProperties contain managed properties of a wifi connection.
type ManagedWiFiProperties struct {
// Passphrase is only used for PSK networks and Eap is only used for EAP.
Eap *ManagedEAPProperties `json:"eap,omitempty"`
Passphrase *ManagedString `json:"passphrase,omitempty"`
Ssid ManagedString `json:"ssid"`
Security SecurityType `json:"security"`
}
// ManagedEthernetProperties contains managed properties of an ethernet
// connection.
type ManagedEthernetProperties struct {
// Authentication represents the configured authentication type for an
// Ethernet network.
Authentication *ManagedString `json:"authentication,omitempty"`
Eap *ManagedEAPProperties `json:"eap,omitempty"`
}
// NetworkTypeManagedProperties contains managed properties for one of the
// network types. Its type is an union, so only one of the fields should be set
// simultaneously.
// Currently only Ethernet and Wifi are implemented.
type NetworkTypeManagedProperties struct {
Ethernet *ManagedEthernetProperties `json:"ethernet,omitempty"`
Wifi *ManagedWiFiProperties `json:"wifi,omitempty"`
}
// ManagedProperties are provided by GetManagedProperties, see onc_spec.md for
// details.
type ManagedProperties struct {
Type NetworkType `json:"type"`
TypeProperties NetworkTypeManagedProperties `json:"typeProperties"`
}
// SubjectAltNameType is the type for SubjectAltName.
type SubjectAltNameType int
// Allowed types for the alternative subject name.
const (
Email SubjectAltNameType = iota
DNS
URI
)
// SubjectAltName contains the information of an alternative subject name.
type SubjectAltName struct {
Type SubjectAltNameType `json:"type"`
Value string `json:"value"`
}
// EAPConfigProperties contains properties for EAP networks.
// Currently only PEAP networks without CA certificates are supported, so the
// fields related to certificates are not included: ServerCAPEMs, ServerCARefs,
// ServerCARef (deprecated), SubjectMatch, TLSVersionMax, UseProactiveKeyCaching.
type EAPConfigProperties struct {
AnonymousIdentity string `json:"anonymousIdentity,omitempty"`
Identity string `json:"identity,omitempty"`
Inner string `json:"inner,omitempty"` // "Automatic"
Outer string `json:"outer"` // "PEAP"
Password string `json:"password,omitempty"`
SaveCredentials bool `json:"saveCredentials,omitempty"` // true.
ClientCertType string `json:"clientCertType,omitempty"` // "None".
DomainSuffixMatch []string `json:"domainSuffixMatch"` // Empty in manual example but not optional in mojo.
SubjectAltNameMatch []SubjectAltName `json:"subjectAltNameMatch"` // Empty in manual example but not optional in mojo.
UseSystemCAs bool `json:"useSystemCAs,omitempty"` // false. Defaults to true.
}
// WiFiConfigProperties is used to create new configurations or augment
// existing ones.
type WiFiConfigProperties struct {
// Eap configuration is only used if the wifi security is WpaEap.
Eap *EAPConfigProperties `json:"eap,omitempty"`
Passphrase string `json:"passphrase,omitempty"`
Ssid string `json:"ssid,omitempty"`
Security SecurityType `json:"security"`
HiddenSsid HiddenSsidMode `json:"hiddenSsid"`
}
// EthernetConfigProperties is used to create ethernet configurations.
type EthernetConfigProperties struct {
// Eap configuration is only used if the ethernet authentication is 8021X.
Authentication string `json:"authentication,omitempty"`
Eap *EAPConfigProperties `json:"eap,omitempty"`
}
// NetworkTypeConfigProperties contains properties for one type of network. Its
// type is an union, so only one of the fields should be set simultaneously.
// Currently only Ethernet and Wifi are supported.
type NetworkTypeConfigProperties struct {
Ethernet *EthernetConfigProperties `json:"ethernet,omitempty"`
VPN *VPNConfigProperties `json:"vpn,omitempty"`
Wifi *WiFiConfigProperties `json:"wifi,omitempty"`
}
// ConfigProperties is passed to SetProperties or ConfigureNetwork to configure
// a new network or augment an existing one.
type ConfigProperties struct {
Name string `json:"name"`
TypeConfig NetworkTypeConfigProperties `json:"typeConfig"`
}
// FilterType is used for requesting lists of network states.
type FilterType int
const (
// ActiveFT :Return active networks. A network is active when its ConnectionStateType != kNotConnected.
ActiveFT FilterType = iota
// VisibleFT :Return visible (active, physically connected or in-range) networks. Active networks will be listed first.
VisibleFT
// ConfiguredFT :Only include configured (saved) networks.
ConfiguredFT
// AllFT :Include all networks.
AllFT
)
// NetworkFilter is passed to GetNetworkStateList to filter the list of networks returned.
type NetworkFilter struct {
Filter FilterType `json:"filter"`
NetworkType NetworkType `json:"networktype"`
Limit int32 `json:"limit"`
}
// SIMLockStatus is the SIM card lock status for Cellular networks.
type SIMLockStatus struct {
LockType string `json:"locktype"`
LockEnabled bool `json:"lockenabled"`
RetriesLeft int32 `json:"retriesleft"`
}
// SIMInfo is details about a sim slot available on the device.
type SIMInfo struct {
SlotID int32 `json:"slotID"`
Eid string `json:"eid"`
Iccid string `json:"iccid"`
IsPrimary bool `json:"isPrimary"`
}
// InhibitReason : Reasons why the Cellular Device may have its scanning inhibited (i.e. temporarily stopped).
type InhibitReason int
const (
// NotInhibited :Not inhibited
NotInhibited InhibitReason = iota
// InstallingProfile Inhibited because an eSIM profile is being installed.
InstallingProfile
// RenamingProfile :Inhibited because an eSIM profile is being renamed.
RenamingProfile
// RemovingProfile :Inhibited because an eSIM profile is being removed.
RemovingProfile
// ConnectingToProfile :Inhibited because a connection is in progress which requires that the device switch to a different eSIM profile
ConnectingToProfile
// RefreshingProfileList :Inhibited because the list of pending eSIM profiles is being refreshed by checking with an SMDS server.
RefreshingProfileList
// ResettingEuiccMemory :Inhibited because the EUICC memory is being reset.
ResettingEuiccMemory
// DisablingProfile :Inhibited because an eSIM profile is being disabled.
DisablingProfile
)
// DeviceStateProperties is returned by GetDeviceStateList
type DeviceStateProperties struct {
Ipv4Address IPAddress `json:"ipv4address,omitempty"`
Ipv6Address IPAddress `json:"ipv6address,omitempty"`
MacAddress string `json:"macaddress,omitempty"`
Scanning bool `json:"scanning"`
SimLockStatus SIMLockStatus `json:"simlockstatus"`
SimInfos []SIMInfo `json:"siminfos,omitempty"`
InhibitReason InhibitReason `json:"inhibitreason"`
SimAbsent bool `json:"simabsent"`
DeviceState DeviceStateType `json:"devicestate"`
Type NetworkType `json:"type"`
ManagedNetworkAvailable bool `json:"managednetworkavailable"`
}
// VPNConfigProperties is used to create new VPN services or augment existing
// ones.
type VPNConfigProperties struct {
Host string `json:"host"`
Type VPNTypeConfig `json:"type"`
IPsec *IPsecConfigProperties `json:"ipSec"`
L2TP *L2TPConfigProperties `json:"l2tp"`
OpenVPN *OpenVPNConfigProperties `json:"openVpn"`
WireGuard *WireGuardConfigProperties `json:"wireguard"`
}
// VPNType is the type of a VPN service.
type VPNType int
// VPN types.
const (
VPNTypeIKEv2 VPNType = iota
VPNTypeL2TPIPsec
VPNTypeOpenVPN
VPNTypeWireGuard
VPNTypeExtension
VPNTypeARC
)
// VPNTypeConfig represents the type of a VPN service.
type VPNTypeConfig struct {
Value VPNType `json:"value"`
}
// IPsecConfigProperties contains the properties to config IPsec tunnel for a VPN
// service.
type IPsecConfigProperties struct {
AuthType string `json:"authenticationType"`
EAP *EAPConfigProperties `json:"eap,omitempty"`
IKEVersion int `json:"ikeVersion"`
LocalID string `json:"localIdentity"`
PSK string `json:"psk"`
RemoteID string `json:"remoteIdentity"`
ServerCAPEMs []string `json:"serverCaPems"`
}
// L2TPConfigProperties contains the properties to config L2TP tunnel for a VPN
// service.
type L2TPConfigProperties struct {
Username string `json:"username"`
Password string `json:"password"`
}
// OpenVPNConfigProperties contains the properties to config a OpenVPN service.
type OpenVPNConfigProperties struct {
ClientCertType string `json:"clientCertType"`
ClientCertPkcs11Id string `json:"clientCertPkcs11Id"`
ExtraHosts []string `json:"extraHosts"`
Password string `json:"password"`
ServerCAPEMs []string `json:"serverCaPems"`
Username string `json:"username"`
UserAuthenticationType string `json:"userAuthenticationType"`
}
// WireGuardConfigProperties contains the properties to config a WireGuard
// service.
type WireGuardConfigProperties struct {
PrivateKey *string `json:"privateKey,omitempty"`
Peers []WireGuardPeerProperties `json:"peers"`
}
// WireGuardPeerProperties contains the properties to config a peer in WireGuard
// services.
type WireGuardPeerProperties struct {
PublicKey string `json:"publicKey"`
PresharedKey *string `json:"presharedKey,omitempty"`
AllowedIPs string `json:"allowedIps"`
Endpoint string `json:"endpoint"`
KeepAlive int `json:"persistentKeepAlive"`
}
|
package imgio
import (
"archive/tar"
"encoding/json"
"fmt"
"io"
"os"
"path"
om "github.com/box-builder/overmount"
"github.com/box-builder/overmount/configmap"
"github.com/docker/docker/image"
dl "github.com/docker/docker/layer"
digest "github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
// Export produces a tar represented as an io.ReadCloser from the Layer provided.
func (d *Docker) Export(repo *om.Repository, layer *om.Layer, tags []string) (io.ReadCloser, error) {
if !layer.Exists() {
return nil, errors.Wrap(om.ErrInvalidLayer, "layer does not exist")
}
r, w := io.Pipe()
go d.writeTar(repo, layer, w, tags)
return r, nil
}
func (d *Docker) writeTar(repo *om.Repository, layer *om.Layer, w *io.PipeWriter, tags []string) (retErr error) {
defer func() {
if retErr == nil {
w.Close()
} else {
w.CloseWithError(retErr)
}
}()
tw := tar.NewWriter(w)
chainIDs, diffIDs, _, _, err := runChain(layer, tw, func(parent digest.Digest, iter *om.Layer, tw *tar.Writer) (digest.Digest, digest.Digest, int64, error) {
tf, err := repo.TempFile()
if err != nil {
return "", "", 0, err
}
defer func() {
tf.Close()
os.Remove(tf.Name())
}()
chainID, diffID, err := calcLayer(parent, iter, tf)
if err != nil {
return "", "", 0, err
}
if err := d.packLayer(chainID, tf, tw); err != nil {
return "", "", 0, err
}
if err := d.writeLayerConfig(chainID, parent, iter, tw); err != nil {
return "", "", 0, err
}
return chainID, diffID, 0, nil
})
if err != nil {
return err
}
if err := d.writeRepositories(tw); err != nil {
return err
}
if err := d.writeManifest(layer, chainIDs, tw, tags); err != nil {
return err
}
if err := d.writeImageConfig(chainIDs[len(chainIDs)-1], diffIDs, layer, tw); err != nil {
return err
}
if err := tw.Close(); err != nil {
return err
}
w.Close()
return nil
}
func (d *Docker) packLayer(chainID digest.Digest, tf *os.File, tw *tar.Writer) error {
err := tw.WriteHeader(&tar.Header{
Name: chainID.Hex(),
Mode: 0700,
Typeflag: tar.TypeDir,
})
if err != nil {
return errors.Wrap(om.ErrImageCannotBeComposed, "cannot add directory to tar writer")
}
if _, err := tf.Seek(0, 0); err != nil {
return err
}
fi, err := tf.Stat()
if err != nil {
return err
}
err = tw.WriteHeader(&tar.Header{
Name: path.Join(chainID.Hex(), "layer.tar"),
Mode: 0600,
Typeflag: tar.TypeReg,
Size: fi.Size(),
})
if err != nil {
return errors.Wrap(om.ErrImageCannotBeComposed, "cannot add file to tar writer")
}
if _, err := io.Copy(tw, tf); err != nil {
return err
}
return nil
}
func (d *Docker) writeLayerConfig(chainID digest.Digest, parentID digest.Digest, iter *om.Layer, tw *tar.Writer) error {
var parent string
if parentID != "" {
parent = parentID.Hex()
}
content, err := json.Marshal(map[string]interface{}{
"id": chainID.Hex(),
"parent": parent,
"config": v1.ImageConfig{},
})
if err != nil {
return err
}
err = tw.WriteHeader(&tar.Header{
Name: path.Join(chainID.Hex(), "json"),
Mode: 0600,
Typeflag: tar.TypeReg,
Size: int64(len(content)),
})
if err != nil {
return err
}
if _, err := tw.Write(content); err != nil {
return err
}
return nil
}
func (d *Docker) writeRepositories(tw *tar.Writer) error {
content, err := json.Marshal(map[string]interface{}{})
if err != nil {
return err
}
err = tw.WriteHeader(&tar.Header{
Name: "repositories",
Mode: 0600,
Typeflag: tar.TypeReg,
Size: int64(len(content)),
})
if err != nil {
return err
}
if _, err := tw.Write(content); err != nil {
return err
}
return nil
}
func (d *Docker) writeManifest(layer *om.Layer, chainIDs []digest.Digest, tw *tar.Writer, tags []string) error {
chainIDHexs := []string{}
for _, chainID := range chainIDs {
chainIDHexs = append(chainIDHexs, path.Join(chainID.Hex(), "layer.tar"))
}
content, err := json.Marshal([]map[string]interface{}{
{
"Config": fmt.Sprintf("%s.json", chainIDs[len(chainIDs)-1].Hex()),
"RepoTags": tags,
"Layers": chainIDHexs,
},
})
if err != nil {
return err
}
err = tw.WriteHeader(&tar.Header{
Name: "manifest.json",
Mode: 0600,
Typeflag: tar.TypeReg,
Size: int64(len(content)),
})
if err != nil {
return err
}
if _, err := tw.Write(content); err != nil {
return err
}
return nil
}
func (d *Docker) writeImageConfig(chainID digest.Digest, diffIDs []digest.Digest, layer *om.Layer, tw *tar.Writer) error {
config, err := layer.Config()
if err != nil {
return errors.Wrap(om.ErrInvalidLayer, err.Error())
}
if config == nil {
return errors.Wrap(om.ErrImageCannotBeComposed, "missing image configuration")
}
img, err := configmap.ToDockerV1(config)
if err != nil {
return errors.Wrap(om.ErrInvalidLayer, err.Error())
}
dids := []dl.DiffID{}
for _, diff := range diffIDs {
dids = append(dids, dl.DiffID(diff))
}
outerConfig := image.Image{
V1Image: *img,
RootFS: &image.RootFS{
Type: "layers",
DiffIDs: dids,
},
Parent: image.ID(config.Parent),
}
content, err := json.Marshal(outerConfig)
if err != nil {
return err
}
err = tw.WriteHeader(&tar.Header{
Name: fmt.Sprintf("%s.json", chainID.Hex()),
Mode: 0600,
Typeflag: tar.TypeReg,
Size: int64(len(content)),
})
if err != nil {
return err
}
if _, err := tw.Write(content); err != nil {
return err
}
return nil
}
|
package graphs
import "../core"
func (d *DirectedNode) DepthFirstSearch() []int {
s := new(core.Stack)
s.Push(d)
var visited []*DirectedNode
for n, _ := s.Pop(); s.Size() != 0; n, _ = s.Pop() {
curr := n.(*DirectedNode)
for _, neighbor := range curr.neighbors {
if !(sliceContains(visited, neighbor) || s.Contains(neighbor, compareNode)) {
s.Push(neighbor)
}
}
visited = append(visited, curr)
}
// extract the actual values
var out []int
for _, n := range visited {
out = append(out, n.value)
}
return out
}
|
package main
import (
"html/template"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
//添加自定义函数
r.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
r.LoadHTMLFiles("./xss.tmpl")
r.GET("/safepage", func(c *gin.Context) {
c.HTML(http.StatusOK, "xss.tmpl", gin.H{
"str1": "<script>alert(123)</script>",
"str2": "<a href=‘http://wwwbaidu.com’>baidu</a>",
})
})
r.Run((":8888"))
}
|
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package blkverify
import (
"github.com/MatrixAINetwork/go-matrix/common"
"github.com/MatrixAINetwork/go-matrix/core/types"
"github.com/MatrixAINetwork/go-matrix/log"
"github.com/MatrixAINetwork/go-matrix/mc"
"github.com/MatrixAINetwork/go-matrix/params/manparams"
"github.com/MatrixAINetwork/go-matrix/params/manversion"
"time"
)
func (p *Process) stopSender() {
p.closeMineReqMsgSender()
p.closePosedReqSender()
p.closeVoteMsgSender()
}
func (p *Process) startSendMineReq(posHeader *types.Header) {
var reqMsg interface{}
if manversion.VersionCmp(string(posHeader.Version), manversion.VersionAIMine) < 0 {
reqMsg = &mc.HD_MiningReqMsg{Header: posHeader}
} else {
// 新版本,只有AI区块才发送挖矿请求
bcInterval, err := p.pm.bc.GetBroadcastIntervalByHash(posHeader.ParentHash)
if err != nil {
log.Info(p.logExtraInfo(), "发送挖矿请求失败", "获取广播周期失败", "err", err, "hash", posHeader.ParentHash.TerminalString())
return
}
if posHeader.IsAIHeader(bcInterval.GetBroadcastInterval()) == false {
log.Debug(p.logExtraInfo(), "发送挖矿请求", "非AI区块不发送挖矿请求", "number", posHeader.Number, "broadcastInterval", bcInterval.GetBroadcastInterval())
return
}
reqMsg = &mc.HD_V2_MiningReqMsg{Header: posHeader}
}
log.Trace(p.logExtraInfo(), "关键时间点", "共识投票完毕,发送挖矿请求", "time", time.Now(), "块高", p.number)
p.closeMineReqMsgSender()
sender, err := common.NewResendMsgCtrl(reqMsg, p.sendMineReqFunc, manparams.MinerReqSendInterval, 0)
if err != nil {
log.Error(p.logExtraInfo(), "创建挖矿请求发送器", "失败", "err", err)
return
}
p.mineReqMsgSender = sender
}
func (p *Process) closeMineReqMsgSender() {
if p.mineReqMsgSender == nil {
return
}
p.mineReqMsgSender.Close()
p.mineReqMsgSender = nil
}
func (p *Process) sendMineReqFunc(data interface{}, times uint32) {
switch data.(type) {
case *mc.HD_MiningReqMsg:
req, OK := data.(*mc.HD_MiningReqMsg)
if !OK {
log.Error(p.logExtraInfo(), "发出挖矿请求", "反射消息失败")
return
}
hash := req.Header.HashNoSignsAndNonce()
//给矿工发送区块验证结果
if times == 1 {
log.Info(p.logExtraInfo(), "发出挖矿请求, Header hash with signs", hash, "高度", p.number)
} else {
log.Trace(p.logExtraInfo(), "发出挖矿请求, Header hash with signs", hash, "次数", times, "高度", p.number)
}
p.pm.hd.SendNodeMsg(mc.HD_MiningReq, req, common.RoleMiner|common.RoleInnerMiner, nil)
case *mc.HD_V2_MiningReqMsg:
req, OK := data.(*mc.HD_V2_MiningReqMsg)
if !OK {
log.Error(p.logExtraInfo(), "发出挖矿请求V2", "反射消息失败")
return
}
hash := req.Header.HashNoSignsAndNonce()
//给矿工发送区块验证结果
if times == 1 {
log.Info(p.logExtraInfo(), "发出挖矿请求V2, Header hash with signs", hash, "高度", p.number)
} else {
log.Trace(p.logExtraInfo(), "发出挖矿请求V2, Header hash with signs", hash, "次数", times, "高度", p.number)
}
p.pm.hd.SendNodeMsg(mc.HD_V2_MiningReq, req, common.RoleMiner|common.RoleInnerMiner, nil)
default:
log.Error(p.logExtraInfo(), "未知的data类型")
return
}
}
func (p *Process) startPosedReqSender(req *mc.HD_BlkConsensusReqMsg) {
p.closePosedReqSender()
sender, err := common.NewResendMsgCtrl(req, p.sendPosedReqFunc, manparams.PosedReqSendInterval, 0)
if err != nil {
log.Error(p.logExtraInfo(), "创建POS完成的req发送器", "失败", "err", err)
return
}
p.posedReqSender = sender
}
func (p *Process) startPosedReqSenderV2(req *reqData) {
p.closePosedReqSender()
sender, err := common.NewResendMsgCtrl(req, p.sendPosedReqFuncV2, manparams.PosedReqSendInterval, 0)
if err != nil {
log.Error(p.logExtraInfo(), "创建POS完成的req发送器", "失败", "err", err)
return
}
p.posedReqSender = sender
}
func (p *Process) closePosedReqSender() {
if p.posedReqSender == nil {
return
}
p.posedReqSender.Close()
p.posedReqSender = nil
}
func (p *Process) sendPosedReqFunc(data interface{}, times uint32) {
req, OK := data.(*mc.HD_BlkConsensusReqMsg)
if !OK {
log.Error(p.logExtraInfo(), "发出POS完成的req", "反射消息失败")
return
}
//给广播节点发送区块验证请求(带签名列表)
if times == 1 {
log.Debug(p.logExtraInfo(), "发出POS完成的req(to broadcast) leader", req.Header.Leader.Hex(), "高度", p.number)
} else {
log.Trace(p.logExtraInfo(), "发出POS完成的req(to broadcast) leader", req.Header.Leader.Hex(), "次数", times, "高度", p.number)
}
p.pm.hd.SendNodeMsg(mc.HD_BlkConsensusReq, req, common.RoleBroadcast, nil)
}
func (p *Process) sendPosedReqFuncV2(data interface{}, times uint32) {
reqInfo, OK := data.(*reqData)
if !OK {
log.Error(p.logExtraInfo(), "发出POS完成的req", "反射消息失败")
return
}
headerTime := reqInfo.req.Header.Time.Int64()
curTime := time.Now().Unix()
if curTime <= headerTime+120 {
//给广播节点发送区块验证请求(带签名列表)
if times == 1 {
log.Debug(p.logExtraInfo(), "发出POS完成的req(to broadcast) leader", reqInfo.req.Header.Leader.Hex(), "高度", p.number)
} else {
log.Trace(p.logExtraInfo(), "发出POS完成的req(to broadcast) leader", reqInfo.req.Header.Leader.Hex(), "次数", times, "高度", p.number)
}
p.pm.hd.SendNodeMsg(mc.HD_BlkConsensusReq, reqInfo.req, common.RoleBroadcast, nil)
} else {
if times%2 != 0 {
return
}
// 2分钟后,每2个间隔发送一次全区块请求
req := &mc.HD_FullBlkReqToBroadcastMsg{
Header: reqInfo.req.Header,
ConsensusTurn: reqInfo.req.ConsensusTurn,
TxsCode: reqInfo.req.TxsCode,
Txs: reqInfo.originalTxs,
OnlineConsensusResults: reqInfo.req.OnlineConsensusResults,
}
log.Trace(p.logExtraInfo(), "发出POS完成的req(完整区块)(to broadcast) leader", req.Header.Leader.Hex(), "次数", times, "高度", p.number)
p.pm.hd.SendNodeMsg(mc.HD_FullBlkReqToBroadcast, req, common.RoleBroadcast, nil)
}
}
func (p *Process) startVoteMsgSender(vote *mc.HD_ConsensusVote) {
p.closeVoteMsgSender()
sender, err := common.NewResendMsgCtrl(vote, p.sendVoteMsgFunc, manparams.BlkVoteSendInterval, manparams.BlkVoteSendTimes)
if err != nil {
log.Error(p.logExtraInfo(), "创建投票消息发送器", "失败", "err", err)
return
}
p.voteMsgSender = sender
}
func (p *Process) closeVoteMsgSender() {
if p.voteMsgSender == nil {
return
}
p.voteMsgSender.Close()
p.voteMsgSender = nil
}
func (p *Process) sendVoteMsgFunc(data interface{}, times uint32) {
vote, OK := data.(*mc.HD_ConsensusVote)
if !OK {
log.Error(p.logExtraInfo(), "发出投票消息", "反射消息失败")
return
}
//发送投票消息
if times == 1 {
log.Info(p.logExtraInfo(), "发出投票消息 signHash", vote.SignHash.TerminalString(), "高度", p.number)
} else {
log.Trace(p.logExtraInfo(), "发出投票消息 signHash", vote.SignHash.TerminalString(), "次数", times, "高度", p.number)
}
p.pm.hd.SendNodeMsg(mc.HD_BlkConsensusVote, vote, common.RoleValidator, nil)
}
|
package model
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Employee struct {
gorm.Model
Name string `gorm:"unique" json:"name"`
City string `json:"city"`
Age int `json:"age"`
Status bool `json:"status"`
}
func (e *Employee) Disable() {
e.Status = false
}
func (p *Employee) Enable() {
p.Status = true
}
// DBMigrate will create and migrate the tables, and then make the some relationships if necessary
func DBMigrate(db *gorm.DB) *gorm.DB {
db.AutoMigrate(&Employee{})
return db
} |
package main
import (
"database/sql"
"fmt"
"html/template"
"net/http"
"time"
"github.com/go-martini/martini"
_ "github.com/go-sql-driver/mysql"
"github.com/martini-contrib/sessions"
)
var wehackerDB *sql.DB
func runMysql(host string, user string, passwd string) {
loginInfo := user + ":" + passwd + "@tcp(" + host + ":3306)/wehacker?charset=utf8"
var err error
if wehackerDB, err = sql.Open("mysql", loginInfo); err != nil {
fmt.Println("can not connect to " + loginInfo)
}
if err = wehackerDB.Ping(); err != nil {
fmt.Println("DB connection is not alive: ", loginInfo)
}
wehackerDB.SetMaxIdleConns(0)
wehackerDB.SetMaxOpenConns(20)
return
}
func register(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
r.ParseForm()
user := r.Form["user"][0]
passwd := r.Form["passwd"][0]
db := wehackerDB
var err error
var userInfo *sql.Stmt
var rows *sql.Rows
if userInfo, err = db.Prepare("SELECT count(*) FROM `register_info` WHERE `user` = ?"); err != nil {
fmt.Println(err.Error())
return
}
defer userInfo.Close()
if rows, err = userInfo.Query(user); err != nil {
fmt.Println(err.Error())
}
defer rows.Close()
var count int
for rows.Next() {
if err = rows.Scan(&count); err != nil {
fmt.Println(err.Error())
return
} else if count != 0 {
fmt.Fprintf(w, `{"status":0}`)
fmt.Printf("this user has been registered, number is %d\n", count)
return
}
}
var newUser *sql.Stmt
if newUser, err = db.Prepare("INSERT INTO `register_info` (`user`,`passwd`,`created_at`) VALUES (?,?,?)"); err != nil {
return
}
defer newUser.Close()
if _, err = newUser.Exec(user, passwd, time.Now()); err != nil {
fmt.Println(err.Error())
}
fmt.Fprintf(w, `{"status":1}`)
return
}
func login(session sessions.Session, w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
r.ParseForm()
user := r.Form["user"][0]
passwd := r.Form["passwd"][0]
db := wehackerDB
var err error
var userInfo *sql.Stmt
var row *sql.Row
if userInfo, err = db.Prepare("SELECT passwd FROM `register_info` WHERE `user` = ?"); err != nil {
fmt.Println(err.Error())
return
}
defer userInfo.Close()
row = userInfo.QueryRow(user)
var tmp string
if err = row.Scan(&tmp); err != nil {
fmt.Fprintf(w, `{"id":0, "pw":0}`)
fmt.Println("no register info")
return
}
if tmp != passwd {
fmt.Fprintf(w, `{"id":1, "pw":0}`)
fmt.Println("passwd error")
return
}
session.Set("username", user)
fmt.Fprintf(w, `{"id":1, "pw":1}`)
return
}
func loginStatus(session sessions.Session, r *http.Request) string {
r.ParseForm()
var check string
var loginOut string
for k, v := range r.Form {
if k == "check" {
check = v[0]
}
if k == "loginOut" {
loginOut = v[0]
}
}
if check == "1" {
v := session.Get("username")
if v == nil {
return ""
} else {
return v.(string)
}
} else if loginOut == "1" {
session.Delete("username")
return "ok"
}
return ""
}
func index(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
t, _ := template.ParseFiles("templates/index.html", "templates/header.html", "templates/register.html", "templates/login.html", "templates/body.html")
t.Execute(w, nil)
return
}
func main() {
runMysql("127.0.0.1", "root", "")
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
store.Options(sessions.Options{MaxAge: 100})
m.Use(sessions.Sessions("my_session", store))
//m.Use(martini.Static("templates"))
m.Use(martini.Static("static"))
m.Post("/register", register)
m.Post("/login", login)
m.Get("/loginStatus", loginStatus)
m.Get("/get", func(session sessions.Session) string {
v := session.Get("username")
if v == nil {
return ""
}
return v.(string)
})
m.Get("/", index)
m.RunOnAddr(":80")
}
|
package models
import (
"context"
"database/sql"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/tristate"
"yunion.io/x/pkg/utils"
"yunion.io/x/sqlchemy"
"yunion.io/x/onecloud/pkg/apis/monitor"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/util/rbacutils"
"yunion.io/x/onecloud/pkg/util/stringutils2"
)
type SMetricFieldManager struct {
db.SEnabledResourceBaseManager
db.SStatusStandaloneResourceBaseManager
db.SScopedResourceBaseManager
}
type SMetricField struct {
//db.SVirtualResourceBase
db.SEnabledResourceBase
db.SStatusStandaloneResourceBase
db.SScopedResourceBase
DisplayName string `width:"256" list:"user" update:"user"`
Unit string `width:"32" list:"user" update:"user"`
ValueType string `width:"32" list:"user" update:"user"`
Score int `width:"32" list:"user" update:"user" default:"99"`
}
var MetricFieldManager *SMetricFieldManager
func init() {
MetricFieldManager = &SMetricFieldManager{
SStatusStandaloneResourceBaseManager: db.NewStatusStandaloneResourceBaseManager(
SMetricField{},
"metricfield_tbl",
"metricfield",
"metricfields",
),
}
MetricFieldManager.SetVirtualObject(MetricFieldManager)
}
func (manager *SMetricFieldManager) NamespaceScope() rbacutils.TRbacScope {
return rbacutils.ScopeSystem
}
func (manager *SMetricFieldManager) ListItemExportKeys(ctx context.Context, q *sqlchemy.SQuery,
userCred mcclient.TokenCredential, keys stringutils2.SSortedStrings) (*sqlchemy.SQuery, error) {
q, err := manager.SStatusStandaloneResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
if err != nil {
return nil, errors.Wrap(err, "SStatusStandaloneResourceBaseManager.ListItemExportKeys")
}
q, err = manager.SScopedResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
if err != nil {
return nil, errors.Wrap(err, "SScopedResourceBaseManager.ListItemExportKeys")
}
return q, nil
}
func (man *SMetricFieldManager) ValidateCreateData(
ctx context.Context, userCred mcclient.TokenCredential,
ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject,
data monitor.MetricFieldCreateInput) (monitor.MetricFieldCreateInput, error) {
return data, nil
}
func (field *SMetricField) ValidateUpdateData(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
data monitor.MetricFieldUpdateInput,
) (monitor.MetricFieldUpdateInput, error) {
if len(data.DisplayName) == 0 {
return data, errors.Wrap(httperrors.ErrNotEmpty, "display_name")
}
if len(data.Unit) == 0 {
return data, errors.Wrap(httperrors.ErrNotEmpty, "unit")
}
if !utils.IsInStringArray(data.Unit, monitor.MetricUnit) {
return data, errors.Wrap(httperrors.ErrBadRequest, "unit")
}
return data, nil
}
func (manager *SMetricFieldManager) ListItemFilter(
ctx context.Context, q *sqlchemy.SQuery,
userCred mcclient.TokenCredential,
query monitor.MetricFieldListInput,
) (*sqlchemy.SQuery, error) {
var err error
q, err = manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, query.StandaloneResourceListInput)
if err != nil {
return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.ListItemFilter")
}
q, err = manager.SEnabledResourceBaseManager.ListItemFilter(ctx, q, userCred, query.EnabledResourceBaseListInput)
if err != nil {
return nil, errors.Wrap(err, "SEnabledResourceBaseManager.ListItemFilter")
}
q, err = manager.SScopedResourceBaseManager.ListItemFilter(ctx, q, userCred,
query.ScopedResourceBaseListInput)
if err != nil {
return nil, errors.Wrap(err, "SScopedResourceBaseManager.ListItemFilter")
}
if len(query.DisplayName) != 0 {
//q = q.Equals("display_name", query.DisplayName)
q = q.Filter(sqlchemy.Like(q.Field("display_name"), query.DisplayName))
}
if len(query.Unit) != 0 {
q = q.Equals("unit", query.Unit)
}
return q, nil
}
func (man *SMetricFieldManager) FetchCustomizeColumns(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
objs []interface{},
fields stringutils2.SSortedStrings,
isList bool,
) []monitor.MetricFieldDetail {
rows := make([]monitor.MetricFieldDetail, len(objs))
return rows
}
func (man *SMetricFieldManager) OrderByExtraFields(
ctx context.Context,
q *sqlchemy.SQuery,
userCred mcclient.TokenCredential,
input monitor.AlertListInput,
) (*sqlchemy.SQuery, error) {
var err error
q, err = man.SStatusStandaloneResourceBaseManager.OrderByExtraFields(ctx, q, userCred, input.StatusStandaloneResourceListInput)
if err != nil {
return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.OrderByExtraFields")
}
q, err = man.SScopedResourceBaseManager.OrderByExtraFields(ctx, q, userCred, input.ScopedResourceBaseListInput)
if err != nil {
return nil, errors.Wrap(err, "SScopedResourceBaseManager.OrderByExtraFields")
}
return q, nil
}
func (manager *SMetricFieldManager) SaveMetricField(ctx context.Context, userCred mcclient.TokenCredential,
ownerId mcclient.IIdentityProvider, fieldInput monitor.MetricFieldCreateInput) (*SMetricField, error) {
field := new(SMetricField)
field.Name = fieldInput.Name
field.DisplayName = fieldInput.DisplayName
field.Description = fieldInput.Description
field.Unit = fieldInput.Unit
field.ValueType = fieldInput.ValueType
field.Enabled = tristate.True
field.SetModelManager(manager, field)
if err := manager.TableSpec().Insert(ctx, field); err != nil {
return nil, errors.Wrapf(err, "insert config %#v", field)
}
return field, nil
}
func (man *SMetricFieldManager) GetFieldByIdOrName(id string, userCred mcclient.TokenCredential) (*SMetricField, error) {
obj, err := man.FetchByIdOrName(userCred, id)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return obj.(*SMetricField), nil
}
func (self *SMetricField) CustomizeDelete(
ctx context.Context, userCred mcclient.TokenCredential,
query jsonutils.JSONObject, data jsonutils.JSONObject) error {
metricJoint, err := self.getMetricJoint()
if err != nil {
return err
}
for _, joint := range metricJoint {
if err := joint.Detach(ctx, userCred); err != nil {
return err
}
}
return nil
}
func (self *SMetricField) getMetricJoint() ([]SMetric, error) {
metricJoint := make([]SMetric, 0)
q := MetricManager.Query().Equals(MetricManager.GetSlaveFieldName(), self.Id)
if err := db.FetchModelObjects(MetricManager, q, &metricJoint); err != nil {
return nil, err
}
return metricJoint, nil
}
|
package errors
import (
"fmt"
"runtime"
"strings"
)
type Stacktrace []*StacktraceFrame
func (f Stacktrace) Caller() *StacktraceFrame {
return f[len(f)-1:][0]
}
func (f Stacktrace) String() string {
sb := &strings.Builder{}
for _, frame := range f {
sb.WriteString(fmt.Sprintf("%s\t%s:%d\n", frame.Function, frame.Filename, frame.Lineno))
}
return sb.String()
}
func (f Stacktrace) Strings() []string {
strs := make([]string, len(f))
for i, frame := range f {
strs[i] = fmt.Sprintf("%s %s:%d", frame.Function, frame.Filename, frame.Lineno)
}
return strs
}
type StacktraceFrame struct {
Filename string `json:"filename,omitempty"`
Function string `json:"function,omitempty"`
Module string `json:"module,omitempty"`
Lineno int `json:"lineno,omitempty"`
}
func (sf *StacktraceFrame) String() string {
return fmt.Sprintf("%s %s:%d", sf.Function, sf.Filename, sf.Lineno)
}
func NewStacktrace(skip int) Stacktrace {
var frames []*StacktraceFrame
callerPcs := make([]uintptr, 50)
numCallers := runtime.Callers(skip+2, callerPcs)
// If there are no callers, the entire stacktrace is nil
if numCallers == 0 {
return nil
}
callersFrames := runtime.CallersFrames(callerPcs)
for {
fr, more := callersFrames.Next()
frame := &StacktraceFrame{Filename: fr.File, Lineno: fr.Line}
frame.Module, frame.Function = functionName(fr.Function)
// `runtime.goexit` is effectively a placeholder that comes from
// runtime/asm_amd64.s and is meaningless.
if frame.Module == "runtime" && frame.Function == "goexit" {
frame = nil
}
if frame != nil {
frames = append(frames, frame)
}
if !more {
break
}
}
// If there are no frames, the entire stacktrace is nil
if len(frames) == 0 {
return nil
}
// Optimize the path where there's only 1 stacktrace
if len(frames) == 1 {
return frames
}
// Sentry wants the frames with the oldest first, so reverse them
for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {
frames[i], frames[j] = frames[j], frames[i]
}
return frames
}
func functionName(fName string) (pack string, name string) {
name = fName
// We get this:
// runtime/debug.*T·ptrmethod
// and want this:
// pack = runtime/debug
// name = *T.ptrmethod
if idx := strings.LastIndex(name, "."); idx != -1 {
pack = name[:idx]
name = name[idx+1:]
}
name = strings.Replace(name, "·", ".", -1)
return
}
|
package main
import (
"fmt"
"os"
"github.com/golang/glog"
)
type targetDirectory string
func (t targetDirectory) String() string {
return string(t)
}
func (t targetDirectory) IsValid() error {
if _, err := os.Stat(t.String()); err != nil {
glog.V(2).Infof("target %s invalid: %v", t, err)
return fmt.Errorf("target %s invalid: %v", t, err)
}
glog.V(2).Infof("target %s valid", t)
return nil
}
|
package factory
import (
"fmt"
"go_simpleweibo/app/models"
userModel "go_simpleweibo/app/models/user"
"go_simpleweibo/pkg/utils"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/bluele/factory-go/factory"
)
var (
// 头像假数据
avatars = []string{
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
"https://cdn.learnku.com/uploads/avatars/7850_1481780622.jpeg!/both/380x380",
}
)
func userFactory(i int) *factory.Factory {
u := &userModel.User{
Password: "123456",
EmailVerifiedAt: time.Now(),
Activated: models.TrueTinyint,
RememberToken: string(utils.RandomCreateBytes(10)),
}
// 第一个用户是管理员
if i == 0 {
u.IsAdmin = models.TrueTinyint
}
r := utils.RandInt(0, len(avatars)-1)
return factory.NewFactory(
u,
).Attr("Name", func(args factory.Args) (interface{}, error) {
return fmt.Sprintf("user-%d", i+1), nil
}).Attr("Avatar", func(args factory.Args) (interface{}, error) {
return avatars[r], nil
}).Attr("Email", func(args factory.Args) (interface{}, error) {
if i == 0 {
return "1@test.com", nil
}
return randomdata.Email(), nil
})
}
// UsersTableSeeder -
func UsersTableSeeder(needCleanTable bool) {
if needCleanTable {
DropAndCreateTable(&userModel.User{})
}
for i := 0; i < 100; i++ {
user := userFactory(i).MustCreate().(*userModel.User)
if err := user.Create(); err != nil {
fmt.Printf("mock user error: %v\n", err)
}
}
}
|
package models
import (
"github.com/astaxie/beego/orm"
"poetryAdmin/worker/app/tools"
"poetryAdmin/worker/core/define"
"time"
)
var TableCategory = "poetry_category"
type uintMaps map[uint32]Category
//poetry_category 诗文分类表
type Category struct {
Id int `orm:"column(id);auto"`
CatName string `orm:"column(cat_name)"`
SourceUrl string `orm:"column(source_url)"`
SourceUrlCrc32 uint32 `orm:"column(source_url_crc32)"`
ShowPosition int `orm:"column(show_position)"`
Pid int `orm:"column(pid)"`
AddDate int64 `orm:"column(add_date)"`
LastUpdateTime int64 `orm:"column(last_update_time)"`
}
func init() {
orm.RegisterModel(new(Category))
}
func (c *Category) TableName() string {
return TableCategory
}
//保存更新分类
func InsertMultiCategoryByDataMap(data define.DataMap) (i int64, err error) {
var (
categorys []Category
)
for _, ret := range data {
if ret.Text == "更多>>" {
continue
}
category := Category{
CatName: ret.Text,
SourceUrl: ret.Href,
SourceUrlCrc32: tools.Crc32(ret.Href),
ShowPosition: int(ret.ShowPosition),
AddDate: time.Now().Unix(),
LastUpdateTime: time.Now().Unix(),
}
categories, _ := GetDataByCateName(category.CatName, category.ShowPosition)
if categories.Id > 0 {
category.Id = categories.Id
_, _ = orm.NewOrm().Update(&category, "cat_name", "source_url", "source_url_crc32", "show_position", "pid", "last_update_time")
category.Id = 0
} else {
categorys = append(categorys, category)
}
}
if len(categorys) > 0 {
i, err = orm.NewOrm().InsertMulti(len(categorys), categorys)
}
return
}
//根据位置查询分类数据
func GetCategoryDataByPosition(showPosition define.ShowPosition) (maps uintMaps, err error) {
var categorys []Category
maps = make(uintMaps)
_, err = orm.NewOrm().QueryTable(TableCategory).Filter("show_position", showPosition).All(&categorys, "id", "cat_name", "source_url", "pid", "source_url_crc32")
if len(categorys) > 0 {
for _, val := range categorys {
maps[val.SourceUrlCrc32] = val
}
}
return
}
//根据分类名和位置查询数据
func GetDataByCateName(cateName string, position int) (categorys Category, err error) {
_, err = orm.NewOrm().QueryTable(TableCategory).Filter("show_position", position).Filter("cat_name", cateName).All(&categorys, "id")
return categorys, err
}
//根据分类名和位置和PID查询数据
func GetDataByCateNameAndPid(cateName string, position int, pid int) (category Category, err error) {
_, err = orm.NewOrm().QueryTable(TableCategory).Filter("show_position", position).Filter("cat_name", cateName).Filter("pid", pid).All(&category, "id")
return category, err
}
//保存分类数据
func SaveCategoryData(data *Category) (id int64, err error) {
id, err = orm.NewOrm().Insert(data)
return
}
|
package hy
import (
"fmt"
"html/template"
"strings"
"sync"
"github.com/bokwoon95/erro"
"github.com/microcosm-cc/bluemonday"
)
// https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
var singletonElements = map[string]struct{}{
"AREA": {}, "BASE": {}, "BR": {}, "COL": {}, "EMBED": {}, "HR": {}, "IMG": {}, "INPUT": {},
"LINK": {}, "META": {}, "PARAM": {}, "SOURCE": {}, "TRACK": {}, "WBR": {},
}
var bufpool = sync.Pool{
New: func() interface{} { return &strings.Builder{} },
}
const Enabled = "\x00"
const Disabled = "\x01"
type Element interface {
AppendHTML(*strings.Builder) error
}
type Attr map[string]string
type Sanitizer interface {
Sanitize(string) string
}
var defaultSanitizer = func() Sanitizer {
p := bluemonday.UGCPolicy()
p.AllowStyling()
p.AllowDataAttributes()
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attributes
p.AllowElements("form")
p.AllowAttrs("accept-charset", "autocomplete", "name", "rel", "action", "enctype", "method", "novalidate", "target").OnElements("form")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes
p.AllowElements("input")
p.AllowAttrs(
"accept", "alt", "autocomplete", "autofocus", "capture", "checked",
"dirname", "disabled", "form", "formaction", "formenctype", "formmethod",
"formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min",
"minlength", "multiple", "name", "pattern", "placeholder", "readonly",
"required", "size", "src", "step", "type", "value", "width",
).OnElements("input")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attributes
p.AllowElements("button")
p.AllowAttrs(
"autofocus", "disabled", "form", "formaction", "formenctype",
"formmethod", "formnovalidate", "formtarget", "name", "type", "value",
).OnElements("button")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attributes
p.AllowElements("label")
p.AllowAttrs("for").OnElements("label")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attributes
p.AllowElements("select")
p.AllowAttrs("autocomplete", "autofocus", "disabled", "form", "multiple", "name", "required", "size").OnElements("select")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#attributes
p.AllowElements("option")
p.AllowAttrs("disabled", "label", "selected", "value").OnElements("option")
// https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode
p.AllowAttrs("inputmode").Globally()
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attributes
p.AllowElements("link")
p.AllowAttrs(
"as", "crossorigin", "disabled", "href", "hreflang", "imagesizes",
"imagesrcset", "media", "rel", "sizes", "title", "type",
).OnElements("link")
p.AllowStandardURLs()
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attributes
p.AllowElements("script")
p.AllowAttrs("async", "crossorigin", "defer", "integrity", "nomodule", "nonce", "referrerpolicy", "src", "type").OnElements("script")
p.AllowElements("svg")
p.AllowImages()
p.AllowLists()
p.AllowTables()
// settings which bluemonday loves to turn back on, leave it for the last
p.RequireNoFollowOnLinks(false)
return p
}()
type Attributes struct {
ParseErr error
Selector string
Tag string
ID string
Class string
Dict map[string]string
}
func ParseAttributes(selector string, attributes map[string]string) Attributes {
type State int
const (
StateNone State = iota
StateTag
StateID
StateClass
StateAttrName
StateAttrValue
)
attrs := Attributes{Selector: selector, Dict: make(map[string]string)}
defer func() {
if attrs.ParseErr != nil {
for k, v := range attributes {
attrs.Dict[k] = v
}
}
}()
state := StateTag
var classes []string
var name []rune
var value []rune
for _, c := range selector {
if c == '#' || c == '.' || c == '[' {
switch state {
case StateTag:
attrs.Tag = string(value)
case StateID:
attrs.ID = string(value)
case StateClass:
if len(value) > 0 {
classes = append(classes, string(value))
}
case StateAttrName, StateAttrValue:
attrs.ParseErr = erro.Wrap(fmt.Errorf("unclosed attribute"))
return attrs
}
value = value[:0]
switch c {
case '#':
state = StateID
case '.':
state = StateClass
case '[':
state = StateAttrName
}
continue
}
if c == '=' {
switch state {
case StateAttrName:
state = StateAttrValue
default:
attrs.ParseErr = erro.Wrap(fmt.Errorf("unopened attribute"))
return attrs
}
continue
}
if c == ']' {
switch state {
case StateAttrName:
if _, ok := attrs.Dict[string(name)]; ok {
break
}
attrs.Dict[string(name)] = Enabled
case StateAttrValue:
if _, ok := attrs.Dict[string(name)]; ok {
break
}
attrs.Dict[string(name)] = string(value)
default:
attrs.ParseErr = erro.Wrap(fmt.Errorf("unopened attribute"))
return attrs
}
name = name[:0]
value = value[:0]
state = StateNone
continue
}
switch state {
case StateTag, StateID, StateClass, StateAttrValue:
value = append(value, c)
case StateAttrName:
name = append(name, c)
case StateNone:
attrs.ParseErr = erro.Wrap(fmt.Errorf("unknown state (please prepend with '#', '.' or '['"))
return attrs
}
}
// flush value
if len(value) > 0 {
switch state {
case StateTag:
attrs.Tag = string(value)
case StateID:
attrs.ID = string(value)
case StateClass:
classes = append(classes, string(value))
case StateNone: // do nothing i.e. drop the value
case StateAttrName, StateAttrValue:
attrs.ParseErr = erro.Wrap(fmt.Errorf("unclosed attribute"))
return attrs
}
value = value[:0]
}
if len(classes) > 0 {
attrs.Class = strings.Join(classes, " ")
}
for name, value := range attributes {
switch name {
case "id":
attrs.ID = value
case "class":
if value != "" {
attrs.Class += " " + value
}
default:
attrs.Dict[name] = value
}
}
return attrs
}
func AppendHTML(buf *strings.Builder, attrs Attributes, children []Element) error {
var err error
if attrs.ParseErr != nil {
return erro.Wrap(attrs.ParseErr)
}
if attrs.Tag != "" {
buf.WriteString(`<` + attrs.Tag)
} else {
buf.WriteString(`<div`)
}
if attrs.ID != "" {
buf.WriteString(` id="` + attrs.ID + `"`)
}
if attrs.Class != "" {
buf.WriteString(` class="` + attrs.Class + `"`)
}
for name, value := range attrs.Dict {
switch value {
case Enabled:
buf.WriteString(` ` + name)
case Disabled:
continue
default:
buf.WriteString(` ` + name + `="` + value + `"`)
}
}
buf.WriteString(`>`)
if _, ok := singletonElements[strings.ToUpper(attrs.Tag)]; !ok {
for _, child := range children {
err = child.AppendHTML(buf)
if err != nil {
return erro.Wrap(err)
}
}
buf.WriteString("</" + attrs.Tag + ">")
}
return nil
}
func MarshalElement(s Sanitizer, el Element) (template.HTML, error) {
buf := bufpool.Get().(*strings.Builder)
defer func() {
buf.Reset()
bufpool.Put(buf)
}()
err := el.AppendHTML(buf)
if err != nil {
return "", erro.Wrap(err)
}
if s == nil {
s = defaultSanitizer
}
output := s.Sanitize(buf.String())
return template.HTML(output), nil
}
type ElementMap map[*template.HTML]Element
func MarshalElements(s Sanitizer, elements map[*template.HTML]Element) error {
var err error
for dest, element := range elements {
if dest == nil {
continue
}
*dest, err = MarshalElement(s, element)
if err != nil {
return erro.Wrap(err)
}
}
return nil
}
|
package main
import (
"fmt"
"os"
"sync"
"time"
)
type secret struct {
RWM sync.RWMutex
M sync.Mutex
password string
}
var Password = secret{password: "root"}
// 通过rwmutex写
func Change(s *secret, pass string) {
s.RWM.Lock()
fmt.Println("Change with rwmutex lock")
time.Sleep(3 * time.Second)
s.password = pass
s.RWM.Unlock()
}
func rwMutexShow(s *secret) string {
s.RWM.RLock()
defer s.RWM.RUnlock()
fmt.Println("show with rwmutex",time.Now().Second())
time.Sleep(1 * time.Second)
return s.password
}
// 通过mutex读,和rwMutexShow的唯一区别在于锁的方式不同
func mutexShow(s *secret) string {
s.M.Lock()
defer s.M.Unlock()
fmt.Println("show with mutex",time.Now().Second())
time.Sleep(1 * time.Second)
return s.password
}
func main() {
var show = func(s *secret) string {return ""}
// 通过变量赋值的方式,选择并重写showFunc函数
if len(os.Args) != 2 {
fmt.Println("Using sync.RWMutex!",time.Now().Second())
show = rwMutexShow
} else {
fmt.Println("Using sync.Mutex!",time.Now().Second())
show = mutexShow
}
var wg sync.WaitGroup
// 激活5个goroutine,每个goroutine都查看
// 根据选择的函数不同,showFunc()加锁的方式不同
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Go Pass:", show(&Password),time.Now().Second())
}()
}
// 激活一个申请写锁的goroutine
go func() {
wg.Add(1)
defer wg.Done()
Change(&Password, "123456")
}()
wg.Wait()
}
|
package utils
import (
"fmt"
"os"
)
func ShowErrorMessage() {
fmt.Println("Please, select a valid option: 1, 2 or 0")
os.Exit(-1)
} |
// Copyright 2019 The Berglas 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 berglas
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"cloud.google.com/go/iam"
"github.com/sethvargo/go-retry"
"google.golang.org/api/googleapi"
storagev1 "google.golang.org/api/storage/v1"
iampb "google.golang.org/genproto/googleapis/iam/v1"
grpccodes "google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
)
const (
iamObjectReader = "roles/storage.legacyObjectReader"
iamKMSDecrypt = "roles/cloudkms.cryptoKeyDecrypter"
)
// storageIAM returns an IAM storage handle to the given object since one does
// not exist in the storage library.
func (c *Client) storageIAM(bucket, object string) *iam.Handle {
return iam.InternalNewHandleClient(&storageIAMClient{
raw: c.storageIAMClient,
}, bucket+"/"+object)
}
// storageIAMClient implements the iam.client interface.
type storageIAMClient struct {
raw *storagev1.Service
}
func (c *storageIAMClient) Get(ctx context.Context, resource string) (*iampb.Policy, error) {
return c.GetWithVersion(ctx, resource, 1)
}
func (c *storageIAMClient) GetWithVersion(ctx context.Context, resource string, version int32) (*iampb.Policy, error) {
bucket, object, err := parseBucketObj(resource)
if err != nil {
return nil, err
}
// Note: Object-level IAM does not support versioned IAM policies at present.
call := c.raw.Objects.GetIamPolicy(bucket, object)
setClientHeader(call.Header())
rp, err := call.Context(ctx).Do()
if err != nil {
return nil, err
}
return iamFromStoragePolicy(rp), nil
}
func (c *storageIAMClient) Set(ctx context.Context, resource string, p *iampb.Policy) error {
bucket, object, err := parseBucketObj(resource)
if err != nil {
return err
}
rp := iamToStoragePolicy(p)
call := c.raw.Objects.SetIamPolicy(bucket, object, rp)
setClientHeader(call.Header())
if _, err := call.Context(ctx).Do(); err != nil {
return err
}
return nil
}
func (c *storageIAMClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) {
bucket, object, err := parseBucketObj(resource)
if err != nil {
return nil, err
}
call := c.raw.Objects.TestIamPermissions(bucket, object, perms)
setClientHeader(call.Header())
res, err := call.Context(ctx).Do()
if err != nil {
return nil, err
}
return res.Permissions, nil
}
// parseBucketObj parses a bucket, object tuple
func parseBucketObj(s string) (string, string, error) {
s = strings.TrimPrefix(s, "gs://")
ss := strings.SplitN(s, "/", 2)
if len(ss) < 2 {
return "", "", fmt.Errorf("does not match bucket/object format: %s", s)
}
return ss[0], ss[1], nil
}
func iamToStoragePolicy(ip *iampb.Policy) *storagev1.Policy {
return &storagev1.Policy{
Bindings: iamToStorageBindings(ip.Bindings),
Etag: string(ip.Etag),
}
}
func iamToStorageBindings(ibs []*iampb.Binding) []*storagev1.PolicyBindings {
var rbs []*storagev1.PolicyBindings
for _, ib := range ibs {
rbs = append(rbs, &storagev1.PolicyBindings{
Role: ib.Role,
Members: ib.Members,
})
}
return rbs
}
func iamFromStoragePolicy(rp *storagev1.Policy) *iampb.Policy {
return &iampb.Policy{
Bindings: iamFromStorageBindings(rp.Bindings),
Etag: []byte(rp.Etag),
}
}
func iamFromStorageBindings(rbs []*storagev1.PolicyBindings) []*iampb.Binding {
var ibs []*iampb.Binding
for _, rb := range rbs {
ibs = append(ibs, &iampb.Binding{
Role: rb.Role,
Members: rb.Members,
})
}
return ibs
}
func setClientHeader(h http.Header) {
h.Set("User-Agent", userAgent)
}
// getIAMPolicy fetches the IAM policy for the given resource handle, handling
// any transient errors or conflicts and automatically retrying.
func getIAMPolicy(ctx context.Context, h *iam.Handle) (*iam.Policy, error) {
var policy *iam.Policy
if err := iamRetry(ctx, func(ctx context.Context) error {
rPolicy, err := h.Policy(ctx)
if err != nil {
return err
}
policy = rPolicy
return nil
}); err != nil {
return nil, err
}
return policy, nil
}
// updateIAMPolicy gets the existing IAM policy, applies the modifications from
// f, and attempts to set the new policy, retrying and accounting for transient
// errors.
func updateIAMPolicy(ctx context.Context, h *iam.Handle, f func(*iam.Policy) *iam.Policy) error {
return iamRetry(ctx, func(ctx context.Context) error {
// Get existing policy
existingPolicy, err := h.Policy(ctx)
if err != nil {
return err
}
// Mutate policy
newPolicy := f(existingPolicy)
// Put new policy
if err := h.SetPolicy(ctx, newPolicy); err != nil {
return err
}
return nil
})
}
// iamRetry is a helper function that executes the given function with retries,
// handling IAM-specific retry conditions.
func iamRetry(ctx context.Context, f retry.RetryFunc) error {
b := retry.WithMaxRetries(5, retry.NewFibonacci(250*time.Millisecond))
return retry.Do(ctx, b, func(ctx context.Context) error {
err := f(ctx)
if err == nil {
return nil
}
// IAM gRPC returns 10 on conflicts
if terr, ok := grpcstatus.FromError(err); ok && terr.Code() == grpccodes.Aborted {
return retry.RetryableError(err)
}
// IAM returns 412 while propagating, also retry on server errors
if terr, ok := err.(*googleapi.Error); ok && (terr.Code == 412 || terr.Code >= 500) {
return retry.RetryableError(err)
}
return err
})
}
|
package controllers
import (
"github.com/gin-gonic/gin"
"github.com/google/wire"
"PMSApp/app/models"
"PMSApp/app/utils"
"go.uber.org/zap"
)
// LoginSet Login DI
var LoginSet = wire.NewSet(wire.Struct(new(Login), "*"))
// Login 登录结构体
type Login struct {
Logger *zap.Logger
Util utils.Ginx
UserModel models.IUser
}
// 登录结构体
type loginSchema struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// Login 登录方法
func (l *Login) Login(c *gin.Context) {
var data loginSchema
if err := l.Util.ParseJSON(c, &data); err != nil {
l.Util.FailWarp(c, utils.ErrBodyCanNotParser)
return
}
err, userInfo := l.UserModel.Login(data.Username, data.Password)
if err != nil {
l.Logger.Warn("服务处理失败", zap.Error(err))
l.Util.FailWarp(c, err)
return
}
l.Util.SuccessWarp(c, userInfo)
}
|
package node
import (
"bytes"
"encoding/hex"
"errors"
"github.com/frankh/rai"
"github.com/frankh/rai/address"
"github.com/frankh/rai/blocks"
"github.com/frankh/rai/uint128"
)
type MessageBlockOpen struct {
Source [32]byte
Representative [32]byte
Account [32]byte
MessageCommon
}
type MessageBlockSend struct {
Previous [32]byte
Destination [32]byte
Balance [16]byte
MessageCommon
}
func (m *MessageBlockOpen) ToBlock() *blocks.OpenBlock {
common := blocks.CommonBlock{
rai.Work(hex.EncodeToString(m.Work[:])),
rai.Signature(hex.EncodeToString(m.Signature[:])),
}
block := blocks.OpenBlock{
rai.BlockHash(hex.EncodeToString(m.Source[:])),
address.PubKeyToAddress(m.Representative[:]),
address.PubKeyToAddress(m.Account[:]),
common,
}
return &block
}
func (m *MessageBlockSend) ToBlock() *blocks.SendBlock {
common := blocks.CommonBlock{
rai.Work(hex.EncodeToString(m.Work[:])),
rai.Signature(hex.EncodeToString(m.Signature[:])),
}
block := blocks.SendBlock{
rai.BlockHash(hex.EncodeToString(m.Previous[:])),
address.PubKeyToAddress(m.Destination[:]),
uint128.FromBytes(m.Balance[:]),
common,
}
return &block
}
func (m *MessagePublishOpen) Read(buf *bytes.Buffer) error {
err1 := m.MessageHeader.ReadHeader(buf)
if m.MessageHeader.BlockType != BlockType_open {
return errors.New("Wrong blocktype")
}
n2, err2 := buf.Read(m.Source[:])
n3, err3 := buf.Read(m.Representative[:])
n4, err4 := buf.Read(m.Account[:])
err5 := m.MessageCommon.ReadCommon(buf)
if err1 != nil || err2 != nil || err3 != nil || err4 != nil || err5 != nil {
return errors.New("Failed to read header")
}
if n2 != 32 || n3 != 32 || n4 != 32 {
return errors.New("Wrong number of bytes read")
}
return nil
}
func (m *MessagePublishOpen) Write(buf *bytes.Buffer) error {
err1 := m.MessageHeader.WriteHeader(buf)
n2, err2 := buf.Write(m.Source[:])
n3, err3 := buf.Write(m.Representative[:])
n4, err4 := buf.Write(m.Account[:])
err5 := m.MessageCommon.WriteCommon(buf)
if err1 != nil || err2 != nil || err3 != nil || err4 != nil || err5 != nil {
return errors.New("Failed to write header")
}
if n2 != 32 || n3 != 32 || n4 != 32 {
return errors.New("Wrong number of bytes written")
}
return nil
}
func (m *MessagePublishSend) Read(buf *bytes.Buffer) error {
err1 := m.MessageHeader.ReadHeader(buf)
if m.MessageHeader.BlockType != BlockType_send {
return errors.New("Wrong blocktype")
}
n2, err2 := buf.Read(m.Previous[:])
n3, err3 := buf.Read(m.Destination[:])
n4, err4 := buf.Read(m.Balance[:])
err5 := m.MessageCommon.ReadCommon(buf)
if err1 != nil || err2 != nil || err3 != nil || err4 != nil || err5 != nil {
return errors.New("Failed to read header")
}
if n2 != 32 || n3 != 32 || n4 != 16 {
return errors.New("Wrong number of bytes read")
}
return nil
}
func (m *MessagePublishSend) Write(buf *bytes.Buffer) error {
err1 := m.MessageHeader.WriteHeader(buf)
n2, err2 := buf.Write(m.Previous[:])
n3, err3 := buf.Write(m.Destination[:])
n4, err4 := buf.Write(m.Balance[:])
err5 := m.MessageCommon.WriteCommon(buf)
if err1 != nil || err2 != nil || err3 != nil || err4 != nil || err5 != nil {
return errors.New("Failed to write header")
}
if n2 != 32 || n3 != 32 || n4 != 16 {
return errors.New("Wrong number of bytes written")
}
return nil
}
|
// Copyright 2016 Apcera Inc. All rights reserved.
package gcp
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
"context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
googlecloud "google.golang.org/api/compute/v1"
googleresourcemanager "google.golang.org/api/cloudresourcemanager/v1"
)
var (
// OAuth token url.
tokenURL = "https://accounts.google.com/o/oauth2/token"
)
type googleService struct {
vm *VM
service *googlecloud.Service
}
// googleResManService represents a service that is used to call Google cloud
// resource manger APIs.
type googleResManService struct {
// account represents the Google cloud account that is used to make
// calls to Google cloud resource manager APIs.
account *Account
// service: represents an object that contains an http client that is
// used to make calls to Google cloud resource manager APIs.
service *googleresourcemanager.Service
}
// accountFile represents the structure of the account file JSON file.
type accountFile struct {
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
ClientId string `json:"client_id"`
}
// getResManService processes the account file and returns the service object
// to make API calls
func (acc *Account) getResManService() (*googleResManService, error) {
var err error
var client *http.Client
if err = parseAccountFile(&acc.account, acc.AccountFile); err != nil {
return nil, err
}
// Auth with AccountFile first if provided
if acc.account.PrivateKey != "" {
config := jwt.Config{
Email: acc.account.ClientEmail,
PrivateKey: []byte(acc.account.PrivateKey),
Scopes: acc.Scopes,
TokenURL: tokenURL,
}
client = config.Client(context.Background())
} else {
client = &http.Client{
Timeout: time.Duration(30 * time.Second),
Transport: &oauth2.Transport{
Source: google.ComputeTokenSource(""),
},
}
}
svc, err := googleresourcemanager.New(client)
if err != nil {
return nil, err
}
return &googleResManService{acc, svc}, nil
}
func (vm *VM) getService() (*googleService, error) {
var err error
var client *http.Client
if err = parseAccountFile(&vm.account, vm.AccountFile); err != nil {
return nil, err
}
// Auth with AccountFile first if provided
if vm.account.PrivateKey != "" {
config := jwt.Config{
Email: vm.account.ClientEmail,
PrivateKey: []byte(vm.account.PrivateKey),
Scopes: vm.Scopes,
TokenURL: tokenURL,
}
client = config.Client(oauth2.NoContext)
} else {
client = &http.Client{
Timeout: time.Duration(30 * time.Second),
Transport: &oauth2.Transport{
Source: google.ComputeTokenSource(""),
},
}
}
svc, err := googlecloud.New(client)
if err != nil {
return nil, err
}
return &googleService{vm, svc}, nil
}
// get instance from current VM definition.
func (svc *googleService) getInstance() (*googlecloud.Instance, error) {
return svc.service.Instances.Get(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
}
// waitForOperation pulls to wait for the operation to finish.
func waitForOperation(timeout int, funcOperation func() (*googlecloud.Operation, error)) error {
var op *googlecloud.Operation
var err error
for i := 0; i < timeout; i++ {
op, err = funcOperation()
if err != nil {
return err
}
if op.Status == "DONE" {
if op.Error != nil {
return fmt.Errorf("operation error: %v", *op.Error.Errors[0])
}
return nil
}
time.Sleep(1 * time.Second)
}
return fmt.Errorf("operation timeout, operations status: %v", op.Status)
}
// waitForOperationReady waits for the regional operation to finish.
func (svc *googleService) waitForOperationReady(operation string) error {
return waitForOperation(OperationTimeout, func() (*googlecloud.Operation, error) {
return svc.service.ZoneOperations.Get(svc.vm.Project, svc.vm.Zone, operation).Do()
})
}
// waitForGlobalOperationReady waits for a global operation to finish.
func (svc *googleService) waitForGlobalOperationReady(operation string) error {
return waitForOperation(OperationTimeout, func() (*googlecloud.Operation, error) {
return svc.service.GlobalOperations.Get(svc.vm.Project, operation).Do()
})
}
func (svc *googleService) getImage() (*googlecloud.Image, error) {
for _, img := range svc.vm.ImageProjects {
image, err := svc.service.Images.Get(img, svc.vm.SourceImage).Do()
if err == nil && image != nil && image.SelfLink != "" {
return image, nil
}
image = nil
}
err := fmt.Errorf("could not find image %s in these projects: %s", svc.vm.SourceImage, svc.vm.ImageProjects)
return nil, err
}
// createDisks creates non-booted disk.
func (svc *googleService) createDisks() (disks []*googlecloud.AttachedDisk, err error) {
if len(svc.vm.Disks) == 0 {
return nil, errors.New("no disks were found")
}
image, err := svc.getImage()
if err != nil {
return nil, err
}
for i, disk := range svc.vm.Disks {
if i == 0 {
// First one is booted device, it will created in VM provision stage
disks = append(disks, &googlecloud.AttachedDisk{
Type: "PERSISTENT",
Mode: "READ_WRITE",
Kind: "compute#attachedDisk",
Boot: true,
AutoDelete: disk.AutoDelete,
InitializeParams: &googlecloud.AttachedDiskInitializeParams{
SourceImage: image.SelfLink,
DiskSizeGb: int64(disk.DiskSizeGb),
DiskType: fmt.Sprintf("zones/%s/diskTypes/%s", svc.vm.Zone, disk.DiskType),
},
})
continue
}
// Reuse the existing disk, create non-booted devices if it does not exist
searchDisk, _ := svc.getDisk(disk.Name)
if searchDisk == nil {
d := &googlecloud.Disk{
Name: disk.Name,
SizeGb: int64(disk.DiskSizeGb),
Type: fmt.Sprintf("zones/%s/diskTypes/%s", svc.vm.Zone, disk.DiskType),
}
op, err := svc.service.Disks.Insert(svc.vm.Project, svc.vm.Zone, d).Do()
if err != nil {
return disks, fmt.Errorf("error while creating disk %s: %v", disk.Name, err)
}
err = svc.waitForOperationReady(op.Name)
if err != nil {
return disks, fmt.Errorf("error while waiting for the disk %s ready, error: %v", disk.Name, err)
}
}
disks = append(disks, &googlecloud.AttachedDisk{
DeviceName: disk.Name,
Type: "PERSISTENT",
Mode: "READ_WRITE",
Boot: false,
AutoDelete: disk.AutoDelete,
Source: fmt.Sprintf("projects/%s/zones/%s/disks/%s", svc.vm.Project, svc.vm.Zone, disk.Name),
})
}
return disks, nil
}
// getDisk retrieves the Disk object.
func (svc *googleService) getDisk(name string) (*googlecloud.Disk, error) {
return svc.service.Disks.Get(svc.vm.Project, svc.vm.Zone, name).Do()
}
// deleteDisk deletes the persistent disk.
func (svc *googleService) deleteDisk(name string) error {
op, err := svc.service.Disks.Delete(svc.vm.Project, svc.vm.Zone, name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// deleteDisks deletes all the persistent disk.
func (svc *googleService) deleteDisks() (errs []error) {
for _, disk := range svc.vm.Disks {
err := svc.deleteDisk(disk.Name)
if err != nil {
errs = append(errs, err)
}
}
return errs
}
// getIPs returns the IP addresses of the GCE instance.
func (svc *googleService) getIPs() ([]net.IP, error) {
instance, err := svc.service.Instances.Get(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
if err != nil {
return nil, err
}
ips := make([]net.IP, 2)
nic := instance.NetworkInterfaces[0]
publicIP := nic.AccessConfigs[0].NatIP
if publicIP == "" {
return nil, errors.New("error while retrieving public IP")
}
privateIP := nic.NetworkIP
if privateIP == "" {
return nil, errors.New("error while retrieving private IP")
}
ips[PublicIP] = net.ParseIP(publicIP)
ips[PrivateIP] = net.ParseIP(privateIP)
return ips, nil
}
// provision a new googlecloud VM instance.
func (svc *googleService) provision() error {
zone, err := svc.service.Zones.Get(svc.vm.Project, svc.vm.Zone).Do()
if err != nil {
return err
}
machineType, err := svc.service.MachineTypes.Get(svc.vm.Project, zone.Name, svc.vm.MachineType).Do()
if err != nil {
return err
}
network, err := svc.service.Networks.Get(svc.vm.Project, svc.vm.Network).Do()
if err != nil {
return err
}
// validate network
if !network.AutoCreateSubnetworks && len(network.Subnetworks) > 0 {
// Network appears to be in "custom" mode, so a subnetwork is required
// libretto doesn't handle the network creation
if svc.vm.Subnetwork == "" {
return fmt.Errorf("a subnetwork must be specified")
}
}
subnetworkSelfLink := ""
if svc.vm.Subnetwork != "" {
subnetwork, err := svc.service.Subnetworks.Get(svc.vm.Project, svc.vm.region(), svc.vm.Subnetwork).Do()
if err != nil {
return err
}
subnetworkSelfLink = subnetwork.SelfLink
}
accessconfig := googlecloud.AccessConfig{
Name: "External NAT for Libretto",
Type: "ONE_TO_ONE_NAT",
}
md := svc.getSSHKey()
disks, err := svc.createDisks()
if err != nil {
return err
}
instance := &googlecloud.Instance{
Name: svc.vm.Name,
Description: svc.vm.Description,
Disks: disks,
MachineType: machineType.SelfLink,
Metadata: &googlecloud.Metadata{
Items: []*googlecloud.MetadataItems{
{
Key: "sshKeys",
Value: &md,
},
},
},
NetworkInterfaces: []*googlecloud.NetworkInterface{
{
AccessConfigs: []*googlecloud.AccessConfig{
&accessconfig,
},
Network: network.SelfLink,
Subnetwork: subnetworkSelfLink,
NetworkIP: svc.vm.PrivateIPAddress,
},
},
Scheduling: &googlecloud.Scheduling{
Preemptible: svc.vm.Preemptible,
},
ServiceAccounts: []*googlecloud.ServiceAccount{
{
Email: "default",
Scopes: svc.vm.Scopes,
},
},
Tags: &googlecloud.Tags{
Items: svc.vm.Tags,
},
}
op, err := svc.service.Instances.Insert(svc.vm.Project, zone.Name, instance).Do()
if err != nil {
return err
}
if err = svc.waitForOperationReady(op.Name); err != nil {
return err
}
_, err = svc.getInstance()
return err
}
// start starts a stopped GCE instance.
func (svc *googleService) start() error {
instance, err := svc.getInstance()
if err != nil {
if !strings.Contains(err.Error(), "no instance found") {
return err
}
}
if instance == nil {
return errors.New("no instance found")
}
op, err := svc.service.Instances.Start(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// stop halts a GCE instance.
func (svc *googleService) stop() error {
_, err := svc.getInstance()
if err != nil {
if !strings.Contains(err.Error(), "no instance found") {
return err
}
return fmt.Errorf("no instance found, %v", err)
}
op, err := svc.service.Instances.Stop(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// deletes the GCE instance.
func (svc *googleService) delete() error {
op, err := svc.service.Instances.Delete(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// extract the region from zone name.
func (vm *VM) region() string {
return vm.Zone[:len(vm.Zone)-2]
}
func parseAccountJSON(result interface{}, jsonText string) error {
dec := json.NewDecoder(strings.NewReader(jsonText))
return dec.Decode(result)
}
func parseAccountFile(file *accountFile, account string) error {
if err := parseAccountJSON(file, account); err != nil {
if _, err = os.Stat(account); os.IsNotExist(err) {
return fmt.Errorf("error finding account file: %s", account)
}
bytes, err := ioutil.ReadFile(account)
if err != nil {
return fmt.Errorf("error reading account file from path '%s': %s", file, err)
}
err = parseAccountJSON(file, string(bytes))
if err != nil {
return fmt.Errorf("error parsing account file: %s", err)
}
}
return nil
}
func (svc *googleService) getSSHKey() string {
return fmt.Sprintf("%s:%s\n", svc.vm.SSHCreds.SSHUser, svc.vm.SSHPublicKey)
}
func (svc *googleService) insertSSHKey() error {
md := svc.getSSHKey()
instance, err := svc.getInstance()
if err != nil {
return err
}
op, err := svc.service.Instances.SetMetadata(svc.vm.Project, svc.vm.Zone, svc.vm.Name, &googlecloud.Metadata{
Fingerprint: instance.Metadata.Fingerprint,
Items: []*googlecloud.MetadataItems{
{
Key: "sshKeys",
Value: &md,
},
},
}).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// getNetworkList gets the list of networks from the given project
func (svc *googleService) getNetworkList() ([]*googlecloud.Network, error) {
networkList, err := svc.service.Networks.List(svc.vm.Project).Do()
if err != nil {
return nil, err
}
return networkList.Items, nil
}
// getSubnetworkList gets the list of subnets for the given combination of
// project and region
func (svc *googleService) getSubnetworkList() ([]*googlecloud.Subnetwork, error) {
subnetworkList, err := svc.service.Subnetworks.List(svc.vm.Project, svc.vm.region()).Do()
if err != nil {
return nil, err
}
return subnetworkList.Items, nil
}
// getMachineTypeList gets the list of machine types (aka flavors) for the
// given project in the given zone
func (svc *googleService) getMachineTypeList() ([]*googlecloud.MachineType, error) {
machineTypeList, err := svc.service.MachineTypes.List(svc.vm.Project, svc.vm.Zone).Do()
if err != nil {
return nil, err
}
return machineTypeList.Items, nil
}
// getZoneList gets the list of zones
func (svc *googleService) getZoneList() ([]*googlecloud.Zone, error) {
zoneList, err := svc.service.Zones.List(svc.vm.Project).Do()
if err != nil {
return nil, err
}
return zoneList.Items, nil
}
// getRegionList gets the list of regions
func (svc *googleService) getRegionList() ([]*googlecloud.Region, error) {
regionList, err := svc.service.Regions.List(svc.vm.Project).Do()
if err != nil {
return nil, err
}
return regionList.Items, nil
}
// reset resets a GCE instance.
func (svc *googleService) reset() error {
op, err := svc.service.Instances.Reset(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// getDiskTypeList gets the list of disk types for the given project in the
// given zone
func (svc *googleService) getDiskTypeList() ([]*googlecloud.DiskType, error) {
diskTypeList, err := svc.service.DiskTypes.List(svc.vm.Project, svc.vm.Zone).Do()
if err != nil {
return nil, err
}
return diskTypeList.Items, nil
}
// getDiskType gets details of a disk type
func (svc *googleService) getDiskType(diskType string) (*googlecloud.DiskType, error) {
return svc.service.DiskTypes.Get(svc.vm.Project, svc.vm.Zone, diskType).Do()
}
// createDisk creates a new disk in GCE
func (svc *googleService) createDisk(disk *Disk) error {
diskType, err := svc.getDiskType(disk.DiskType)
if err != nil {
return err
}
gDisk := &googlecloud.Disk{
Name: disk.Name,
SizeGb: int64(disk.DiskSizeGb),
Type: diskType.SelfLink,
Description: disk.Description,
}
op, err := svc.service.Disks.Insert(svc.vm.Project, svc.vm.Zone, gDisk).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// attachDisk attaches a disk to an instance
func (svc *googleService) attachDisk(disk *Disk) error {
gDisk, err := svc.getDisk(disk.Name)
if err != nil {
return err
}
gAttachedDisk := &googlecloud.AttachedDisk{
Source: gDisk.SelfLink,
DeviceName: disk.Name,
AutoDelete: disk.AutoDelete,
}
op, err := svc.service.Instances.AttachDisk(svc.vm.Project, svc.vm.Zone,
svc.vm.Name, gAttachedDisk).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// detachDisk detaches a disk from an instance
func (svc *googleService) detachDisk(disk *Disk) error {
var deviceName string
gDisk, err := svc.getDisk(disk.Name)
if err != nil {
return err
}
instance, err := svc.getInstance()
if err != nil {
return err
}
for _, attachedDisk := range instance.Disks {
if attachedDisk.Source == gDisk.SelfLink {
deviceName = attachedDisk.DeviceName
break
}
}
op, err := svc.service.Instances.DetachDisk(svc.vm.Project, svc.vm.Zone,
svc.vm.Name, deviceName).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
}
// getFirewall gets details of a firewall
func (svc *googleService) getFirewall() (*googlecloud.Firewall, error) {
return svc.service.Firewalls.Get(svc.vm.Project, svc.vm.Firewall).Do()
}
// addFirewallRules adds new ports to a firewall
func (svc *googleService) addFirewallRules() error {
currFirewall, err := svc.getFirewall()
if err != nil {
return err
}
newRules := currFirewall.Allowed
for _, endpoint := range svc.vm.Endpoints {
newRules = append(newRules, &googlecloud.FirewallAllowed{
IPProtocol: endpoint.Protocol,
Ports: endpoint.Ports,
})
}
return svc.patchFirewall(newRules)
}
// patchFirewall patches the firewall with the given allowed ports (rules)
func (svc *googleService) patchFirewall(allowed []*googlecloud.FirewallAllowed) error {
newFirewall := &googlecloud.Firewall{
Allowed: allowed,
}
op, err := svc.service.Firewalls.Patch(svc.vm.Project, svc.vm.Firewall,
newFirewall).Do()
if err != nil {
return err
}
return svc.waitForGlobalOperationReady(op.Name)
}
// removeFirewallRules removes ports from a given firewall
func (svc *googleService) removeFirewallRules() error {
// Define a map to identify ports to be removed. It will record the
// ports with corresponding protocol as remPorts[Protocol][Port] = true
// for each protocol and port combination.
remPorts := make(map[string]map[string]bool)
// Define a map to deal with elements where the same protocol
// appears again
encountered := make(map[string]bool)
// Identify ports for each protocol to be removed
for _, endpoint := range svc.vm.Endpoints {
// Initialize the map only if the given protocol is encountered
// for the first time
if ok := encountered[endpoint.Protocol]; !ok {
remPorts[endpoint.Protocol] = make(map[string]bool)
encountered[endpoint.Protocol] = true
}
for _, port := range endpoint.Ports {
remPorts[endpoint.Protocol][port] = true
}
}
// Initialize new rules with the current one
// Refer to this link for structure of firewall resource
// https://cloud.google.com/compute/docs/reference/latest/firewalls
firewall, err := svc.getFirewall()
if err != nil {
return err
}
newRules := firewall.Allowed
// Remove the ports and protocols that are to be removed from the
// rules. Iterate through each item in the list of rules.
for indexEndp := 0; indexEndp < len(newRules); indexEndp++ {
allowed := newRules[indexEndp]
// Iterate through each port in the port list
for indPort := 0; indPort < len(newRules[indexEndp].Ports); indPort++ {
port := newRules[indexEndp].Ports[indPort]
// Process removal if the given port is to be removed
if ok := remPorts[allowed.IPProtocol][port]; ok {
newRules[indexEndp].Ports[indPort] = ""
newRules[indexEndp].Ports = append(
newRules[indexEndp].Ports[:indPort],
newRules[indexEndp].Ports[indPort+1:]...
)
// Set the index back by one because we have
// shifted elements from indP onwards to left
// by one
indPort = indPort - 1
}
}
// At the end of removal of ports for a particular protocol if
// there are no ports left, then remove that protocol as well.
if len(newRules[indexEndp].Ports) == 0 {
newRules[indexEndp] = nil
newRules = append(newRules[:indexEndp], newRules[indexEndp+1:]...)
// Set the index back by one because we have shifted
// elements from indP onwards to left by one
indexEndp = indexEndp - 1
}
}
return svc.patchFirewall(newRules)
}
// getImageList gets a list of available images in the given list of projects
func (svc *googleService) getImageList() ([]*googlecloud.Image, error) {
imageListAll := make([]*googlecloud.Image, 0)
for _, project := range svc.vm.ImageProjects {
imageList, err := svc.service.Images.List(project).Do()
if err != nil {
return nil, err
}
imageListAll = append(imageListAll, imageList.Items...)
}
return imageListAll, nil
}
// convResURLToName returns resource name from the given resource URL
func convResURLToName(url string) string {
urlSplit := strings.Split(url, "/")
return urlSplit[len(urlSplit)-1]
}
// IsInstance checks if the given instance is present in GCP. Returns true if
// instance is available else false.
func (vm *VM) IsInstance() (bool, error) {
s, err := vm.getService()
if err != nil {
return false, err
}
_, err = s.getInstance()
if err != nil {
return false, err
} else {
return true, nil
}
}
// getProjectList retrieves the list of projects that the given Google cloud
// service account has access to.
func (svc *googleResManService) getProjectList() ([]*googleresourcemanager.Project, error) {
projectList, err := svc.service.Projects.List().Do()
if err != nil {
return nil, err
}
return projectList.Projects, nil
}
// createImage creates a new image in Google cloud platform from a raw disk
// image stored on Google Cloud Storage.
func (svc *googleService) createImage() error {
image := &googlecloud.Image{
Name: svc.vm.SourceImage,
Description: svc.vm.Description,
RawDisk: &googlecloud.ImageRawDisk{
Source: svc.vm.RawDiskSource,
},
}
op, err := svc.service.Images.Insert(svc.vm.Project, image).Do()
if err != nil {
return err
}
return svc.waitForGlobalOperationReady(op.Name)
}
// deleteImage deletes an image from Google cloud platform
func (svc *googleService) deleteImage() error {
op, err := svc.service.Images.Delete(svc.vm.Project, svc.vm.SourceImage).Do()
if err != nil {
return err
}
return svc.waitForGlobalOperationReady(op.Name)
}
|
// This is part of the library that is being used directly inside this package.
// https://github.com/alexedwards/stack
package webgo
import "net/http"
type chainHandler func(*Context) http.Handler
type ChainMiddleware func(*Context, http.Handler) http.Handler
type Chain struct {
mws []ChainMiddleware
h chainHandler
}
func NewStack(mws ...ChainMiddleware) Chain {
return Chain{mws: mws}
}
func (c Chain) Append(mws ...ChainMiddleware) Chain {
newMws := make([]ChainMiddleware, len(c.mws)+len(mws))
copy(newMws[:len(c.mws)], c.mws)
copy(newMws[len(c.mws):], mws)
c.mws = newMws
return c
}
func (c Chain) Then(chf func(ctx *Context, w http.ResponseWriter, r *http.Request)) HandlerChain {
c.h = adaptContextHandlerFunc(chf)
return newHandlerChain(c)
}
func (c Chain) ThenHandler(h http.Handler) HandlerChain {
c.h = adaptHandler(h)
return newHandlerChain(c)
}
func (c Chain) ThenHandlerFunc(fn func(http.ResponseWriter, *http.Request)) HandlerChain {
c.h = adaptHandlerFunc(fn)
return newHandlerChain(c)
}
type HandlerChain struct {
context *Context
Chain
}
func newHandlerChain(c Chain) HandlerChain {
return HandlerChain{context: NewContext(), Chain: c}
}
func (hc HandlerChain) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Always take a copy of context (i.e. pointing to a brand new memory location)
ctx := hc.context.copy()
final := hc.h(ctx)
for i := len(hc.mws) - 1; i >= 0; i-- {
final = hc.mws[i](ctx, final)
}
final.ServeHTTP(w, r)
}
func StackInject(hc HandlerChain, key string, val interface{}) HandlerChain {
hc.context = hc.context.copy().Put(key, val)
return hc
}
// Adapt third party middleware with the signature
// func(http.Handler) http.Handler into ChainMiddleware
func Adapt(fn func(http.Handler) http.Handler) ChainMiddleware {
return func(ctx *Context, h http.Handler) http.Handler {
return fn(h)
}
}
// Adapt http.Handler into a chainHandler
func adaptHandler(h http.Handler) chainHandler {
return func(ctx *Context) http.Handler {
return h
}
}
// Adapt a function with the signature
// func(http.ResponseWriter, *http.Request) into a chainHandler
func adaptHandlerFunc(fn func(w http.ResponseWriter, r *http.Request)) chainHandler {
return adaptHandler(http.HandlerFunc(fn))
}
// Adapt a function with the signature
// func(Context, http.ResponseWriter, *http.Request) into a chainHandler
func adaptContextHandlerFunc(fn func(ctx *Context, w http.ResponseWriter, r *http.Request)) chainHandler {
return func(ctx *Context) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fn(ctx, w, r)
})
}
}
|
package models
import(
"encoding/json"
)
/**
* Type definition for VmwareTypeEnum enum
*/
type VmwareTypeEnum int
/**
* Value collection for VmwareTypeEnum enum
*/
const (
VmwareType_KVCENTER VmwareTypeEnum = 1 + iota
VmwareType_KFOLDER
VmwareType_KDATACENTER
VmwareType_KCOMPUTERESOURCE
VmwareType_KCLUSTERCOMPUTERESOURCE
VmwareType_KRESOURCEPOOL
VmwareType_KDATASTORE
VmwareType_KHOSTSYSTEM
VmwareType_KVIRTUALMACHINE
VmwareType_KVIRTUALAPP
VmwareType_KSTANDALONEHOST
VmwareType_KSTORAGEPOD
VmwareType_KNETWORK
VmwareType_KDISTRIBUTEDVIRTUALPORTGROUP
VmwareType_KTAGCATEGORY
VmwareType_KTAG
VmwareType_KOPAQUENETWORK
VmwareType_KVCLOUDDIRECTOR
VmwareType_KORGANIZATION
VmwareType_KVIRTUALDATACENTER
VmwareType_KCATALOG
VmwareType_KORGMETADATA
VmwareType_KSTORAGEPOLICY
)
func (r VmwareTypeEnum) MarshalJSON() ([]byte, error) {
s := VmwareTypeEnumToValue(r)
return json.Marshal(s)
}
func (r *VmwareTypeEnum) UnmarshalJSON(data []byte) error {
var s string
json.Unmarshal(data, &s)
v := VmwareTypeEnumFromValue(s)
*r = v
return nil
}
/**
* Converts VmwareTypeEnum to its string representation
*/
func VmwareTypeEnumToValue(vmware_TypeEnum VmwareTypeEnum) string {
switch vmware_TypeEnum {
case VmwareType_KVCENTER:
return "kVCenter"
case VmwareType_KFOLDER:
return "kFolder"
case VmwareType_KDATACENTER:
return "kDatacenter"
case VmwareType_KCOMPUTERESOURCE:
return "kComputeResource"
case VmwareType_KCLUSTERCOMPUTERESOURCE:
return "kClusterComputeResource"
case VmwareType_KRESOURCEPOOL:
return "kResourcePool"
case VmwareType_KDATASTORE:
return "kDatastore"
case VmwareType_KHOSTSYSTEM:
return "kHostSystem"
case VmwareType_KVIRTUALMACHINE:
return "kVirtualMachine"
case VmwareType_KVIRTUALAPP:
return "kVirtualApp"
case VmwareType_KSTANDALONEHOST:
return "kStandaloneHost"
case VmwareType_KSTORAGEPOD:
return "kStoragePod"
case VmwareType_KNETWORK:
return "kNetwork"
case VmwareType_KDISTRIBUTEDVIRTUALPORTGROUP:
return "kDistributedVirtualPortgroup"
case VmwareType_KTAGCATEGORY:
return "kTagCategory"
case VmwareType_KTAG:
return "kTag"
case VmwareType_KOPAQUENETWORK:
return "kOpaqueNetwork"
case VmwareType_KVCLOUDDIRECTOR:
return "kVCloudDirector"
case VmwareType_KORGANIZATION:
return "kOrganization"
case VmwareType_KVIRTUALDATACENTER:
return "kVirtualDatacenter"
case VmwareType_KCATALOG:
return "kCatalog"
case VmwareType_KORGMETADATA:
return "kOrgMetadata"
case VmwareType_KSTORAGEPOLICY:
return "kStoragePolicy"
default:
return "kVCenter"
}
}
/**
* Converts VmwareTypeEnum Array to its string Array representation
*/
func VmwareTypeEnumArrayToValue(vmware_TypeEnum []VmwareTypeEnum) []string {
convArray := make([]string,len( vmware_TypeEnum))
for i:=0; i<len(vmware_TypeEnum);i++ {
convArray[i] = VmwareTypeEnumToValue(vmware_TypeEnum[i])
}
return convArray
}
/**
* Converts given value to its enum representation
*/
func VmwareTypeEnumFromValue(value string) VmwareTypeEnum {
switch value {
case "kVCenter":
return VmwareType_KVCENTER
case "kFolder":
return VmwareType_KFOLDER
case "kDatacenter":
return VmwareType_KDATACENTER
case "kComputeResource":
return VmwareType_KCOMPUTERESOURCE
case "kClusterComputeResource":
return VmwareType_KCLUSTERCOMPUTERESOURCE
case "kResourcePool":
return VmwareType_KRESOURCEPOOL
case "kDatastore":
return VmwareType_KDATASTORE
case "kHostSystem":
return VmwareType_KHOSTSYSTEM
case "kVirtualMachine":
return VmwareType_KVIRTUALMACHINE
case "kVirtualApp":
return VmwareType_KVIRTUALAPP
case "kStandaloneHost":
return VmwareType_KSTANDALONEHOST
case "kStoragePod":
return VmwareType_KSTORAGEPOD
case "kNetwork":
return VmwareType_KNETWORK
case "kDistributedVirtualPortgroup":
return VmwareType_KDISTRIBUTEDVIRTUALPORTGROUP
case "kTagCategory":
return VmwareType_KTAGCATEGORY
case "kTag":
return VmwareType_KTAG
case "kOpaqueNetwork":
return VmwareType_KOPAQUENETWORK
case "kVCloudDirector":
return VmwareType_KVCLOUDDIRECTOR
case "kOrganization":
return VmwareType_KORGANIZATION
case "kVirtualDatacenter":
return VmwareType_KVIRTUALDATACENTER
case "kCatalog":
return VmwareType_KCATALOG
case "kOrgMetadata":
return VmwareType_KORGMETADATA
case "kStoragePolicy":
return VmwareType_KSTORAGEPOLICY
default:
return VmwareType_KVCENTER
}
}
|
package main
import (
"fmt"
"os"
"sort"
"strconv"
"time"
"github.com/dustin/go-humanize"
"github.com/olekukonko/tablewriter"
)
type listCompactionSummaryCmd struct {
TenantID string `arg:"" help:"tenant-id within the bucket"`
backendOptions
}
func (l *listCompactionSummaryCmd) Run(ctx *globalOptions) error {
r, c, err := loadBackend(&l.backendOptions, ctx)
if err != nil {
return err
}
windowDuration := time.Hour
results, err := loadBucket(r, c, l.TenantID, windowDuration, false)
if err != nil {
return err
}
displayCompactionSummary(results)
return nil
}
func displayCompactionSummary(results []blockStats) {
fmt.Println()
fmt.Println("Stats by compaction level:")
resultsByLevel := make(map[int][]blockStats)
var levels []int
for _, r := range results {
l := int(r.CompactionLevel)
s, ok := resultsByLevel[l]
if !ok {
s = make([]blockStats, 0)
levels = append(levels, l)
}
s = append(s, r)
resultsByLevel[l] = s
}
sort.Ints(levels)
columns := []string{"lvl", "blocks", "total", "smallest block", "largest block", "earliest", "latest"}
out := make([][]string, 0)
for _, l := range levels {
sizeSum := uint64(0)
sizeMin := uint64(0)
sizeMax := uint64(0)
countSum := 0
countMin := 0
countMax := 0
var newest time.Time
var oldest time.Time
for _, r := range resultsByLevel[l] {
sizeSum += r.Size
countSum += r.TotalObjects
if r.Size < sizeMin || sizeMin == 0 {
sizeMin = r.Size
}
if r.Size > sizeMax {
sizeMax = r.Size
}
if r.TotalObjects < countMin || countMin == 0 {
countMin = r.TotalObjects
}
if r.TotalObjects > countMax {
countMax = r.TotalObjects
}
if r.StartTime.Before(oldest) || oldest.IsZero() {
oldest = r.StartTime
}
if r.EndTime.After(newest) {
newest = r.EndTime
}
}
line := make([]string, 0)
for _, c := range columns {
s := ""
switch c {
case "lvl":
s = strconv.Itoa(l)
case "blocks":
s = fmt.Sprintf("%d (%d %%)", len(resultsByLevel[l]), len(resultsByLevel[l])*100/len(results))
case "total":
s = fmt.Sprintf("%s objects (%s)", humanize.Comma(int64(countSum)), humanize.Bytes(sizeSum))
case "smallest block":
s = fmt.Sprintf("%s objects (%s)", humanize.Comma(int64(countMin)), humanize.Bytes(sizeMin))
case "largest block":
s = fmt.Sprintf("%s objects (%s)", humanize.Comma(int64(countMax)), humanize.Bytes(sizeMax))
case "earliest":
s = fmt.Sprint(time.Since(oldest).Round(time.Second), " ago")
case "latest":
s = fmt.Sprint(time.Since(newest).Round(time.Second), " ago")
}
line = append(line, s)
}
out = append(out, line)
}
fmt.Println()
w := tablewriter.NewWriter(os.Stdout)
w.SetHeader(columns)
w.AppendBulk(out)
w.Render()
}
|
package handler
import (
"fmt"
"net/http"
)
type HelloHandler struct{}
func (*HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//ints := []int{0, 1, 2}
//fmt.Fprintf(w, "%v", ints[0:5])
fmt.Fprintf(w, "Hello World1")
} |
package main
import (
"io/ioutil"
"os"
"testing"
"time"
)
// TestConfigReloadNotifications tests the notification of files changing with
// limiting on output duration.
// x = file write
// y = expected notification time
// x x y
// | | |
// 0s 1s 2s
func TestConfigReloadNotificatons(t *testing.T) {
// make temp file and write changes in the background
tempDirectory := os.TempDir()
testFile := tempDirectory + "testFile"
go tempFileWriter(testFile, t)
// write an initial blank file so the config monitor finds something without error
err := ioutil.WriteFile(testFile, []byte("this is the second test file"), 0775)
if err != nil {
t.Fatal("Failed to write initial file to disk:", err)
}
// begin watching for changes
t.Log("using test file:", testFile)
outChan, cancelFunc, err := startConfigReloadMonitoringWithSmoothing(testFile, time.Second*1, time.Second*5)
if err != nil {
t.Fatal(err)
}
defer cancelFunc()
// watch for expected results
expectedNotifications := 2
foundNotifications := 0
startTime := time.Now()
quickestRunTime := time.Second * 20
quickestPossibleFinishTime := startTime.Add(quickestRunTime)
maxRunTime := time.Second * 25
timeout := time.After(maxRunTime)
for {
if foundNotifications == expectedNotifications {
if time.Now().Before(quickestPossibleFinishTime) {
t.Fatal("Tests ran too quickly! Duration was:", time.Now().Sub(startTime))
}
break
}
select {
case <-outChan:
foundNotifications++
t.Log("Got file change notification!", foundNotifications, "/", expectedNotifications)
case <-timeout:
t.Fatal("Did not get expected notifications in time.")
}
}
}
// tempFileWriter writes files to the specified testFile on a schedule to test config file reloading
func tempFileWriter(testFile string, t *testing.T) {
// write changes for 4 seconds every second
for i := 0; i < 4; i++ {
err := ioutil.WriteFile(testFile, []byte("this is the test file"+time.Now().String()), 0775)
if err != nil {
t.Fatal("Failed to write temp file content:", err)
}
t.Log("Wrote content to location:", testFile)
time.Sleep(time.Second)
}
time.Sleep(time.Second * 10)
// write changes for 4 seconds every second
for i := 0; i < 4; i++ {
err := ioutil.WriteFile(testFile, []byte("this is the test file"+time.Now().String()), 0775)
if err != nil {
t.Fatal("Failed to write temp file content:", err)
}
t.Log("Wrote content to location:", testFile)
time.Sleep(time.Second)
}
}
|
package account
import (
"crypto/md5"
"crypto/rand"
"errors"
"fmt"
"log"
"strconv"
"time"
"unicode"
"github.com/jinzhu/gorm"
"github.com/kiwih/nullables"
"golang.org/x/crypto/bcrypt"
"gopkg.in/validator.v2"
)
type Account struct {
Id int64
Email string `sql:"unique; type:varchar(60);" validate:"nonzero"`
Nickname string `sql:"type:varchar(15); validate:"nonzero"`
Password string `sql:"type:varchar(60);"`
VerificationCode nullables.NullString `sql:"type:varchar(32)"`
ResetPasswordVerificationCode nullables.NullString `sql:"type:varchar(32)"`
CurrentSession nullables.NullString `sql:"type:varchar(32)"`
SessionExpires nullables.NullTime
VoteBank int64
Admin bool
CreatedAt nullables.NullTime
UpdatedAt nullables.NullTime
DeletedAt nullables.NullTime
}
type AccountStorer interface {
LoadAccountFromEmail(email string) (*Account, error)
LoadAccountFromId(int64) (*Account, error)
LoadAccountFromSession(sessionId string) (*Account, error)
CreateAccount(*Account) error
SaveAccount(*Account) error
}
var (
NoVotesLeft error = errors.New("No votes left in bank!")
InvalidUsernameOrPassword error = errors.New("Invalid Username/Password")
AccountNotYetVerified error = errors.New("Account not yet verified.")
AccountNicknameTooLong error = errors.New("Your nickname cannot be longer than 15 characters!")
AccountDoesNotNeedVerification error = errors.New("Account doesn't need verifying!")
AccountVerificationCodeNotMatch error = errors.New("Bad verification code!")
AccountPasswordResetNotRequested error = errors.New("Password reset not requested!")
EmailAddressAlreadyInUse error = errors.New("This email address is already in use!")
PasswordNotAcceptable error = errors.New("Password must contain at least 3 of types of characters from uppercase, lowercase, punctuation, and digits, and be at least 8 characters long.")
)
func GenerateValidationKey() (nullables.NullString, error) {
//generate validation key
b := make([]byte, 10)
_, err := rand.Read(b)
if err != nil {
return nullables.NullString{}, err
}
return nullables.NullString{String: fmt.Sprintf("%x", md5.Sum(b)), Valid: true}, nil
}
func AttemptLogin(as AccountStorer, propEmail string, propPassword string, willExpire bool) (*Account, error) {
propUser, err := as.LoadAccountFromEmail(propEmail)
if err == nil {
if err = bcrypt.CompareHashAndPassword([]byte(propUser.Password), []byte(propPassword)); err == nil {
//they have passed the login check. Save them to the session and redirect to management portal
if propUser.VerificationCode.Valid {
return nil, AccountNotYetVerified
}
//successful login.
//generate session
propUser.CurrentSession, err = GenerateValidationKey()
if err != nil {
return nil, err
}
if willExpire {
propUser.SessionExpires = nullables.NullTime{Time: time.Now().Add(3600 * time.Second), Valid: true} //expires in 1 hour if they don't want to be remembered
} else {
propUser.SessionExpires = nullables.NullTime{Time: time.Now().AddDate(0, 1, 0), Valid: true} //expires in 1 month if they want to be remembered
}
return propUser, as.SaveAccount(propUser)
}
return nil, InvalidUsernameOrPassword
}
return nil, InvalidUsernameOrPassword
}
func IsEmailInUse(as AccountStorer, email string) (bool, error) {
if _, err := as.LoadAccountFromEmail(email); err != nil {
if err.Error() == gorm.ErrRecordNotFound.Error() {
return false, nil
} else {
return false, err
}
}
return true, nil
}
var passwordMustHave = []func(rune) bool{
unicode.IsUpper,
unicode.IsLower,
unicode.IsSymbol,
unicode.IsDigit,
unicode.IsPunct,
}
func IsPasswordAcceptable(plaintextPassword string) bool {
if len(plaintextPassword) < 8 {
return false
}
types := 0
for _, testRune := range passwordMustHave {
found := false
for _, r := range plaintextPassword {
if testRune(r) {
found = true
}
}
if found {
types++
}
}
return types >= 3
}
func CanAccountBeMade(as AccountStorer, a *Account, passwordClearText string) error {
//make sure password is secure
if !IsPasswordAcceptable(passwordClearText) {
return PasswordNotAcceptable
}
//make sure username isn't taken
if nameTaken, err := IsEmailInUse(as, a.Email); nameTaken == true || err != nil {
if err != nil {
return err
}
return EmailAddressAlreadyInUse
}
if len(a.Nickname) > 15 {
return AccountNicknameTooLong
}
//check account is valid
if err := a.Valid(); err != nil {
return err
}
return nil
}
func (a *Account) SetPassword(cleartext string) error {
hashpass, err := bcrypt.GenerateFromPassword([]byte(cleartext), 10)
if err != nil {
return err
}
a.Password = string(hashpass)
return nil
}
func CheckAndCreateAccount(as AccountStorer, email string, password string, nickname string) error {
//check if account is valid
a := &Account{
Nickname: nickname,
Email: email,
VoteBank: 10,
}
if err := CanAccountBeMade(as, a, password); err != nil {
return err
}
//hash password
if err := a.SetPassword(password); err != nil {
log.Println("Error in password hashing: " + err.Error())
return err
}
var err error
if a.VerificationCode, err = GenerateValidationKey(); err != nil {
return err
}
//create account, send validation email
if err = as.CreateAccount(a); err != nil {
return err
}
sendEmail(a.Email, "Verification code", "Hello!\r\n\r\nTo validate your hey.fyi account, you need to follow this link:\r\nhttp://hey.fyi/verify/"+strconv.FormatInt(a.Id, 10)+"/"+a.VerificationCode.String+"\r\n\r\nI hope you enjoy using the service!\r\n\r\nRegards,\r\nhey.fyi")
log.Printf("Verification code for user %s is %s\n", a.Email, a.VerificationCode.String)
return nil
}
func DoPasswordResetRequestIfPossible(as AccountStorer, email string) error {
a, err := as.LoadAccountFromEmail(email)
if err != nil {
return err
}
if a.ResetPasswordVerificationCode, err = GenerateValidationKey(); err != nil {
return err
}
sendEmail(a.Email, "Password Reset Request", "Hello!\r\n\r\nSomeone requested a password reset to your hey.fyi account.\r\nIf you didn't request this, simply ignore this email.\r\n\r\nOtherwise, follow this link:\r\nhttp://hey.fyi/reset/"+strconv.FormatInt(a.Id, 10)+"/"+a.ResetPasswordVerificationCode.String+"\r\n\r\nRegards,\r\nhey.fyi")
log.Printf("Reset Password verification code for user %s is %s\n", a.Email, a.VerificationCode.String)
return as.SaveAccount(a)
}
func (a Account) Valid() error {
return validator.Validate(a)
}
func (a *Account) ApplyVerificationCode(as AccountStorer, verificationCode string) error {
if a.VerificationCode.Valid == false {
return AccountDoesNotNeedVerification
}
if a.VerificationCode.String != verificationCode {
return AccountVerificationCodeNotMatch
}
a.VerificationCode.String = ""
a.VerificationCode.Valid = false
return as.SaveAccount(a)
}
func (a *Account) AwaitingPasswordReset() bool {
return a.ResetPasswordVerificationCode.Valid
}
func (a *Account) ApplyPasswordResetVerificationCode(as AccountStorer, resetVerificationCode string, newPassword string) error {
if a.AwaitingPasswordReset() == false {
return AccountPasswordResetNotRequested
}
if a.ResetPasswordVerificationCode.String != resetVerificationCode {
return AccountVerificationCodeNotMatch
}
if !IsPasswordAcceptable(newPassword) {
return PasswordNotAcceptable
}
if err := a.SetPassword(newPassword); err != nil {
return err
}
a.ResetPasswordVerificationCode.String = ""
a.ResetPasswordVerificationCode.Valid = false
return as.SaveAccount(a)
}
func (a *Account) UpdateVoteBank(as AccountStorer, up bool, currentAccountVote int64) error {
if (up && currentAccountVote >= 0) || (!up && currentAccountVote <= 0) { //they are casting a vote
if a.VoteBank <= 0 {
return NoVotesLeft
} else {
a.VoteBank--
return as.SaveAccount(a)
}
}
//else, they are retracting a vote
a.VoteBank++
return as.SaveAccount(a)
}
func (a *Account) ExpireSession(as AccountStorer) error {
a.CurrentSession.Valid = false
a.CurrentSession.String = ""
a.SessionExpires.Time = time.Now()
return as.SaveAccount(a)
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package adb
import (
"context"
"regexp"
"strconv"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/errors"
"chromiumos/tast/shutil"
)
// ShellCommand returns a command in Android shell via adb.
func (d *Device) ShellCommand(ctx context.Context, name string, args ...string) *testexec.Cmd {
// adb shell executes the command via /bin/sh, so here it is necessary
// to escape.
cmd := "exec " + shutil.EscapeSlice(append([]string{name}, args...))
return d.Command(ctx, "shell", cmd)
}
// SendIntentCommand returns a Cmd to send an intent with "am start" command.
func (d *Device) SendIntentCommand(ctx context.Context, action, data string) *testexec.Cmd {
args := []string{"start", "-a", action}
if len(data) > 0 {
args = append(args, "-d", data)
}
return d.ShellCommand(ctx, "am", args...)
}
// GetProp returns the Android system property indicated by the specified key.
func (d *Device) GetProp(ctx context.Context, key string) (string, error) {
o, err := d.ShellCommand(ctx, "getprop", key).Output(testexec.DumpLogOnError)
if err != nil {
return "", err
}
return strings.TrimSpace(string(o)), nil
}
// BroadcastResult is the parsed result of an Android Activity Manager broadcast.
type BroadcastResult struct {
// The result value of the broadcast.
Result int
// Optional: Additional data to be passed with the result.
Data *string
// Optional: A bundle of extra data passed with the result.
// TODO(springerm): extras is a key-value map and should be parsed.
Extras *string
}
const (
// Activity.RESULT_OK
intentResultActivityResultOk = -1
)
// BroadcastIntent broadcasts an intent with "am broadcast" and returns the result.
func (d *Device) BroadcastIntent(ctx context.Context, action string, params ...string) (*BroadcastResult, error) {
args := []string{"broadcast", "-a", action}
args = append(args, params...)
output, err := d.ShellCommand(ctx, "am", args...).Output(testexec.DumpLogOnError)
if err != nil {
return nil, err
}
// TODO(springerm): Find a way to report metrics from Android apps, so we can avoid this parsing hackery.
// broadcastResultRegexp matches the result from an Android Activity Manager broadcast.
broadcastResultRegexp := regexp.MustCompile(`Broadcast completed: result=(-?[0-9]+)(, data="((\\.|[^\\"])*)")?(, extras: Bundle\[(.*)\])?`)
m := broadcastResultRegexp.FindSubmatch(output)
if m == nil {
return nil, errors.Errorf("unable to parse broadcast result for %s: %q", action, output)
}
resultValue, err := strconv.Atoi(string(m[1]))
if err != nil {
return nil, errors.Errorf("unable to parse broadcast result value for %s: %q", action, string(m[1]))
}
broadcastResult := BroadcastResult{}
broadcastResult.Result = resultValue
// `m[3]` matches the data value. `m[2]` matches the entire "data=\"...\"" part.
// We have to check `m[2]` because the data could be an empty string, which is different from "no data", in which case we return nil.
data := string(m[3])
if string(m[2]) != "" {
broadcastResult.Data = &data
}
extras := string(m[6])
if string(m[5]) != "" {
broadcastResult.Extras = &extras
}
return &broadcastResult, nil
}
// BroadcastIntentGetData broadcasts an intent with "am broadcast" and returns the result data.
func (d *Device) BroadcastIntentGetData(ctx context.Context, action string, params ...string) (string, error) {
result, err := d.BroadcastIntent(ctx, action, params...)
if err != nil {
return "", err
}
if result.Result != intentResultActivityResultOk {
if result.Data == nil {
return "", errors.Errorf("broadcast of %q failed, status = %d", action, result.Result)
}
return "", errors.Errorf("broadcast of %q failed, status = %d, data = %q", action, result.Result, *result.Data)
}
if result.Data == nil {
return "", errors.Errorf("broadcast of %q has no result data", action)
}
return *result.Data, nil
}
// BugReport returns bugreport of the device.
func (d *Device) BugReport(ctx context.Context, path string) error {
return d.Command(ctx, "bugreport", path).Run(testexec.DumpLogOnError)
}
|
package main
import "fmt"
func main() {
c := make(chan int, 2)
// go func() {
// c <- 13
// }()
c <- 13
c <- 99
fmt.Println(<-c)
fmt.Println(<-c)
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package k8s
import (
"context"
corev1 "k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// CreateOrUpdateSecret creates or update a secret
func (kc *KubeClient) CreateOrUpdateSecret(namespace string, secret *corev1.Secret) (metav1.Object, error) {
ctx := context.TODO()
_, err := kc.Clientset.CoreV1().Secrets(namespace).Get(ctx, secret.GetName(), metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8sErrors.IsNotFound(err) {
return kc.Clientset.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{})
}
return kc.Clientset.CoreV1().Secrets(namespace).Update(ctx, secret, metav1.UpdateOptions{})
}
// GetSecrets returns a list of kubernetes secret objects if they exist.
//
// Any errors will be returned immediately and the remaining secrets will be
// skipped.
func (kc *KubeClient) GetSecrets(nameSpace string, secretsNames []string) ([]*corev1.Secret, error) {
ctx := context.TODO()
secrets := []*corev1.Secret{}
for _, secretsName := range secretsNames {
secret, err := kc.Clientset.CoreV1().Secrets(nameSpace).Get(ctx, secretsName, metav1.GetOptions{})
if err != nil {
return secrets, err
}
secrets = append(secrets, secret)
}
return secrets, nil
}
|
//go:generate mockgen -package mock -destination=mock/port_domain.go github.com/johnnywidth/9ty/api PortDomainClient
package service
import (
"context"
"fmt"
"github.com/johnnywidth/9ty/api"
"github.com/johnnywidth/9ty/client/entity"
)
// PortDomain port domain service with grpc client
type PortDomain struct {
client api.PortDomainClient
}
// NewPortDomain create new instance of port domain service
func NewPortDomain(
client api.PortDomainClient,
) *PortDomain {
return &PortDomain{
client: client,
}
}
// Create send port data to Port Domain service
func (s *PortDomain) Create(ctx context.Context, key string, e *entity.PortData) error {
_, err := s.client.Create(ctx, &api.PortRequest{
Key: key,
Name: e.Name,
City: e.City,
Country: e.Country,
Alias: e.Alias,
Regions: e.Regions,
Coordinates: e.Coordinates,
Province: e.Province,
Timezone: e.Timezone,
Unlocs: e.Unlocs,
Code: e.Code,
})
if err != nil {
return fmt.Errorf("service create port data failed. %w", err)
}
return nil
}
// Get get port data from Port Domain service for given port key
func (s *PortDomain) Get(ctx context.Context, key string) (*entity.PortData, error) {
e, err := s.client.Get(ctx, &api.GetRequest{Key: key})
if err != nil {
return nil, fmt.Errorf("service get port data failed. %w", err)
}
if e == nil || e.Name == "" {
return nil, fmt.Errorf("service return empty port data. %w", entity.ErrNotFound)
}
return &entity.PortData{
Name: e.Name,
City: e.City,
Country: e.Country,
Alias: e.Alias,
Regions: e.Regions,
Coordinates: e.Coordinates,
Province: e.Province,
Timezone: e.Timezone,
Unlocs: e.Unlocs,
Code: e.Code,
}, nil
}
|
package forgotpassword
func UserForgotPassword(email string) error {
return nil
}
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hostinet
import (
"unsafe"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/hostarch"
"gvisor.dev/gvisor/pkg/sentry/arch"
"gvisor.dev/gvisor/pkg/sentry/inet"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/socket"
"gvisor.dev/gvisor/pkg/syserr"
"gvisor.dev/gvisor/pkg/usermem"
)
func firstBytePtr(bs []byte) unsafe.Pointer {
if len(bs) == 0 {
return nil
}
return unsafe.Pointer(&bs[0])
}
// Preconditions: len(dsts) != 0.
func readv(fd int, dsts []unix.Iovec) (uint64, error) {
n, _, errno := unix.Syscall(unix.SYS_READV, uintptr(fd), uintptr(unsafe.Pointer(&dsts[0])), uintptr(len(dsts)))
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
return uint64(n), nil
}
// Preconditions: len(srcs) != 0.
func writev(fd int, srcs []unix.Iovec) (uint64, error) {
n, _, errno := unix.Syscall(unix.SYS_WRITEV, uintptr(fd), uintptr(unsafe.Pointer(&srcs[0])), uintptr(len(srcs)))
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
return uint64(n), nil
}
func ioctl(ctx context.Context, fd int, io usermem.IO, sysno uintptr, args arch.SyscallArguments) (uintptr, error) {
switch cmd := uintptr(args[1].Int()); cmd {
case unix.TIOCINQ, unix.TIOCOUTQ:
var val int32
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), cmd, uintptr(unsafe.Pointer(&val))); errno != 0 {
return 0, translateIOSyscallError(errno)
}
var buf [4]byte
hostarch.ByteOrder.PutUint32(buf[:], uint32(val))
_, err := io.CopyOut(ctx, args[2].Pointer(), buf[:], usermem.IOOpts{
AddressSpaceActive: true,
})
return 0, err
case linux.SIOCGIFFLAGS,
linux.SIOCGIFHWADDR,
linux.SIOCGIFINDEX,
linux.SIOCGIFMTU,
linux.SIOCGIFNAME,
linux.SIOCGIFNETMASK,
linux.SIOCGIFTXQLEN:
cc := &usermem.IOCopyContext{
Ctx: ctx,
IO: io,
Opts: usermem.IOOpts{
AddressSpaceActive: true,
},
}
var ifr linux.IFReq
if _, err := ifr.CopyIn(cc, args[2].Pointer()); err != nil {
return 0, err
}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), cmd, uintptr(unsafe.Pointer(&ifr))); errno != 0 {
return 0, translateIOSyscallError(errno)
}
_, err := ifr.CopyOut(cc, args[2].Pointer())
return 0, err
case linux.SIOCGIFCONF:
cc := &usermem.IOCopyContext{
Ctx: ctx,
IO: io,
Opts: usermem.IOOpts{
AddressSpaceActive: true,
},
}
var ifc linux.IFConf
if _, err := ifc.CopyIn(cc, args[2].Pointer()); err != nil {
return 0, err
}
// The user's ifconf can have a nullable pointer to a buffer. Use a Sentry array if non-null.
ifcNested := linux.IFConf{Len: ifc.Len}
var ifcBuf []byte
if ifc.Ptr != 0 {
ifcBuf = make([]byte, ifc.Len)
ifcNested.Ptr = uint64(uintptr(unsafe.Pointer(&ifcBuf[0])))
}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), cmd, uintptr(unsafe.Pointer(&ifcNested))); errno != 0 {
return 0, translateIOSyscallError(errno)
}
// Copy out the buffer if it was non-null.
if ifc.Ptr != 0 {
if _, err := cc.CopyOutBytes(hostarch.Addr(ifc.Ptr), ifcBuf); err != nil {
return 0, err
}
}
ifc.Len = ifcNested.Len
_, err := ifc.CopyOut(cc, args[2].Pointer())
return 0, err
case linux.SIOCETHTOOL:
cc := &usermem.IOCopyContext{
Ctx: ctx,
IO: io,
Opts: usermem.IOOpts{
AddressSpaceActive: true,
},
}
var ifr linux.IFReq
if _, err := ifr.CopyIn(cc, args[2].Pointer()); err != nil {
return 0, err
}
// SIOCETHTOOL commands specify the subcommand in the first 32 bytes pointed
// to by ifr.ifr_data. We need to copy it in first to understand the actual
// structure pointed by ifr.ifr_data.
ifrData := hostarch.Addr(hostarch.ByteOrder.Uint64(ifr.Data[:8]))
var ethtoolCmd linux.EthtoolCmd
if _, err := ethtoolCmd.CopyIn(cc, ifrData); err != nil {
return 0, err
}
// We only support ETHTOOL_GFEATURES.
if ethtoolCmd != linux.ETHTOOL_GFEATURES {
return 0, linuxerr.EOPNOTSUPP
}
var gfeatures linux.EthtoolGFeatures
if _, err := gfeatures.CopyIn(cc, ifrData); err != nil {
return 0, err
}
// Find the requested device.
stk := inet.StackFromContext(ctx)
if stk == nil {
return 0, linuxerr.ENODEV
}
var (
iface inet.Interface
found bool
)
for _, iface = range stk.Interfaces() {
if iface.Name == ifr.Name() {
found = true
break
}
}
if !found {
return 0, linuxerr.ENODEV
}
// Copy out the feature blocks to the memory pointed to by ifrData.
blksToCopy := int(gfeatures.Size)
if blksToCopy > len(iface.Features) {
blksToCopy = len(iface.Features)
}
gfeatures.Size = uint32(blksToCopy)
if _, err := gfeatures.CopyOut(cc, ifrData); err != nil {
return 0, err
}
next, ok := ifrData.AddLength(uint64(unsafe.Sizeof(linux.EthtoolGFeatures{})))
for i := 0; i < blksToCopy; i++ {
if !ok {
return 0, linuxerr.EFAULT
}
if _, err := iface.Features[i].CopyOut(cc, next); err != nil {
return 0, err
}
next, ok = next.AddLength(uint64(unsafe.Sizeof(linux.EthtoolGetFeaturesBlock{})))
}
return 0, nil
default:
return 0, linuxerr.ENOTTY
}
}
func accept4(fd int, addr *byte, addrlen *uint32, flags int) (int, error) {
afd, _, errno := unix.Syscall6(unix.SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(addr)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
return int(afd), nil
}
func getsockopt(fd int, level, name int, opt []byte) ([]byte, error) {
optlen32 := int32(len(opt))
_, _, errno := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(firstBytePtr(opt)), uintptr(unsafe.Pointer(&optlen32)), 0)
if errno != 0 {
return nil, errno
}
return opt[:optlen32], nil
}
// GetSockName implements socket.Socket.GetSockName.
func (s *Socket) GetSockName(t *kernel.Task) (linux.SockAddr, uint32, *syserr.Error) {
addr := make([]byte, sizeofSockaddr)
addrlen := uint32(len(addr))
_, _, errno := unix.Syscall(unix.SYS_GETSOCKNAME, uintptr(s.fd), uintptr(unsafe.Pointer(&addr[0])), uintptr(unsafe.Pointer(&addrlen)))
if errno != 0 {
return nil, 0, syserr.FromError(errno)
}
return socket.UnmarshalSockAddr(s.family, addr), addrlen, nil
}
// GetPeerName implements socket.Socket.GetPeerName.
func (s *Socket) GetPeerName(t *kernel.Task) (linux.SockAddr, uint32, *syserr.Error) {
addr := make([]byte, sizeofSockaddr)
addrlen := uint32(len(addr))
_, _, errno := unix.Syscall(unix.SYS_GETPEERNAME, uintptr(s.fd), uintptr(unsafe.Pointer(&addr[0])), uintptr(unsafe.Pointer(&addrlen)))
if errno != 0 {
return nil, 0, syserr.FromError(errno)
}
return socket.UnmarshalSockAddr(s.family, addr), addrlen, nil
}
func recvfrom(fd int, dst []byte, flags int, from *[]byte) (uint64, error) {
fromLen := uint32(len(*from))
n, _, errno := unix.Syscall6(unix.SYS_RECVFROM, uintptr(fd), uintptr(firstBytePtr(dst)), uintptr(len(dst)), uintptr(flags), uintptr(firstBytePtr(*from)), uintptr(unsafe.Pointer(&fromLen)))
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
*from = (*from)[:fromLen]
return uint64(n), nil
}
func recvmsg(fd int, msg *unix.Msghdr, flags int) (uint64, error) {
n, _, errno := unix.Syscall(unix.SYS_RECVMSG, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags))
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
return uint64(n), nil
}
func sendmsg(fd int, msg *unix.Msghdr, flags int) (uint64, error) {
n, _, errno := unix.Syscall(unix.SYS_SENDMSG, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags))
if errno != 0 {
return 0, translateIOSyscallError(errno)
}
return uint64(n), nil
}
|
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
notifyKill()
fmt.Printf(">> env addr:%v,port:%v,topic:%v \n", os.Getenv("KAFKA_HOST"), os.Getenv("PORT"), os.Getenv("TOPIC"))
config := Config{
Brokers: []string{os.Getenv("KAFKA_HOST") + ":" + os.Getenv("PORT")},
Topic: os.Getenv("TOPIC"),
}
if err := Consume("consumer-kafka", config,
EventFruit,
); err != nil {
panic(err)
}
fmt.Println("consumer is ready!")
time.Sleep(100 * time.Hour)
}
func notifyKill() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Kill, os.Interrupt)
go func() {
for s := range signals {
switch s {
case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
os.Exit(0)
}
}
}()
}
|
package service
import (
"errors"
. "worker/common"
"worker/model/task"
)
type TaskServicer interface {
Check() error
Run()
}
func GetService(task *task.TaskModel) (TaskServicer, error) {
name := task.Name
switch name {
case VIDEO_DOWNLOAD:
return &VideoService{task: task}, nil
default:
return nil, errors.New("未找到任务【" + name + "】")
}
}
|
package main
import (
"fmt"
"unsafe"
)
type S struct {
A struct{}
B struct{}
}
func main() {
null := struct{}{}
fmt.Println(unsafe.Sizeof(null)) // 0
fmt.Printf("%p\n", &null)
// 定义多个空结构体都指向同一个内存地址(全局区)
null2 := struct{}{}
fmt.Printf("%p\n", &null2)
s := S{}
fmt.Println(s.A) // {}
fmt.Println(s.B) // {}
}
|
package main
import "fmt"
func main() {
err1, err2 := 1, 2
fmt.Println(&err1, &err2)
// 左边存在两个变量的情况,会一起重新进行声明time
// 这里的地址没有变,不要混淆 作用域 以及 life
err2, err3 := 3, 4
fmt.Println(&err1, &err2, &err3)
}
|
package persist
import (
"github.com/jinzhu/gorm"
"github.com/Eric-GreenComb/one-account-info/bean"
"github.com/Eric-GreenComb/one-account-info/config"
)
// ConnectDb connect Db
func ConnectDb() (*gorm.DB, error) {
db, err := gorm.Open(config.MariaDB.Dialect, config.MariaDB.URL)
if config.Server.GormLogMode == "false" {
db.LogMode(false)
}
if err != nil {
return nil, err
}
return db, nil
}
// InitDatabase Init Db
func InitDatabase() {
db, err := gorm.Open(config.MariaDB.Dialect, config.MariaDB.URL)
defer db.Close()
if config.Server.GormLogMode == "false" {
db.LogMode(false)
}
if err != nil {
panic(err)
}
if !db.HasTable(&bean.Account{}) {
db.CreateTable(&bean.Account{})
db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&bean.Account{})
}
return
}
|
package Pool
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"time"
)
type MongoPool struct {
pool chan *mongo.Client //存放连接的管道, 缓存控制最大闲置连接数
timeout time.Duration //超时
uri string //地址
connections int //当前系统连接数
poolSize int //最大连接数
}
func (mp *MongoPool) getContextTimeOut() context.Context {
ctx, _ := context.WithTimeout(context.Background(), mp.timeout)
return ctx
}
func (mp *MongoPool) createToChan() {
var conn *mongo.Client
conn, e := mongo.NewClient(options.Client().ApplyURI(mp.uri))
if e != nil {
log.Fatalf("Create the Pool failed,err=%v", e)
}
e = conn.Connect(mp.getContextTimeOut())
if e != nil {
log.Fatalf("Create the Pool failed,err=%v", e)
}
mp.pool <- conn
mp.connections++
}
func (mp *MongoPool) CloseConnection(conn *mongo.Client) error {
select {
case mp.pool <- conn:
return nil
default:
if err := conn.Disconnect(context.TODO()); err != nil {
log.Fatalf("Close the Pool failed,err=%v", err)
return err
}
mp.connections--
return nil
}
}
func (mp *MongoPool) GetConnection() (*mongo.Client, error) {
for {
select {
case conn := <-mp.pool:
err := conn.Ping(mp.getContextTimeOut(), readpref.Primary())
if err != nil {
log.Fatalf("获取连接池连接失败,err=%v", err)
return nil, err
}
return conn, nil
default:
if mp.connections < mp.poolSize {
mp.createToChan()
}
}
}
}
func GetCollection(conn *mongo.Client, dbname, collection string) *mongo.Collection {
return conn.Database(dbname).Collection(collection)
}
|
package service
import (
"testing"
m "../model"
)
func TestVerifyTime(t *testing.T) {
email := m.Email{From: "abc@gmail.com", ScheduledTime: "09 Dec 18 4:36 UTC"}
if email.ScheduledTime != "09 Dec 18 4:36 UTC" {
t.Error("Expected ScheduledTime equal 09 Dec 18 4:36 UTC")
}
if email.From != "abc@gmail.com" {
t.Error("Expected From equal abc@gmail.com")
}
}
|
// Copyright 2014 Dirk Jablonowski. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ambientlight
import (
"github.com/dirkjabl/bricker"
"github.com/dirkjabl/bricker/device"
)
// SetIlluminanceCallbackThreshold creates the subscriber to set the callback thresold.
// Default value is ('x', 0, 0).
func SetIlluminanceCallbackThreshold(id string, uid uint32, t *device.Threshold16, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "SetIlluminanceCallbackThreshold"),
Fid: function_set_illuminance_callback_threshold,
Uid: uid,
Data: t,
Handler: handler,
WithPacket: true}.CreateDevice()
}
// SetIlluminanceCallbackThresholdFuture is a future pattern version for a synchronized call of the subscriber.
// If an error occur, the result is false.
func SetIlluminanceCallbackThresholdFuture(brick *bricker.Bricker, connectorname string, uid uint32, t *device.Threshold16) bool {
future := make(chan bool)
defer close(future)
sub := SetIlluminanceCallbackThreshold("setilluminancecallbackthresholdfuture"+device.GenId(), uid, t,
func(r device.Resulter, err error) {
future <- device.IsEmptyResultOk(r, err)
})
err := brick.Subscribe(sub, connectorname)
if err != nil {
return false
}
return <-future
}
// GetIlluminanceCallbackThreshold creates the subscriber to get the callback thresold.
func GetIlluminanceCallbackThreshold(id string, uid uint32, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "GetIlluminanceCallbackThreshold"),
Fid: function_get_illuminance_callback_threshold,
Uid: uid,
Result: &device.Threshold16{},
Handler: handler,
WithPacket: true}.CreateDevice()
}
// GetIlluminanceCallbackThresholdFuture is a future pattern version for a synchronized call of the subscriber.
// If an error occur, the result is nil.
func GetIlluminanceCallbackThresholdFuture(brick *bricker.Bricker, connectorname string, uid uint32) *device.Threshold16 {
future := make(chan *device.Threshold16)
defer close(future)
sub := GetIlluminanceCallbackThreshold("getilluminancecallbackthresholdfuture"+device.GenId(), uid,
func(r device.Resulter, err error) {
var v *device.Threshold16 = nil
if err == nil {
if value, ok := r.(*device.Threshold16); ok {
v = value
}
}
future <- v
})
err := brick.Subscribe(sub, connectorname)
if err != nil {
return nil
}
return <-future
}
// SetAnalogValueCallbackThreshold creates the subscriber to set the callback thresold.
// Default value is ('x', 0, 0).
func SetAnalogValueCallbackThreshold(id string, uid uint32, t *device.Threshold16, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "SetAnalogValueCallbackThreshold"),
Fid: function_set_analog_value_callback_threshold,
Uid: uid,
Data: t,
Handler: handler,
WithPacket: true}.CreateDevice()
}
// SetAnalogValueCallbackThresholdFuture is a future pattern version for a synchronized call of the subscriber.
// If an error occur, the result is false.
func SetAnalogValueCallbackThresholdFuture(brick *bricker.Bricker, connectorname string, uid uint32, t *device.Threshold16) bool {
future := make(chan bool)
defer close(future)
sub := SetAnalogValueCallbackThreshold("setanalogvaluecallbackthresholdfuture"+device.GenId(), uid, t,
func(r device.Resulter, err error) {
future <- device.IsEmptyResultOk(r, err)
})
err := brick.Subscribe(sub, connectorname)
if err != nil {
return false
}
return <-future
}
// GetAnalogValueCallbackThreshold creates the subscriber to get the callback thresold.
func GetAnalogValueCallbackThreshold(id string, uid uint32, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "GetAnalogValueCallbackThreshold"),
Fid: function_get_analog_value_callback_threshold,
Uid: uid,
Result: &device.Threshold16{},
Handler: handler,
WithPacket: true}.CreateDevice()
}
// GetAnalogValueCallbackThresholdFuture is a future pattern version for a synchronized call of the subscriber.
// If an error occur, the result is nil.
func GetAnalogValueCallbackThresholdFuture(brick *bricker.Bricker, connectorname string, uid uint32) *device.Threshold16 {
future := make(chan *device.Threshold16)
defer close(future)
sub := GetAnalogValueCallbackThreshold("getanalogvaluecallbackthresholdfuture"+device.GenId(), uid,
func(r device.Resulter, err error) {
var v *device.Threshold16 = nil
if err == nil {
if value, ok := r.(*device.Threshold16); ok {
v = value
}
}
future <- v
})
err := brick.Subscribe(sub, connectorname)
if err != nil {
return nil
}
return <-future
}
// IlluminanceReached creates a subscriber for the theshold triggered voltage callback.
func IlluminanceReached(id string, uid uint32, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "IlluminanceReached"),
Fid: callback_illuminance_reached,
Uid: uid,
Result: &Illuminance{},
Handler: handler,
IsCallback: true,
WithPacket: false}.CreateDevice()
}
// AnalogValueReached creates a subscriber for the theshold triggered voltage callback.
func AnalogValueReached(id string, uid uint32, handler func(device.Resulter, error)) *device.Device {
return device.Generator{
Id: device.FallbackId(id, "AnalogValueReached"),
Fid: callback_analog_value_reached,
Uid: uid,
Result: &AnalogValue{},
Handler: handler,
IsCallback: true,
WithPacket: false}.CreateDevice()
}
|
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"Models"
"net/http"
"math/rand"
)
const Rooms = map[string]Models.Room
const KEY_LENGTH = 10
const letterRunes = []string("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func uniqueKey(key) {
recurse := false
for k := range Rooms {
if (k == key) {
recurse := true
}
}
if (recurse) {
return uniqueKey(genRoomKey(KEY_LENGTH))
} else {
return key
}
}
func genRoomKey(n int) {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return uniqueKey(string(b))
}
func createRoom(w http.ResponseWriter, r *http.Request) {
// Creates user and room with a randomly generated key
u := Models.User{ Name: r.UserName, ConnectedAccount: true}
key := genRoomKey(KEY_LENGTH)
Rooms[key] = Models.Room{ Name: r.RoomName, Password: r.RoomPassword, Users: []Models.User{u},
SpotifyPassword: r.SpotifyPassword, SpotfiyUsername: r.SpotfiyUsername}
roomCookie := http.Cookie{ Name: "goqueueRoomKey", Value: key}
userCookie := http.Cookie{ Name: "goqueueUName", Value: r.UserName}
http.SetCookie(w, roomCookie)
http.SetCookie(w, userCookie)
http.Redirect(w, r, "/room/", http.StatusFound)
}
func deleteRoom(w http.ResponseWriter, r *http.Request) {
delete(Rooms, r.RoomKey)
}
func leaveRoom(w http.ResponseWriter, r *http.Request) {
users := Rooms[r.RoomKey].Users
if len(users) == 1 {
deleteRoom(w, r)
} else {
for i := range users {
if users[i].Name == r.UserName {
users[i] = users[0]
Rooms[r.RoomKey].Users := users[1:]
}
}
}
}
func getRoom(w http.ResponseWriter, r *http.Request) {
for _, cookie := range r.Cookies() {
cookie.Value
fmt.Fprint(w, cookie.Name)
}
}
func addUserToRoom(w http.ResponseWriter, r *http.Request) {
user = Models.User{ Name: r.UserName, ConnectedAccount: false}
append(Rooms[r.RoomKey].Users, user)
}
func main() {
rand.Seed(time.Now().UnixNano())
fs := http.FileServer(http.Dir("frontend"))
http.Handle("/test/", http.StripPrefix("/test/", fs))
http.HandleFunc("/room/create/", createRoom)
http.ListenAndServe(":8080", nil)
}
|
package main
import (
"blockchain/certdemo/certdb"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
)
func main() {
//启动消息推送服务
web()
}
type NoBC struct{
Status string
Key string
Cert string
}
func web() {
http.HandleFunc("/queryByNoBC", queryByNoBc)
log.Println("starting service!")
//log.Fatal输出后,会退出程序,执行os.Exit(1)
log.Fatal(http.ListenAndServe(":5000", nil))
}
func queryByNoBc(w http.ResponseWriter,r*http.Request) {
err := r.ParseForm()
if err != nil {
log.Println(err)
return
}
tForm := make(map[string]string)
for a, b := range r.Form {
if len(b) == 0 {
//fmt.Println("a:",a,"b:","null")
tForm[a] = ""
} else {
tForm[a] = b[0]
}
}
fmt.Println(tForm)
fmt.Println(r.RequestURI)
var resp NoBC
resp.Key=tForm["pubKey"]
resp.Key=strings.Replace(resp.Key,"\r","",-1)
//用于检查控制符
//log.Println([]byte(queryDiff.NoBCPubKey))
//本地不用先访问crl,因为添加进crl的时候,删除了cert
resp.Cert,err=certdb.DbCert.Get(resp.Key)
if err!=nil{
resp.Status=err.Error()
}else{
//log.Println(NoBCClientCert)
resp.Status="ok"
}
//resp.Status="ok"
data,err:=json.Marshal(resp)
fmt.Println(string(data))
if err!=nil{
log.Println(err)
}else{
_,err=w.Write(data)
if err!=nil{
log.Println(err)
}
}
}
func queryByNoBcTest(w http.ResponseWriter,r*http.Request) {
var resp NoBC
var NoBCPubKey string=`-----BEGIN EC Public KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+wmZKMQrSnzF0XjCycAjaDo5Ecog
JfuLVvjmpBKhqLd0FQ4RGUjdtV5DzcYN6R74gp6nTlFgTxhIyq0c9vvlKw==
-----END EC Public KEY-----`
log.Println("Get Query by NoBC")
if NoBCPubKey[len(NoBCPubKey)-1]=='\n'{
NoBCPubKey=NoBCPubKey[:len(NoBCPubKey)-1]
log.Println("NoBCPubKey last char is \\n")
}
/*
-----BEGIN EC Public KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+wmZKMQrSnzF0XjCycAjaDo5Ecog
JfuLVvjmpBKhqLd0FQ4RGUjdtV5DzcYN6R74gp6nTlFgTxhIyq0c9vvlKw==
-----END EC Public KEY-----
-----BEGIN CERTIFICATE-----
MIICijCCAi+gAwIBAgIQcE55k4i5XjO3yUdMw0/B1DAKBggqhkjOPQQDAjCBsjEL
MAkGA1UEBhMCQ04xEDAOBgNVBAgTB0JlaWppbmcxFTATBgNVBAcTDHpob25nZ3Vh
bmN1bjEsMA0GA1UECRMGc3RyZWV0MA4GA1UECRMHYWRkcmVzczALBgNVBAkTBGRl
bW8xDzANBgNVBBETBjMxMDAwMDERMA8GA1UEChMIcGFyYWRpc2UxDTALBgNVBAsT
BHRlY3QxGTAXBgNVBAMTEGRlbW8uZXhhbXBsZS5jb20wHhcNMTkwMjE5MTMzNjU4
WhcNMjAwMjE5MTMzNjU4WjBNMQkwBwYDVQQGEwAxCTAHBgNVBAgTADEJMAcGA1UE
BxMAMQkwBwYDVQQJEwAxCTAHBgNVBBETADEJMAcGA1UEChMAMQkwBwYDVQQLEwAw
WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAT7CZkoxCtKfMXReMLJwCNoOjkRyiAl
+4tW+OakEqGot3QVDhEZSN21XkPNxg3pHviCnqdOUWBPGEjKrRz2++Uro4GKMIGH
MA4GA1UdDwEB/wQEAwIBpjAPBgNVHSUECDAGBgRVHSUAMAwGA1UdEwEB/wQCMAAw
KQYDVR0OBCIEILE3wP6Vw19ySz3ZknkX6JORK+MahWv96QNBtcVJFoqVMCsGA1Ud
IwQkMCKAII5LW8yeTR0EB7ScK6R/7EM8LWOWhNgQpyO/6pGWkKPbMAoGCCqGSM49
BAMCA0kAMEYCIQDIi4s54+QTTXZ0BaQT7t+V8EazLW/WNgJ1z6U8iHlYEQIhAJe2
rQ9rst0D6//VZ9cbWw5niUbz55eCbxMkOawT4KqL
-----END CERTIFICATE-----
*/
NoBCPubKey=strings.Replace(NoBCPubKey,"\r","",-1)
fmt.Println(NoBCPubKey)
//用于检查控制符
//log.Println([]byte(queryDiff.NoBCPubKey))
//本地不用先访问crl,因为添加进crl的时候,删除了cert
NoBCClientCert,err:=certdb.DbCert.Get(NoBCPubKey)
fmt.Println(NoBCClientCert)
if err!=nil{
resp.Status=err.Error()
}else{
//log.Println(NoBCClientCert)
resp.Status="ok"
}
resp.Key=NoBCPubKey
resp.Cert=NoBCClientCert
//resp.Status="ok"
data,err:=json.Marshal(resp)
fmt.Println(string(data))
if err!=nil{
log.Println(err)
}else{
_,err=w.Write(data)
if err!=nil{
log.Println(err)
}
}
} |
//常數 下了之後無法再更改 除非同樣常數指令更改
package main
import "fmt"
const a int = 42
var b int = 11
func main() {
fmt.Println(a)
fmt.Printf("%T\n", a)
const a int = 55
fmt.Println(a)
fmt.Println(b)
b = 22
fmt.Println(b)
}
|
// Copyright (c) 2014 Eric Robert. All rights reserved.
package shard
import (
"fmt"
"github.com/EricRobert/goreports"
"path"
)
type URLSharder struct {
Table Table
}
func (h *URLSharder) Shard(req *report.Request) (url string, k int, err error) {
p := req.Request.URL.Path
key := path.Base(p)
if p == "." || p == "/" {
err = fmt.Errorf("URL '%s' does not ends with an id", p)
return
}
url, k = h.Table.GetURL([]byte(key))
return
}
|
package v2
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/url"
"strings"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/traPtitech/trap-collection-server/src/domain"
"github.com/traPtitech/trap-collection-server/src/domain/values"
"github.com/traPtitech/trap-collection-server/src/repository"
mockRepository "github.com/traPtitech/trap-collection-server/src/repository/mock"
"github.com/traPtitech/trap-collection-server/src/service"
mockStorage "github.com/traPtitech/trap-collection-server/src/storage/mock"
"github.com/traPtitech/trap-collection-server/testdata"
)
func TestSaveGameVideo(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDB := mockRepository.NewMockDB(ctrl)
mockGameRepository := mockRepository.NewMockGameV2(ctrl)
mockGameVideoRepository := mockRepository.NewMockGameVideoV2(ctrl)
type test struct {
description string
gameID values.GameID
isValidFile bool
videoType values.GameVideoType
GetGameErr error
executeRepositorySaveGameVideo bool
RepositorySaveGameVideoErr error
executeStorageSaveGameVideo bool
StorageSaveGameVideoErr error
isErr bool
err error
}
testCases := []test{
{
description: "特に問題ないのでエラーなし",
gameID: values.NewGameID(),
isValidFile: true,
videoType: values.GameVideoTypeMp4,
executeRepositorySaveGameVideo: true,
executeStorageSaveGameVideo: true,
},
{
description: "GetGameがErrRecordNotFoundなのでErrInvalidGameID",
gameID: values.NewGameID(),
isValidFile: true,
videoType: values.GameVideoTypeMp4,
GetGameErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameID,
},
{
description: "GetGameがエラーなのでエラー",
gameID: values.NewGameID(),
isValidFile: true,
videoType: values.GameVideoTypeMp4,
GetGameErr: errors.New("error"),
isErr: true,
},
{
description: "動画が不正なのでエラー",
gameID: values.NewGameID(),
executeStorageSaveGameVideo: true,
isValidFile: false,
isErr: true,
err: service.ErrInvalidFormat,
},
{
description: "repository.SaveGameVideoがエラーなのでエラー",
gameID: values.NewGameID(),
isValidFile: true,
videoType: values.GameVideoTypeMp4,
executeRepositorySaveGameVideo: true,
executeStorageSaveGameVideo: true,
RepositorySaveGameVideoErr: errors.New("error"),
isErr: true,
},
{
description: "storage.SaveGameVideoがエラーなのでエラー",
gameID: values.NewGameID(),
isValidFile: true,
videoType: values.GameVideoTypeMp4,
executeRepositorySaveGameVideo: true,
executeStorageSaveGameVideo: true,
StorageSaveGameVideoErr: errors.New("error"),
isErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
buf := bytes.NewBuffer(nil)
mockGameVideoStorage := mockStorage.NewGameVideo(ctrl, buf)
gameVideoService := NewGameVideo(
mockDB,
mockGameRepository,
mockGameVideoRepository,
mockGameVideoStorage,
)
var file io.Reader
var expectBytes []byte
if testCase.isValidFile {
imgBuf := bytes.NewBuffer(nil)
err := func() error {
var path string
if testCase.videoType == values.GameVideoTypeMp4 {
path = "1.mp4"
} else {
t.Fatalf("invalid video type: %v\n", testCase.videoType)
}
f, err := testdata.FS.Open(path)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
_, err = io.Copy(imgBuf, f)
if err != nil {
return fmt.Errorf("failed to copy file: %w", err)
}
return nil
}()
if err != nil {
t.Fatalf("failed to encode video: %s", err)
}
file = imgBuf
expectBytes = imgBuf.Bytes()
} else {
file = strings.NewReader("invalid file")
}
mockGameRepository.
EXPECT().
GetGame(gomock.Any(), testCase.gameID, repository.LockTypeRecord).
Return(nil, testCase.GetGameErr)
if testCase.executeRepositorySaveGameVideo {
mockGameVideoRepository.
EXPECT().
SaveGameVideo(gomock.Any(), testCase.gameID, gomock.Any()).
Return(testCase.RepositorySaveGameVideoErr)
}
if testCase.executeStorageSaveGameVideo {
mockGameVideoStorage.
EXPECT().
SaveGameVideo(gomock.Any(), gomock.Any()).
Return(testCase.StorageSaveGameVideoErr)
}
video, err := gameVideoService.SaveGameVideo(ctx, file, testCase.gameID)
if testCase.isErr {
if testCase.err == nil {
assert.Error(t, err)
} else if !errors.Is(err, testCase.err) {
t.Errorf("error must be %v, but actual is %v", testCase.err, err)
}
} else {
assert.NoError(t, err)
}
if err != nil || testCase.isErr {
return
}
assert.Equal(t, testCase.videoType, video.GetType())
assert.WithinDuration(t, time.Now(), video.GetCreatedAt(), time.Second)
assert.Equal(t, expectBytes, buf.Bytes())
})
}
}
func TestGetGameVideos(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDB := mockRepository.NewMockDB(ctrl)
mockGameRepository := mockRepository.NewMockGameV2(ctrl)
mockGameVideoRepository := mockRepository.NewMockGameVideoV2(ctrl)
mockGameVideoStorage := mockStorage.NewGameVideo(ctrl, nil)
gameVideoService := NewGameVideo(
mockDB,
mockGameRepository,
mockGameVideoRepository,
mockGameVideoStorage,
)
type test struct {
description string
gameID values.GameID
getGameErr error
executeGetGameVideos bool
getGameVideosErr error
isErr bool
gameVideos []*domain.GameVideo
err error
}
now := time.Now()
testCases := []test{
{
description: "特に問題ないのでエラーなし",
gameID: values.NewGameID(),
executeGetGameVideos: true,
gameVideos: []*domain.GameVideo{
domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
now,
),
},
},
{
description: "GetGameがErrRecordNotFoundなのでErrInvalidGameID",
gameID: values.NewGameID(),
getGameErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameID,
},
{
description: "GetGameがエラーなのでエラー",
gameID: values.NewGameID(),
getGameErr: errors.New("error"),
isErr: true,
},
{
description: "動画がなくてもエラーなし",
gameID: values.NewGameID(),
executeGetGameVideos: true,
gameVideos: []*domain.GameVideo{},
},
{
description: "動画が複数でもエラーなし",
gameID: values.NewGameID(),
executeGetGameVideos: true,
gameVideos: []*domain.GameVideo{
domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
now,
),
domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
now.Add(-time.Second),
),
},
},
{
description: "GetGameVideosがエラーなのでエラー",
gameID: values.NewGameID(),
executeGetGameVideos: true,
getGameVideosErr: errors.New("error"),
isErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
mockGameRepository.
EXPECT().
GetGame(gomock.Any(), testCase.gameID, repository.LockTypeNone).
Return(nil, testCase.getGameErr)
if testCase.executeGetGameVideos {
mockGameVideoRepository.
EXPECT().
GetGameVideos(gomock.Any(), testCase.gameID, repository.LockTypeNone).
Return(testCase.gameVideos, testCase.getGameVideosErr)
}
gameVideos, err := gameVideoService.GetGameVideos(ctx, testCase.gameID)
if testCase.isErr {
if testCase.err == nil {
assert.Error(t, err)
} else if !errors.Is(err, testCase.err) {
t.Errorf("error must be %v, but actual is %v", testCase.err, err)
}
} else {
assert.NoError(t, err)
}
if err != nil || testCase.isErr {
return
}
for i, gameVideo := range gameVideos {
assert.Equal(t, testCase.gameVideos[i].GetID(), gameVideo.GetID())
assert.Equal(t, testCase.gameVideos[i].GetType(), gameVideo.GetType())
assert.Equal(t, testCase.gameVideos[i].GetCreatedAt(), gameVideo.GetCreatedAt())
}
})
}
}
func TestGetGameVideo(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDB := mockRepository.NewMockDB(ctrl)
mockGameRepository := mockRepository.NewMockGameV2(ctrl)
mockGameVideoRepository := mockRepository.NewMockGameVideoV2(ctrl)
mockGameVideoStorage := mockStorage.NewGameVideo(ctrl, nil)
gameVideoService := NewGameVideo(
mockDB,
mockGameRepository,
mockGameVideoRepository,
mockGameVideoStorage,
)
type test struct {
description string
gameID values.GameID
gameVideoID values.GameVideoID
getGameErr error
executeGetGameVideo bool
video *repository.GameVideoInfo
getGameVideoErr error
executeGetTempURL bool
videoURL values.GameVideoTmpURL
getTempURLErr error
isErr bool
err error
}
urlLink, err := url.Parse("https://example.com")
if err != nil {
t.Fatalf("failed to encode video: %v", err)
}
gameID1 := values.NewGameID()
gameID2 := values.NewGameID()
testCases := []test{
{
description: "特に問題ないのでエラーなし",
gameID: gameID1,
executeGetGameVideo: true,
video: &repository.GameVideoInfo{
GameVideo: domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
time.Now(),
),
GameID: gameID1,
},
executeGetTempURL: true,
videoURL: values.NewGameVideoTmpURL(urlLink),
},
{
description: "GetGameがErrRecordNotFoundなのでErrInvalidGameID",
gameID: values.NewGameID(),
getGameErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameID,
},
{
description: "GetGameがエラーなのでエラー",
gameID: values.NewGameID(),
getGameErr: errors.New("error"),
isErr: true,
},
{
description: "GetGameVideoがErrRecordNotFoundなのでErrInvalidGameVideoID",
gameID: values.NewGameID(),
executeGetGameVideo: true,
getGameVideoErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameVideoID,
},
{
description: "ゲーム動画に紐づくゲームIDが違うのでErrInvalidGameVideoID",
gameID: values.NewGameID(),
executeGetGameVideo: true,
video: &repository.GameVideoInfo{
GameVideo: domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
time.Now(),
),
GameID: values.NewGameID(),
},
isErr: true,
err: service.ErrInvalidGameVideoID,
},
{
description: "GetGameVideoがエラーなのでエラー",
gameID: values.NewGameID(),
executeGetGameVideo: true,
getGameVideoErr: errors.New("error"),
isErr: true,
},
{
description: "GetTempURLがエラーなのでエラー",
gameID: gameID2,
executeGetGameVideo: true,
video: &repository.GameVideoInfo{
GameVideo: domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
time.Now(),
),
GameID: gameID2,
},
executeGetTempURL: true,
videoURL: values.NewGameVideoTmpURL(urlLink),
getTempURLErr: errors.New("error"),
isErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
mockGameRepository.
EXPECT().
GetGame(ctx, testCase.gameID, repository.LockTypeNone).
Return(nil, testCase.getGameErr)
if testCase.executeGetGameVideo {
mockGameVideoRepository.
EXPECT().
GetGameVideo(ctx, testCase.gameVideoID, repository.LockTypeRecord).
Return(testCase.video, testCase.getGameVideoErr)
}
if testCase.executeGetTempURL {
mockGameVideoStorage.
EXPECT().
GetTempURL(ctx, testCase.video.GameVideo, time.Minute).
Return(testCase.videoURL, testCase.getTempURLErr)
}
tmpURL, err := gameVideoService.GetGameVideo(ctx, testCase.gameID, testCase.gameVideoID)
if testCase.isErr {
if testCase.err == nil {
assert.Error(t, err)
} else if !errors.Is(err, testCase.err) {
t.Errorf("error must be %v, but actual is %v", testCase.err, err)
}
} else {
assert.NoError(t, err)
}
if err != nil {
return
}
assert.Equal(t, testCase.videoURL, tmpURL)
})
}
}
func TestGetGameVideoMeta(t *testing.T) {
t.Parallel()
ctx := context.Background()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDB := mockRepository.NewMockDB(ctrl)
mockGameRepository := mockRepository.NewMockGameV2(ctrl)
mockGameVideoRepository := mockRepository.NewMockGameVideoV2(ctrl)
mockGameVideoStorage := mockStorage.NewGameVideo(ctrl, nil)
gameVideoService := NewGameVideo(
mockDB,
mockGameRepository,
mockGameVideoRepository,
mockGameVideoStorage,
)
type test struct {
description string
gameID values.GameID
gameVideoID values.GameVideoID
getGameErr error
executeGetGameVideo bool
video *repository.GameVideoInfo
getGameVideoErr error
isErr bool
err error
}
gameID1 := values.NewGameID()
testCases := []test{
{
description: "特に問題ないのでエラーなし",
gameID: gameID1,
executeGetGameVideo: true,
video: &repository.GameVideoInfo{
GameVideo: domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
time.Now(),
),
GameID: gameID1,
},
},
{
description: "GetGameがErrRecordNotFoundなのでErrInvalidGameID",
gameID: values.NewGameID(),
getGameErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameID,
},
{
description: "GetGameがエラーなのでエラー",
gameID: values.NewGameID(),
getGameErr: errors.New("error"),
isErr: true,
},
{
description: "GetGameVideoがErrRecordNotFoundなのでErrInvalidGameVideoID",
gameID: values.NewGameID(),
executeGetGameVideo: true,
getGameVideoErr: repository.ErrRecordNotFound,
isErr: true,
err: service.ErrInvalidGameVideoID,
},
{
description: "ゲーム動画に紐づくゲームIDが違うのでErrInvalidGameVideoID",
gameID: values.NewGameID(),
executeGetGameVideo: true,
video: &repository.GameVideoInfo{
GameVideo: domain.NewGameVideo(
values.NewGameVideoID(),
values.GameVideoTypeMp4,
time.Now(),
),
GameID: values.NewGameID(),
},
isErr: true,
err: service.ErrInvalidGameVideoID,
},
{
description: "GetGameVideoがエラーなのでエラー",
gameID: values.NewGameID(),
executeGetGameVideo: true,
getGameVideoErr: errors.New("error"),
isErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) {
mockGameRepository.
EXPECT().
GetGame(ctx, testCase.gameID, repository.LockTypeNone).
Return(nil, testCase.getGameErr)
if testCase.executeGetGameVideo {
mockGameVideoRepository.
EXPECT().
GetGameVideo(ctx, testCase.gameVideoID, repository.LockTypeNone).
Return(testCase.video, testCase.getGameVideoErr)
}
gameVideo, err := gameVideoService.GetGameVideoMeta(ctx, testCase.gameID, testCase.gameVideoID)
if testCase.isErr {
if testCase.err == nil {
assert.Error(t, err)
} else if !errors.Is(err, testCase.err) {
t.Errorf("error must be %v, but actual is %v", testCase.err, err)
}
} else {
assert.NoError(t, err)
}
if err != nil {
return
}
assert.Equal(t, testCase.video.GameVideo.GetID(), gameVideo.GetID())
assert.Equal(t, testCase.video.GameVideo.GetType(), gameVideo.GetType())
assert.Equal(t, testCase.video.GameVideo.GetCreatedAt(), gameVideo.GetCreatedAt())
})
}
}
|
package divisiblesumpairs
// https://www.hackerrank.com/challenges/divisible-sum-pairs
func nChooseK(N, K uint32) uint64 {
result := uint64(1)
for k := uint64(0); k < uint64(K); k++ {
result = result * (uint64(N) - k) / (k + 1)
}
return result
}
// DivisibleSumPairs - implements the solution to the problem
func DivisibleSumPairs(n int32, k int32, ar []int32) int32 {
counted := make(map[uint32]uint32)
for _, value := range ar {
rest := uint32(value % k)
_, present := counted[rest]
if present {
counted[rest]++
} else {
counted[rest] = 1
}
}
total := uint64(0)
covered := make(map[uint32]struct{})
exists := struct{}{}
for a := range counted {
countedA, _ := counted[a]
_, coveredContainsA := covered[a]
if coveredContainsA {
continue
}
if a == 0 {
total += nChooseK(countedA, 2)
covered[a] = exists
} else {
b := uint32(k) - a
if b == a {
total += nChooseK(countedA, 2)
covered[a] = exists
} else {
countedB, countedContainsB := counted[b]
if countedContainsB {
total += uint64(countedA * countedB)
covered[a] = exists
covered[b] = exists
}
}
}
}
return int32(total)
}
|
package boxxy
func newBlock(offset int) *block {
return &block{offset: offset}
}
type block struct {
buf [32]interface{}
tail int // This actually could be a uint8.. hmm
offset int
}
func (b *block) get(idx int) interface{} {
return b.buf[idx]
}
func (b *block) append(val interface{}) (ok bool) {
if b.tail == 32 {
return
}
b.buf[b.tail] = val
b.tail++
return true
}
func (b *block) prepend(val interface{}) (ok bool) {
if b.tail == 32 {
return
}
b.shiftRight(0)
b.buf[0] = val
return true
}
func (b *block) insert(idx int, val interface{}) (overflow interface{}) {
if b.tail == 32 {
overflow = b.buf[31]
}
b.shiftRight(idx)
b.buf[idx] = val
return
}
func (b *block) forEach(fn func(i int, val interface{}) (end bool)) (ended bool) {
for i := 0; i < b.tail; i++ {
if fn(i+b.offset, b.buf[i]) {
ended = true
return
}
}
return
}
func (b *block) shiftRight(i int) {
var cval interface{}
end := b.tail
if end == 32 {
end = 31
} else {
b.tail++
}
for ; i <= end; i++ {
item := b.buf[i]
b.buf[i] = cval
cval = item
}
}
|
package model
//Content ...
type Content struct {
Type string `json:"type"`
Value string `json:"value"`
}
// Email Model Structure
type Email struct {
From string
To []string
Cc []string
Bcc []string
Subject string
Content []Content
Status string
ScheduledTime string
}
|
package ssdb
//ssdb连接池
import (
// "encoding/json"
"errors"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/ssdb/gossdb/ssdb"
)
//ssdb连接信息
type SsdbProvider struct {
conn *ssdb.Client
Host string
Port int
// MaxLifetime int64
}
//ssdb初始化连接
func (p *SsdbProvider) connectInit() error {
var err error
p.Host = beego.AppConfig.String("ssdb_host")
port := beego.AppConfig.String("ssdb_port")
p.Port, _ = strconv.Atoi(port)
p.conn, err = ssdb.Connect(p.Host, p.Port)
return err
}
////NewSsdbCache create new ssdb adapter.
//func NewSsdbCache() cache.Cache {
// return &Cache{}
//}
// Get get value from memcache.
func (rc *SsdbProvider) Get(key string) interface{} {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return nil
}
}
value, err := rc.conn.Get(key)
if err == nil {
return value
}
return nil
}
// GetMulti get value from memcache.
func (rc *SsdbProvider) GetMulti(keys []string) []interface{} {
size := len(keys)
var values []interface{}
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
for i := 0; i < size; i++ {
values = append(values, err)
}
return values
}
}
res, err := rc.conn.Do("multi_get", keys)
resSize := len(res)
if err == nil {
for i := 1; i < resSize; i += 2 {
values = append(values, res[i+1])
}
return values
}
for i := 0; i < size; i++ {
values = append(values, err)
}
return values
}
// DelMulti get value from memcache.
func (rc *SsdbProvider) DelMulti(keys []string) error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Do("multi_del", keys)
return err
}
// Put put value to memcache. only support string.
func (rc *SsdbProvider) Put(key string, value interface{}, timeout time.Duration) error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
v, ok := value.(string)
if !ok {
return errors.New("value must string")
}
var resp []string
var err error
ttl := int(timeout / time.Second)
if ttl < 0 {
resp, err = rc.conn.Do("set", key, v)
} else {
resp, err = rc.conn.Do("setx", key, v, ttl)
}
if err != nil {
return err
}
if len(resp) == 2 && resp[0] == "ok" {
return nil
}
return errors.New("bad response")
}
// Delete delete value in memcache.
func (rc *SsdbProvider) Delete(key string) error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Del(key)
return err
}
// Incr increase counter.
func (rc *SsdbProvider) Incr(key string) error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Do("incr", key, 1)
return err
}
// Decr decrease counter.
func (rc *SsdbProvider) Decr(key string) error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
_, err := rc.conn.Do("incr", key, -1)
return err
}
// IsExist check value exists in memcache.
func (rc *SsdbProvider) IsExist(key string) bool {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return false
}
}
resp, err := rc.conn.Do("exists", key)
if err != nil {
return false
}
if len(resp) == 2 && resp[1] == "1" {
return true
}
return false
}
// ClearAll clear all cached in memcache.
func (rc *SsdbProvider) ClearAll() error {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return err
}
}
keyStart, keyEnd, limit := "", "", 50
resp, err := rc.Scan(keyStart, keyEnd, limit)
for err == nil {
size := len(resp)
if size == 1 {
return nil
}
keys := []string{}
for i := 1; i < size; i += 2 {
keys = append(keys, resp[i])
}
_, e := rc.conn.Do("multi_del", keys)
if e != nil {
return e
}
keyStart = resp[size-2]
resp, err = rc.Scan(keyStart, keyEnd, limit)
}
return err
}
// Scan key all cached in ssdb.
func (rc *SsdbProvider) Scan(keyStart string, keyEnd string, limit int) ([]string, error) {
if rc.conn == nil {
if err := rc.connectInit(); err != nil {
return nil, err
}
}
resp, err := rc.conn.Do("scan", keyStart, keyEnd, limit)
if err != nil {
return nil, err
}
return resp, nil
}
|
package model
import "errors"
var (
ErrParam = errors.New("Param Error.")
)
|
package command
import (
"os"
"path/filepath"
"github.com/codegangsta/cli"
"github.com/dnaeon/gru/catalog"
"github.com/dnaeon/gru/module"
"github.com/dnaeon/gru/resource"
)
// NewApplyCommand creates a new sub-command for
// applying configurations on the local system
func NewApplyCommand() cli.Command {
cmd := cli.Command{
Name: "apply",
Usage: "apply configuration on the local system",
Action: execApplyCommand,
Flags: []cli.Flag{
cli.StringFlag{
Name: "siterepo",
Value: "",
Usage: "path/url to the site repo",
EnvVar: "GRU_SITEREPO",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "just report what would be done, instead of doing it",
},
},
}
return cmd
}
// Executes the "apply" command
func execApplyCommand(c *cli.Context) {
if len(c.Args()) < 1 {
displayError(errNoModuleName, 64)
}
config := &catalog.Config{
Main: c.Args()[0],
DryRun: c.Bool("dry-run"),
ModuleConfig: &module.Config{
Path: filepath.Join(c.String("siterepo"), "modules"),
ResourceConfig: &resource.Config{
SiteRepo: c.String("siterepo"),
Writer: os.Stdout,
},
},
}
katalog, err := catalog.Load(config)
if err != nil {
displayError(err, 1)
}
err = katalog.Run()
if err != nil {
displayError(err, 1)
}
}
|
package delete
import (
"encoding/json"
"net/http"
"github.com/ocoscope/face/db"
"github.com/ocoscope/face/utils"
"github.com/ocoscope/face/utils/answer"
)
func Department(w http.ResponseWriter, r *http.Request) {
type tbody struct {
CompanyID, UserID, DepartmentID int64
AccessToken string
}
var body tbody
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
utils.Message(w, answer.WRONG_DATA, 400)
return
}
database, err := db.CopmanyDB(body.CompanyID)
if err != nil {
utils.Message(w, answer.NOT_FOUND_COMPANY, 400)
return
}
defer database.Close()
err = db.CheckUserAccessToken(database, body.UserID, body.AccessToken)
if err != nil {
utils.Message(w, answer.UNAUTHORIZED, 401)
return
}
userRoleID, err := db.GetUserRoleID(database, body.UserID)
if err != nil || userRoleID != 1 {
utils.Message(w, answer.ACCESS_DENIED, 400)
return
}
// удаляем сотрудников отдела
db.DeleteEmployeeByDepartment(database, body.DepartmentID)
// удаляем сам отдел
err = db.DeleteDepartment(database, body.DepartmentID)
if err != nil {
utils.Message(w, answer.FR, 500)
return
}
utils.Message(w, answer.SD_DEPARTMENT, 200)
}
|
package request
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNewRequestBuilderWithDefaults(t *testing.T) {
builder := NewRequestBuilder()
builder.WithUrl(POSTMAN_ECHO_ROOT)
r1 := builder.Build()
assert.NotNil(t, r1, "Should not be nil")
r2 := r1.getUnderlyingRequest()
c := r1.getUnderlyingHttpClient()
assert.NotNil(t, r2, "Should not be nil")
assert.Equal(t, "GET", r2.Method, "Should equal GET method")
assert.True(t, len(r2.Header) == 0, "Should have empty header map")
assert.Empty(t, r2.Header.Get("Authorization"), "Should not have set authorization header")
assert.Equal(t, 30*time.Second, c.Timeout, "Should equal 30 seconds")
}
func TestNewHttpClientWithCustomTimeout(t *testing.T) {
client := newHttpClient(45 * time.Second)
assert.NotNil(t, client, "Should not be nil")
assert.Equal(t, 45*time.Second, client.Timeout, "Should equal 45 seconds timeout")
}
|
package main
import "fmt"
/*
- Utilizando o exercício anterior, remova uma entrada do map e demonstre o map inteiro utilizando range.
*/
func main() {
mepezin := map[string][]string{"cores": []string{"verde", "azul", "preto"}}
mepezin["tools"] = []string{"gobuster", "dirbuster", "set"}
fmt.Println(mepezin)
delete(mepezin, "tools")
for i, v := range mepezin {
fmt.Println(i, v)
}
}
|
package main
import (
"bytes"
"flag"
"fmt"
"gopkg.in/russross/blackfriday.v2"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func runCommand(command string) {
args := strings.Fields(command)
var cmd *exec.Cmd
if len(args) < 2 {
cmd = exec.Command(args[0])
} else {
cmd = exec.Command(args[0], args[1:]...)
}
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Print(out.String())
}
// Converts markdown to html and opens the resulting file in chrome.
func governMarkdown(filePath string) {
markdownFile, _ := ioutil.ReadFile(filePath)
output := blackfriday.Run(markdownFile)
dir, _ := ioutil.TempDir("", "markdown")
outputPath := filepath.Join(dir, "converted_markdown.html")
f, _ := os.Create(outputPath)
runCommand(strings.Join([]string{"open", outputPath}, " "))
f.Write(output)
f.Sync()
f.Close()
}
func main() {
filePtr := flag.String("file", "", "File to determine a task for")
searchPtr := flag.Bool("search", false, "Search for a file")
flag.Parse()
if *filePtr == "" && *searchPtr == false {
fmt.Println("no file supplied to govern, please use the -file or -search flag")
os.Exit(0)
}
if *searchPtr == true {
Search()
} else if *filePtr != "" {
// TODO find the full filepath by combining current dir with parameter
filePath := *filePtr
if strings.HasSuffix(filePath, ".clj") {
fmt.Println("clojure file found, executing load-file")
// TODO inspect file for deftest OR clojure.test for more stable address.
} else if strings.HasSuffix(filePath, ".go") {
fmt.Println("go file found, executing go test")
runCommand("go test")
} else if strings.HasSuffix(filePath, ".md") {
governMarkdown(filePath)
}
}
}
|
package main
import (
"github.com/hexoul/metric-collector/collector"
"github.com/hexoul/metric-collector/imon"
)
func init() {
}
func main() {
collector.New(10, imon.MakeRequestContext)
}
|
package users
import (
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
//MysqlStore represents a user store backed by mySQL
type MysqlStore struct {
db *sql.DB
}
//NewMysqlStore constructs a new MysqlStore
func NewMysqlStore(db *sql.DB) *MysqlStore {
//initialize and return a new MysqlStore struct
return &MysqlStore{db}
}
//Returns a user by getting the ID from the database, returns an error if the user does not exist
func (ms *MysqlStore) GetByID(id int64) (*User, error) {
rows := ms.db.QueryRow("SELECT id, email, pass_hash, usr_name, first_name, last_name, photo_url FROM Users WHERE id=?", id)
var email, userName, fName, lName, photo_url, pHash string
var user User
err := rows.Scan(&id, &email, &pHash, &userName, &fName, &lName, &photo_url)
if err != nil {
return nil, err
}
user = User{ID: id, Email: email, PassHash: []byte(pHash), UserName: userName, FirstName: fName, LastName: lName, PhotoURL: photo_url}
return &user, nil
}
//Returns a user by getting the Email from the database, returns an error if the user does not exist
func (ms *MysqlStore) GetByEmail(email string) (*User, error) {
rows := ms.db.QueryRow("SELECT id, email, pass_hash, usr_name, first_name, last_name, photo_url FROM Users WHERE email=?", email)
var id int64
var username, fName, lName, photo_url, pHash string
var user User
err := rows.Scan(&id, &email, &pHash, &username, &fName, &lName, &photo_url)
if err != nil {
return nil, err
}
user = User{ID: id, Email: email, PassHash: []byte(pHash), UserName: username, FirstName: fName, LastName: lName, PhotoURL: photo_url}
return &user, nil
}
//Returns a user by getting the Username from the database, returns an error if the user does not exist
func (ms *MysqlStore) GetByUserName(username string) (*User, error) {
rows := ms.db.QueryRow("SELECT id, email, pass_hash, usr_name, first_name, last_name, photo_url FROM Users WHERE usr_name=?", username)
var id int64
var email, fName, lName, photo_url, pHash string
var user User
err := rows.Scan(&id, &email, &pHash, &username, &fName, &lName, &photo_url)
if err != nil {
return nil, err
}
user = User{ID: id, Email: email, PassHash: []byte(pHash), UserName: username, FirstName: fName, LastName: lName, PhotoURL: photo_url}
return &user, nil
}
//Inserts a new user into the user store and returns that user, returns an error if the user cannot be inserted or the id cannot be retrieved
func (ms *MysqlStore) Insert(user *User) (*User, error) {
userCopy := user
insq := "INSERT INTO Users(email, pass_hash, usr_name, first_name, last_name, photo_url) VALUES (?,?,?,?,?,?)"
res, err := ms.db.Exec(insq, user.Email, user.PassHash, user.UserName, user.FirstName, user.LastName, user.PhotoURL)
if err != nil {
return nil, err
}
id, err := res.LastInsertId()
if err != nil {
return nil, err
}
userCopy.ID = id
return userCopy, nil
}
//Updates the information about a user provided by ID and return the updated user, returns an erros if the update is illegal or the user does not exist
func (ms *MysqlStore) Update(id int64, updates *Updates) (*User, error) {
user, err := ms.GetByID(id)
if err != nil {
return nil, err
}
err = user.ApplyUpdates(updates)
if err != nil {
return nil, err
}
_, err = ms.db.Exec("UPDATE Users SET first_name = ?, last_name = ? WHERE id = ?", updates.FirstName, updates.LastName, id)
if err != nil {
return nil, err
}
return user, nil
}
//Delete a user from the user store, returns an error if the user cannot be found
func (ms *MysqlStore) Delete(id int64) error {
_, err := ms.db.Exec("DELETE FROM Users WHERE id=?", id)
if err != nil {
return err
}
return nil
}
//Logs a certain successful login attempt by its user id, time of login, and ip address of login
func (ms *MysqlStore) Log(id int64, ipAddr string) error {
if len(ipAddr) > 45 {
return fmt.Errorf("invalid ip address")
}
insq := "INSERT INTO UserLog(usr_id, signin_dt, client_IP) VALUES (?,?,?)"
_, err := ms.db.Exec(insq, id, time.Now(), ipAddr)
if err != nil {
return err
}
return nil
}
|
package main
import (
"fmt"
"math"
)
func maximumGap(nums []int) int {
if len(nums) <= 1 {
return 0
}
min, max := nums[0], nums[0]
for _, v := range nums {
if v < min {
min = v
}
if v > max {
max = v
}
}
bSize := (max - min + len(nums)) / len(nums)
bNum := (max - min + bSize) / bSize
valueToIndex := func(v int) int {
return (v - min) / bSize
}
bMin := make([]int, bNum)
bMax := make([]int, bNum)
updateBucket := func(v int) {
bID := valueToIndex(v)
if v < bMin[bID] {
bMin[bID] = v
}
if v > bMax[bID] {
bMax[bID] = v
}
}
for i := 0; i < bNum; i++ {
bMin[i], bMax[i] = math.MaxInt32, math.MinInt32
}
for _, v := range nums {
updateBucket(v)
}
ans, lastMax := 0, math.MinInt32
for i := 0; i < bNum; i++ {
if bMin[i] != math.MaxInt32 {
gap := bMax[i] - bMin[i]
if gap > ans {
ans = gap
}
if lastMax != math.MinInt32 {
gap = bMin[i] - lastMax
if gap > ans {
ans = gap
}
}
lastMax = bMax[i]
}
}
return ans
}
func main() {
fmt.Println(maximumGap([]int{1, 3, 100}))
fmt.Println(maximumGap([]int{3, 6, 9, 1}))
fmt.Println(maximumGap([]int{10}))
}
|
// Copyright (c) Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package managedcluster
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
clusterv1 "github.com/open-cluster-management/api/cluster/v1"
workv1 "github.com/open-cluster-management/api/work/v1"
hivev1 "github.com/openshift/hive/apis/hive/v1"
"github.com/open-cluster-management/applier/pkg/applier"
libgometav1 "github.com/open-cluster-management/library-go/pkg/apis/meta/v1"
"github.com/open-cluster-management/managedcluster-import-controller/pkg/bindata"
)
// constants for delete work and finalizer
const (
managedClusterFinalizer string = "managedcluster-import-controller.open-cluster-management.io/cleanup"
registrationFinalizer string = "cluster.open-cluster-management.io/api-resource-cleanup"
)
const clusterLabel string = "cluster.open-cluster-management.io/managedCluster"
const selfManagedLabel string = "local-cluster"
const autoImportRetryName string = "autoImportRetry"
/* #nosec */
const autoImportSecretName string = "auto-import-secret"
const ManagedClusterImportSucceeded string = "ManagedClusterImportSucceeded"
const curatorJobPrefix string = "curator-job"
var log = logf.Log.WithName("controller_managedcluster")
/**
* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
* business logic. Delete these comments after modifying this file.*
*/
// customClient will do get secret without cache, other operations are like normal cache client
type customClient struct {
client.Client
APIReader client.Reader
}
// newCustomClient creates custom client to do get secret without cache
func newCustomClient(client client.Client, apiReader client.Reader) client.Client {
return customClient{
Client: client,
APIReader: apiReader,
}
}
func (cc customClient) Get(ctx context.Context, key client.ObjectKey, obj runtime.Object) error {
if _, ok := obj.(*corev1.Secret); ok {
return cc.APIReader.Get(ctx, key, obj)
}
return cc.Client.Get(ctx, key, obj)
}
func newManagedClusterSpecPredicate() predicate.Predicate {
return predicate.Predicate(predicate.Funcs{
GenericFunc: func(e event.GenericEvent) bool { return false },
CreateFunc: func(e event.CreateEvent) bool { return true },
DeleteFunc: func(e event.DeleteEvent) bool { return true },
UpdateFunc: func(e event.UpdateEvent) bool {
if e.MetaOld == nil {
log.Error(nil, "Update event has no old metadata", "event", e)
return false
}
if e.ObjectOld == nil {
log.Error(nil, "Update event has no old runtime object to update", "event", e)
return false
}
if e.ObjectNew == nil {
log.Error(nil, "Update event has no new runtime object for update", "event", e)
return false
}
if e.MetaNew == nil {
log.Error(nil, "Update event has no new metadata", "event", e)
return false
}
newManagedCluster, okNew := e.ObjectNew.(*clusterv1.ManagedCluster)
oldManagedCluster, okOld := e.ObjectOld.(*clusterv1.ManagedCluster)
if okNew && okOld {
return !reflect.DeepEqual(newManagedCluster.Spec, oldManagedCluster.Spec) ||
checkOffLine(newManagedCluster) != checkOffLine(oldManagedCluster) ||
newManagedCluster.DeletionTimestamp != nil
// !reflect.DeepEqual(newManagedCluster.Status.Conditions, oldManagedCluster.Status.Conditions)
}
return false
},
})
}
func newManifestWorkSpecPredicate() predicate.Predicate {
return predicate.Predicate(predicate.Funcs{
GenericFunc: func(e event.GenericEvent) bool { return false },
CreateFunc: func(e event.CreateEvent) bool { return false },
DeleteFunc: func(e event.DeleteEvent) bool { return true },
UpdateFunc: func(e event.UpdateEvent) bool {
if e.MetaOld == nil {
log.Error(nil, "Update event has no old metadata", "event", e)
return false
}
if e.ObjectOld == nil {
log.Error(nil, "Update event has no old runtime object to update", "event", e)
return false
}
if e.ObjectNew == nil {
log.Error(nil, "Update event has no new runtime object for update", "event", e)
return false
}
if e.MetaNew == nil {
log.Error(nil, "Update event has no new metadata", "event", e)
return false
}
newManifestWork, okNew := e.ObjectNew.(*workv1.ManifestWork)
oldManifestWork, okOld := e.ObjectOld.(*workv1.ManifestWork)
if okNew && okOld {
return !reflect.DeepEqual(newManifestWork.Spec, oldManifestWork.Spec)
}
return false
},
})
}
// blank assignment to verify that ReconcileManagedCluster implements reconcile.Reconciler
var _ reconcile.Reconciler = &ReconcileManagedCluster{}
// ReconcileManagedCluster reconciles a ManagedCluster object
type ReconcileManagedCluster struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
}
// Reconcile reads that state of the cluster for a ManagedCluster object and makes changes based on the state read
// and what is in the ManagedCluster.Spec
// Note:
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileManagedCluster) Reconcile(request reconcile.Request) (reconcile.Result, error) {
reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
reqLogger.Info("Reconciling ManagedCluster")
// Fetch the ManagedCluster instance
instance := &clusterv1.ManagedCluster{}
if err := r.client.Get(
context.TODO(),
types.NamespacedName{Namespace: "", Name: request.Name},
instance,
); err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
reqLogger.Info(fmt.Sprintf("deleteNamespace: %s", request.Name))
err = r.deleteNamespace(request.Name)
if err != nil {
reqLogger.Error(err, "Failed to delete namespace")
return reconcile.Result{Requeue: true, RequeueAfter: 1 * time.Minute}, nil
}
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
if instance.DeletionTimestamp != nil {
return r.managedClusterDeletion(instance)
}
//Wait a number of conditions before starting to process a managedcluster.
clusterDeployment, ready, err := r.isReadyToReconcile(instance)
if err != nil || !ready {
return reconcile.Result{Requeue: true, RequeueAfter: 1 * time.Minute},
nil
}
reqLogger.Info(fmt.Sprintf("AddFinalizer to instance: %s", instance.Name))
libgometav1.AddFinalizer(instance, managedClusterFinalizer)
instanceLabels := instance.GetLabels()
if instanceLabels == nil {
instanceLabels = make(map[string]string)
}
if _, ok := instanceLabels["name"]; !ok {
instanceLabels["name"] = instance.Name
instance.SetLabels(instanceLabels)
}
if err := r.client.Update(context.TODO(), instance); err != nil {
reqLogger.Error(err, "Error while updating labels")
return reconcile.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
}
//Add clusterLabel on ns if missing
ns := &corev1.Namespace{}
if err := r.client.Get(
context.TODO(),
types.NamespacedName{Namespace: "", Name: instance.Name},
ns); err != nil {
reqLogger.Error(err, "Error while getting ns", "namespace", instance.Name)
return reconcile.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
}
labels := ns.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
if _, ok := labels[clusterLabel]; !ok {
labels[clusterLabel] = instance.Name
ns.SetLabels(labels)
if err := r.client.Update(context.TODO(), ns); err != nil {
reqLogger.Error(err, "Error while updating ns", "namespace", instance.Name)
return reconcile.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
}
}
//Create the values for the yamls
config := struct {
ManagedClusterName string
ManagedClusterNamespace string
BootstrapServiceAccountName string
}{
ManagedClusterName: instance.Name,
ManagedClusterNamespace: instance.Name,
BootstrapServiceAccountName: instance.Name + bootstrapServiceAccountNamePostfix,
}
a, err := applier.NewApplier(
bindata.NewBindataReader(),
nil,
r.client,
instance,
r.scheme,
nil)
if err != nil {
reqLogger.Error(err, "Error while creating applier", "namespace", instance.Name)
return reconcile.Result{}, err
}
sa := &corev1.ServiceAccount{}
if err := r.client.Get(context.TODO(),
types.NamespacedName{
Name: instance.Name + bootstrapServiceAccountNamePostfix,
Namespace: instance.Name,
},
sa); err != nil && errors.IsNotFound(err) {
reqLogger.Info(
fmt.Sprintf("Create hub/managedcluster/manifests/managedcluster-service-account.yaml: %s",
instance.Name))
err = a.CreateResource(
"hub/managedcluster/manifests/managedcluster-service-account.yaml",
config,
)
if err != nil {
reqLogger.Error(err, "Error while applying service account", "sa", instance.Name+bootstrapServiceAccountNamePostfix)
return reconcile.Result{}, err
}
}
reqLogger.Info(fmt.Sprintf("CreateOrUpdateInPath hub/managedcluster/manifests except sa: %s", instance.Name))
err = a.CreateOrUpdateInPath(
"hub/managedcluster/manifests",
[]string{"hub/managedcluster/manifests/managedcluster-service-account.yaml"},
false,
config,
)
if err != nil {
reqLogger.Error(err, "Error while applying manifest", "cluster", instance.Name)
return reconcile.Result{}, err
}
crds, yamls, err := generateImportYAMLs(r.client, instance, []string{})
if err != nil {
return reconcile.Result{}, err
}
reqLogger.Info(fmt.Sprintf("createOrUpdateImportSecret: %s", instance.Name))
_, err = createOrUpdateImportSecret(r.client, r.scheme, instance, crds, yamls)
if err != nil {
reqLogger.Error(err, "create ManagedCluster Import Secret")
return reconcile.Result{}, err
}
//Remove syncset if exists as we are now using manifestworks
result, err := deleteKlusterletSyncSets(r.client, instance)
if err != nil {
return result, err
}
if !checkOffLine(instance) {
reqLogger.Info(fmt.Sprintf("createOrUpdateManifestWorks: %s", instance.Name))
isV1, err := isAPIExtensionV1(nil, instance, "")
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: 30 * time.Second}, err
}
if isV1 {
_, _, err = createOrUpdateManifestWorks(r.client, r.scheme, instance, crds["v1"], yamls)
} else {
_, _, err = createOrUpdateManifestWorks(r.client, r.scheme, instance, crds["v1beta1"], yamls)
}
if err != nil {
reqLogger.Error(err, "Error while creating mw")
return reconcile.Result{}, err
}
} else {
autoImportSecret, toImport, err := r.toBeImported(instance, clusterDeployment)
if err != nil {
return reconcile.Result{}, err
}
//Stop here if no auto-import
if !toImport {
klog.Infof("Not importing auto-import cluster: %s", instance.Name)
return reconcile.Result{}, nil
}
//Import the cluster
result, err := r.importCluster(instance, clusterDeployment, autoImportSecret)
if result.Requeue || err != nil {
return result, err
}
errCond := r.setConditionImport(instance, err, fmt.Sprintf("Unable to import %s", instance.Name))
if errCond != nil {
klog.Error(errCond)
return reconcile.Result{}, errCond
}
return result, err
}
return reconcile.Result{}, nil
}
func (r *ReconcileManagedCluster) isReadyToReconcile(managedCluster *clusterv1.ManagedCluster) (*hivev1.ClusterDeployment, bool, error) {
//Check if hive cluster and get client from clusterDeployment
clusterDeployment := &hivev1.ClusterDeployment{}
err := r.client.Get(
context.TODO(),
types.NamespacedName{
Name: managedCluster.Name,
Namespace: managedCluster.Name,
},
clusterDeployment,
)
if err != nil {
if errors.IsNotFound(err) {
klog.Infof("ready to reconcile, cluster %s has no clusterdeployment", clusterDeployment.Name)
return nil, true, nil
}
return nil, false, err
}
if !clusterDeployment.Spec.Installed {
klog.Infof("not ready to reconcile, cluster %s not yet installed", clusterDeployment.Name)
return clusterDeployment, false, nil
}
klog.Infof("ready to reconcile, cluster %s installed", clusterDeployment.Name)
return clusterDeployment, true, nil
}
func (r *ReconcileManagedCluster) toBeImported(managedCluster *clusterv1.ManagedCluster,
clusterDeployment *hivev1.ClusterDeployment) (*corev1.Secret, bool, error) {
//Check self managed
if v, ok := managedCluster.GetLabels()[selfManagedLabel]; ok {
toImport, err := strconv.ParseBool(v)
return nil, toImport, err
}
//Check if hive cluster and get client from clusterDeployment
if clusterDeployment != nil {
//clusterDeployment found and so need to be imported
return nil, true, nil
}
//Check auto-import
klog.V(2).Info("Check autoImportRetry")
autoImportSecret := &corev1.Secret{}
err := r.client.Get(context.TODO(), types.NamespacedName{
Name: autoImportSecretName,
Namespace: managedCluster.Name,
},
autoImportSecret)
if err != nil {
if errors.IsNotFound(err) {
klog.Infof("Will not retry as autoImportSecret not found for %s", managedCluster.Name)
return nil, false, nil
}
klog.Errorf("Unable to read the autoImportSecret Error: %s", err.Error())
return nil, false, err
}
klog.Infof("Will retry as autoImportSecret is found for %s and counter still present", managedCluster.Name)
return autoImportSecret, true, nil
}
func (r *ReconcileManagedCluster) setConditionImport(managedCluster *clusterv1.ManagedCluster, errIn error, reason string) error {
newCondition := metav1.Condition{
Type: ManagedClusterImportSucceeded,
Status: metav1.ConditionTrue,
Message: "Import succeeded",
Reason: "ManagedClusterImported",
}
if errIn != nil {
newCondition.Status = metav1.ConditionFalse
newCondition.Message = errIn.Error()
newCondition.Reason = "ManagedClusterNotImported"
if reason != "" {
newCondition.Message += ": " + reason
}
}
patch := client.MergeFrom(managedCluster.DeepCopy())
meta.SetStatusCondition(&managedCluster.Status.Conditions, newCondition)
err := r.client.Status().Patch(context.TODO(), managedCluster, patch)
if err != nil {
return err
}
return errIn
}
func filterFinalizers(managedCluster *clusterv1.ManagedCluster, finalizers []string) []string {
results := make([]string, 0)
clusterFinalizers := managedCluster.GetFinalizers()
for _, cf := range clusterFinalizers {
found := false
for _, f := range finalizers {
if cf == f {
found = true
break
}
}
if !found {
results = append(results, cf)
}
}
return results
}
func checkOffLine(managedCluster *clusterv1.ManagedCluster) bool {
for _, sc := range managedCluster.Status.Conditions {
if sc.Type == clusterv1.ManagedClusterConditionAvailable {
return sc.Status == metav1.ConditionUnknown || sc.Status == metav1.ConditionFalse
}
}
return true
}
func (r *ReconcileManagedCluster) deleteNamespace(namespaceName string) error {
ns := &corev1.Namespace{}
err := r.client.Get(
context.TODO(),
types.NamespacedName{
Name: namespaceName,
},
ns,
)
if err != nil {
if errors.IsNotFound(err) {
log.Info("Namespace " + namespaceName + " not found")
return nil
}
log.Error(err, "Failed to get namespace")
return err
}
if ns.DeletionTimestamp != nil {
log.Info("Already in deletion")
return nil
}
clusterDeployment := &hivev1.ClusterDeployment{}
err = r.client.Get(
context.TODO(),
types.NamespacedName{
Name: namespaceName,
Namespace: namespaceName,
},
clusterDeployment,
)
tobeDeleted := false
if err != nil {
if errors.IsNotFound(err) {
tobeDeleted = true
} else {
log.Error(err, "Failed to get cluster deployment")
return err
}
} else {
libgometav1.RemoveFinalizer(clusterDeployment, managedClusterFinalizer)
err = r.client.Update(context.TODO(), clusterDeployment)
if err != nil {
return err
}
return fmt.Errorf(
"can not delete namespace %s as ClusterDeployment %s still exist",
namespaceName,
namespaceName,
)
}
if tobeDeleted {
pods := &corev1.PodList{}
err = r.client.List(context.TODO(), pods, client.InNamespace(namespaceName))
if err != nil {
return err
}
for _, pod := range pods.Items {
if !strings.HasPrefix(pod.Name, curatorJobPrefix) {
log.Info("Detected non curator pods, the namespace will be not deleted")
tobeDeleted = false
break
}
}
}
if tobeDeleted {
err = r.client.Delete(context.TODO(), ns)
if err != nil && !errors.IsNotFound(err) {
log.Error(err, "Failed to delete namespace")
return err
}
}
return nil
}
//TODO add logic
//the client is nil when we create the manifestwork,
//at that time the managedcluster is already on line and
//we can check the managedcluster to get the kubeversion
//
//the client is not nill when the cluster will be auto-imported and
//we can check the managed cluster to find out the kubeversion version
func isAPIExtensionV1(managedClusterClient client.Client,
managedCluster *clusterv1.ManagedCluster,
managedClusterKubeVersion string) (bool, error) {
var actualVersion string
//Search kubernetes version for creating manifestwork
if managedClusterClient == nil {
if managedCluster.Status.Version.Kubernetes == "" {
return false, fmt.Errorf("kubernetes version not yet available for managed cluster %s", managedCluster.GetName())
}
actualVersion = managedCluster.Status.Version.Kubernetes
} else {
actualVersion = managedClusterKubeVersion
}
klog.V(4).Infof("actual kubernetes version is %s", actualVersion)
isV1, err := v1APIExtensionMinVersion.Compare(actualVersion)
if err != nil {
return false, err
}
klog.V(4).Infof("isV1: %t", isV1 == -1)
return isV1 == -1, nil
}
|
package clusterconf_test
import (
"encoding/json"
"fmt"
"net/url"
"path/filepath"
"testing"
"time"
"github.com/cerana/cerana/acomm"
"github.com/cerana/cerana/pkg/test"
"github.com/cerana/cerana/provider"
"github.com/cerana/cerana/providers/clusterconf"
"github.com/cerana/cerana/providers/kv"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/stretchr/testify/suite"
)
type clusterConf struct {
suite.Suite
coordinator *test.Coordinator
config *clusterconf.Config
clusterConf *clusterconf.ClusterConf
tracker *acomm.Tracker
viper *viper.Viper
responseHook *url.URL
kv *kv.Mock
}
func TestClusterConf(t *testing.T) {
suite.Run(t, new(clusterConf))
}
func (s *clusterConf) SetupSuite() {
var err error
s.coordinator, err = test.NewCoordinator("")
s.Require().NoError(err)
s.responseHook, _ = url.ParseRequestURI("unix:///tmp/foobar")
v := s.coordinator.NewProviderViper()
v.Set("dataset_ttl", time.Minute.String())
v.Set("bundle_ttl", time.Minute.String())
v.Set("node_ttl", time.Minute.String())
flagset := pflag.NewFlagSet("clusterconf", pflag.PanicOnError)
config := clusterconf.NewConfig(flagset, v)
s.Require().NoError(flagset.Parse([]string{}))
s.Require().NoError(config.LoadConfig())
s.Require().NoError(config.SetupLogging())
s.config = config
s.viper = v
s.tracker, err = acomm.NewTracker(filepath.Join(s.coordinator.SocketDir, "tracker.sock"), nil, nil, 5*time.Second)
s.Require().NoError(err)
s.Require().NoError(s.tracker.Start())
s.clusterConf = clusterconf.New(config, s.tracker)
v = s.coordinator.NewProviderViper()
flagset = pflag.NewFlagSet("kv", pflag.PanicOnError)
kvConfig := provider.NewConfig(flagset, v)
s.Require().NoError(flagset.Parse([]string{}))
s.Require().NoError(kvConfig.LoadConfig())
s.kv, err = kv.NewMock(kvConfig, s.coordinator.ProviderTracker())
s.Require().NoError(err)
s.coordinator.RegisterProvider(s.kv)
s.Require().NoError(s.coordinator.Start())
}
func (s *clusterConf) TearDownTest() {
s.Require().NoError(s.clearData())
}
func (s *clusterConf) TearDownSuite() {
s.coordinator.Stop()
s.kv.Stop()
s.tracker.Stop()
s.Require().NoError(s.coordinator.Cleanup())
}
func (s *clusterConf) TestRegisterTasks() {
server, err := provider.NewServer(s.config.Config)
s.Require().NoError(err)
s.clusterConf.RegisterTasks(server)
s.True(len(server.RegisteredTasks()) > 0)
}
func (s *clusterConf) loadData(data map[string]interface{}) (map[string]uint64, error) {
multiRequest := acomm.NewMultiRequest(s.tracker, 0)
requests := make(map[string]*acomm.Request)
for key, v := range data {
value, err := json.Marshal(v)
if err != nil {
return nil, err
}
req, err := acomm.NewRequest(acomm.RequestOptions{
Task: "kv-update",
Args: kv.UpdateArgs{
Key: key,
Value: string(value),
},
})
if err != nil {
return nil, err
}
requests[key] = req
}
for name, req := range requests {
if err := multiRequest.AddRequest(name, req); err != nil {
continue
}
if err := acomm.Send(s.config.CoordinatorURL(), req); err != nil {
multiRequest.RemoveRequest(req)
continue
}
}
responses := multiRequest.Responses()
indexes := make(map[string]uint64)
for name := range requests {
resp, ok := responses[name]
if !ok {
return nil, fmt.Errorf("failed to send request: %s", name)
}
if resp.Error != nil {
return nil, fmt.Errorf("request failed: %s: %s", name, resp.Error)
}
var result kv.UpdateReturn
if err := resp.UnmarshalResult(&result); err != nil {
return nil, err
}
indexes[name] = result.Index
}
return indexes, nil
}
func (s *clusterConf) clearData() error {
respChan := make(chan *acomm.Response, 1)
defer close(respChan)
rh := func(_ *acomm.Request, resp *acomm.Response) {
respChan <- resp
}
req, err := acomm.NewRequest(acomm.RequestOptions{
Task: "kv-delete",
ResponseHook: s.tracker.URL(),
Args: kv.DeleteArgs{
Key: "",
Recursive: true,
},
SuccessHandler: rh,
ErrorHandler: rh,
})
if err != nil {
return err
}
if err := s.tracker.TrackRequest(req, 0); err != nil {
return err
}
if err := acomm.Send(s.config.CoordinatorURL(), req); err != nil {
s.tracker.RemoveRequest(req)
return err
}
resp := <-respChan
return resp.Error
}
|
package gohaystack
import (
"encoding/json"
"reflect"
"sort"
"testing"
)
func TestGrid_UnmarshalJSON(t *testing.T) {
blabla := "blabla"
myID := NewHaystackID("myid")
myID2 := NewHaystackID("myid2")
type fields struct {
Meta map[string]string
entities []*Entity
}
type args struct {
b []byte
}
tests := []struct {
name string
fields fields
args args
wantErr bool
}{
{
"bad json structure",
fields{},
args{
[]byte(`blabla`),
},
true,
},
{
"No version",
fields{},
args{
[]byte(`{"meta":{"verion":"3.0"}, "cols":[{"name":"blabla"}],"rows":[{"id":"r:myid","blabla":"s:blabla"}]}`),
},
true,
},
{
"bad ver number",
fields{},
args{
[]byte(`{"meta":{"ver":"WRONG"}, "cols":[{"name":"blabla"}],"rows":[{"id":"r:myid","blabla":"s:blabla"}]}`),
},
true,
},
{
"bad Ver number",
fields{},
args{
[]byte(`{"meta":{"Ver":"WRONG"}, "cols":[{"name":"blabla"}],"rows":[{"id":"r:myid","blabla":"s:blabla"}]}`),
},
true,
},
{
"missing id",
fields{},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name":"blabla"}],"rows":[{"idd":"r:myid","blabla":"s:blabla"}]}`),
},
true,
},
{
"id is not ref",
fields{},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name":"blabla"}],"rows":[{"id":"s:myid","blabla":"s:blabla"}]}`),
},
true,
},
{
"id ok",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
{
id: NewHaystackID("myid"),
/*
tags: map[*Label]*Value{
&Label{Value: "blabla"}: &Value{
kind: haystackTypeStr,
str: &blabla,
},
},
*/
},
},
},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[],"rows":[{"id":"r:myid"}]}`),
},
false,
},
{
"id ok and one entity",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
{
id: NewHaystackID("myid"),
tags: map[*Label]*Value{
{Value: "blabla"}: {
kind: HaystackTypeStr,
str: &blabla,
},
},
},
},
},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name": "blabla"}],"rows":[{"id":"r:myid","blabla":"blabla"}]}`),
},
false,
},
{
"id ok and two entities with references",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
{
id: myID,
tags: map[*Label]*Value{
{Value: "blabla"}: {
kind: HaystackTypeStr,
str: &blabla,
},
},
},
{
id: myID2,
tags: map[*Label]*Value{
{Value: "somethingRef"}: {
kind: HaystackTypeRef,
ref: myID,
},
},
},
},
},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name": "blabla"},{"name": "somethingRef"}],"rows":[{"id":"r:myid","blabla":"blabla"},{"id":"r:myid2","somethingRef":"r:myid"}]}`),
},
false,
},
{
"Undeclared label",
fields{},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name": "blablabla"}],"rows":[{"id":"r:myid","blabla":"blabla"}]}`),
},
true,
},
/*
{
"simple",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
&Entity{
id: NewHaystackID("myid"),
tags: map[*Label]*Value{
&Label{Value: "blabla"}: &Value{
kind: haystackTypeStr,
str: &blabla,
},
},
},
},
},
args{
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name":"blabla"}],"rows":[{"id":"r:myid","blabla":"s:blabla"}]}`),
},
false,
},
{
"sample",
fields{
Meta: map[string]string{
"ver": "3.0",
},
//entities: make([]*Entity, 0),
},
args{
samplePayload,
},
false,
},
*/
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Grid{
Meta: tt.fields.Meta,
entities: tt.fields.entities,
}
gg := new(Grid)
if err := gg.UnmarshalJSON(tt.args.b); (err != nil) != tt.wantErr {
t.Errorf("Grid.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
}
if !reflect.DeepEqual(g.Meta, gg.Meta) {
t.Errorf("Grid.UnmarshalJSON() = %v, want %v", gg.Meta, g.Meta)
}
if len(g.entities) != len(gg.entities) {
t.Errorf("Grid.UnmarshalJSON() = found %v entities, want %v", len(gg.entities), len(g.entities))
}
for i := 0; i < len(g.entities); i++ {
gentity := g.entities[i]
ggentity := gg.entities[i]
if *gentity.id != *ggentity.id {
t.Errorf("Grid.UnmarshalJSON() = bad id %v, want %v", gentity.id, ggentity.id)
}
if len(gentity.tags) != len(ggentity.tags) {
t.Errorf("Grid.UnmarshalJSON() = found %v tags, want %v", len(ggentity.tags), len(gentity.tags))
}
for k, v := range ggentity.tags {
var vv *Value
var ok bool
if vv, ok = ggentity.tags[k]; !ok {
t.Errorf("Grid.UnmarshalJSON() = expected tag %v not found", k)
}
if !reflect.DeepEqual(v, vv) {
t.Errorf("Grid.UnmarshalJSON() = bad vallue for tag %v found %v tags, want %v", k, v, vv)
}
}
}
})
}
}
func TestGrid_MarshalJSON(t *testing.T) {
siteLabel := NewLabel("site")
blablaLabel := NewLabel("blabla")
blablaLabelWithDis := NewLabel("blabla")
blablaLabelWithDis.Display = "blabla display"
blablaValue := NewStr("blabla")
myid := NewHaystackID("myid")
type fields struct {
Meta map[string]string
entities []*Entity
}
tests := []struct {
name string
fields fields
want []byte
wantErr bool
}{
{
"Missing version",
fields{
Meta: map[string]string{
"Version": "3.0",
},
entities: []*Entity{},
},
nil,
true,
},
{
"Bad version Ver",
fields{
Meta: map[string]string{
"Ver": "4.0",
},
entities: []*Entity{},
},
nil,
true,
},
{
"Bad version ver",
fields{
Meta: map[string]string{
"ver": "4.0",
},
entities: []*Entity{},
},
nil,
true,
},
{
"simple example",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
{
id: myid,
tags: map[*Label]*Value{
siteLabel: MarkerValue,
blablaLabel: blablaValue,
},
},
},
},
[]byte(`{"meta":{"ver":"3.0"}, "cols":[{"name":"site"},{"name":"blabla"}],"rows":[{"id":"r:myid","blabla":"s:blabla","site":"m:"}]}`),
false,
},
{
"simple example with dis",
fields{
Meta: map[string]string{
"ver": "3.0",
},
entities: []*Entity{
{
id: myid,
tags: map[*Label]*Value{
blablaLabelWithDis: blablaValue,
},
},
},
},
[]byte(`{
"meta":{
"ver":"3.0"
},
"cols":[
{
"name":"blabla",
"dis": "blabla display"
}
],
"rows":[
{
"blabla":"s:blabla",
"id":"r:myid"
}
]
}`),
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Grid{
Meta: tt.fields.Meta,
entities: tt.fields.entities,
}
got, err := g.MarshalJSON()
if (err != nil) != tt.wantErr {
t.Errorf("Grid.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
var a, b haystackJSONStructureTest
err = json.Unmarshal(tt.want, &a)
if err != nil {
t.Fatal(err)
}
err = json.Unmarshal(got, &b)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(a.Meta, b.Meta) {
t.Errorf("Grid.MarshalJSON() = %v, want %v", b, a)
}
if !reflect.DeepEqual(a.Rows, b.Rows) {
t.Errorf("Grid.MarshalJSON() = %v, want %v", b, a)
}
sort.Sort(labelsByAlphabeticalOrder(a.Cols))
sort.Sort(labelsByAlphabeticalOrder(b.Cols))
if !reflect.DeepEqual(a.Cols, b.Cols) {
t.Errorf("Grid.MarshalJSON() = %v, want %v", b.Cols, a.Cols)
}
}
})
}
}
type labelsByAlphabeticalOrder []haystackJSONColTest
func (a labelsByAlphabeticalOrder) Len() int { return len(a) }
func (a labelsByAlphabeticalOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a labelsByAlphabeticalOrder) Less(i, j int) bool { return a[i].Name < a[j].Name }
type haystackJSONColTest struct {
Name string `json:"name"`
Dis string `json:"dis,omitempty"`
}
type haystackJSONStructureTest struct {
Meta map[string]string `json:"meta"`
Cols []haystackJSONColTest `json:"cols"`
Rows []map[string]string `json:"rows"`
}
|
package trackerapi
import (
"os"
"bufio"
"bytes"
"encoding/base64"
"io/ioutil"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
// RoundTripFunc .
type RoundTripFunc func(req *http.Request) *http.Response
// RoundTrip .
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
//NewTestClient returns *http.Client with Transport replaced to avoid making real calls
func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: RoundTripFunc(fn),
}
}
var defaultTestClient = NewTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}
})
func TestMe_promptsForUsernameAndPassword(t *testing.T) {
var tempDirectory, _ = ioutil.TempDir(".", "test")
var outputByteBuffer bytes.Buffer
var inputByteBuffer bytes.Buffer
Me(&outputByteBuffer, bufio.NewReader(&inputByteBuffer), defaultTestClient, tempDirectory)
var prompts = outputByteBuffer.String()
assert.Contains(t, prompts, "Username: ")
assert.Contains(t, prompts, "Password: ")
os.RemoveAll(tempDirectory)
}
func TestMe_submitsSuppliedUsernameAndPasswordToLogin(t *testing.T) {
var tempDirectory, _ = ioutil.TempDir(".", "test")
var outputByteBuffer bytes.Buffer
var inputByteBuffer bytes.Buffer
inputByteBuffer.WriteString("someUserName\nsomePassword\n")
client := NewTestClient(func(req *http.Request) *http.Response {
assert.Equal(t, "https://www.pivotaltracker.com/services/v5/me", req.URL.String())
assert.Equal(t, "Basic "+base64.StdEncoding.EncodeToString([]byte("someUserName:somePassword")), req.Header.Get("Authorization"))
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}
})
Me(&outputByteBuffer, bufio.NewReader(&inputByteBuffer), client, tempDirectory)
os.RemoveAll(tempDirectory)
}
func TestMe_writesTheLoginTokenToAFile(t *testing.T) {
var tempDirectory, _ = ioutil.TempDir(".", "test")
var outputByteBuffer bytes.Buffer
var inputByteBuffer bytes.Buffer
const apiToken = "someApiToken"
client := NewTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString("{\"api_token\": \"" + apiToken + "\"}")),
Header: make(http.Header),
}
})
Me(&outputByteBuffer, bufio.NewReader(&inputByteBuffer), client, tempDirectory)
var fileContents, _ = ioutil.ReadFile(tempDirectory + "/.tracker")
assert.Equal(t, apiToken, string(fileContents))
os.RemoveAll(tempDirectory)
}
|
package Jump_Game_II
import "testing"
func Test_jump(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
want int
}{
// TODO: Add test cases.
{
"case",
args{
[]int{1, 2},
},
1,
},
{
"case1",
args{
[]int{7, 0, 9, 6, 9, 6, 1, 7, 9, 0, 1, 2, 9, 0, 3},
},
2,
},
{
"case2",
args{
[]int{2, 3, 1},
},
1,
},
{
"case3",
args{
[]int{2, 3, 1, 1, 4},
},
2,
},
{
"case4",
args{
[]int{1, 2, 3},
},
2,
},
{
"case5",
args{
[]int{1, 1, 1, 1},
},
3,
},
{
"case6",
args{
[]int{1, 1, 1, 1, 1, 1},
},
5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := jump(tt.args.nums); got != tt.want {
t.Errorf("jump() = %v, want %v", got, tt.want)
}
})
}
}
|
package V01
import (
"fmt"
"github.com/wangyide/golearn/huawei/base"
)
type Vlan struct {
base.Vlan
FieldC bool
}
func (c *Vlan) ShowA() {
c.FieldB = "v01"
c.Vlan.FieldA = 10
fmt.Printf("%v\n", c)
}
|
//go:build !e2e_testing
// +build !e2e_testing
package overlay
import (
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/sirupsen/logrus"
)
func newTunFromFd(_ *logrus.Logger, _ int, _ *net.IPNet, _ int, _ []Route, _ int, _ bool) (Device, error) {
return nil, fmt.Errorf("newTunFromFd not supported in Windows")
}
func newTun(l *logrus.Logger, deviceName string, cidr *net.IPNet, defaultMTU int, routes []Route, _ int, _ bool, _ bool) (Device, error) {
useWintun := true
if err := checkWinTunExists(); err != nil {
l.WithError(err).Warn("Check Wintun driver failed, fallback to wintap driver")
useWintun = false
}
if useWintun {
device, err := newWinTun(l, deviceName, cidr, defaultMTU, routes)
if err != nil {
return nil, fmt.Errorf("create Wintun interface failed, %w", err)
}
return device, nil
}
device, err := newWaterTun(l, cidr, defaultMTU, routes)
if err != nil {
return nil, fmt.Errorf("create wintap driver failed, %w", err)
}
return device, nil
}
func checkWinTunExists() error {
myPath, err := os.Executable()
if err != nil {
return err
}
arch := runtime.GOARCH
switch arch {
case "386":
//NOTE: wintun bundles 386 as x86
arch = "x86"
}
_, err = syscall.LoadDLL(filepath.Join(filepath.Dir(myPath), "dist", "windows", "wintun", "bin", arch, "wintun.dll"))
return err
}
|
package message
import (
"github.com/bitmaelum/bitmaelum-server/core"
)
type Message struct {
Header Header
Catalog Catalog
}
func LoadMessage(addr core.Address, id string) {
}
|
package glog
import (
"testing"
)
func TestColorLog(t *testing.T) {
VerboseF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
TraceF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
ErrorF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
WarnF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
InfoF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
DebugF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
AssetF("TestColorLog F", "go get -u %s", "gooim.me/dewdrop/glog")
Verbose("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Trace("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Error("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Warn("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Info("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Debug("TestColorLog", "go get -u gooim.me/dewdrop/glog")
Asset("TestColorLog", "go get -u gooim.me/dewdrop/glog")
}
|
package company
import (
"encoding/json"
"github.com/xiaotian/stock/pkg/enums"
"github.com/xiaotian/stock/pkg/model"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
"time"
)
//上海交易所上市公司信息收集器
type SHCompanyCollector struct {
}
const (
COOKIE string = "yfx_c_g_u_id_10000042=_ck18012900250116338392357618947; VISITED_MENU=%5B%228528%22%5D; yfx_f_l_v_t_10000042=f_t_1517156701630__r_t_1517314287296__v_t_1517320502571__r_c_2"
USERAGENT string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"
Referer string = "http://www.sse.com.cn/assortment/stock/list/share/"
)
type SHResponse struct {
Data []SHResponseData `json:"result"`
Error string `json:"csrcCode"`
}
type SHResponseData struct {
CompanySimpleName string `json:"COMPANY_ABBR"`
StockCode string `json:"COMPANY_CODE"`
ListingDate string `json:"LISTING_DATE"`
}
func (s SHCompanyCollector) String() string {
return "SHCompanyCollector"
}
func (s SHCompanyCollector) GetStockExchange() int {
return enums.SH
}
func (s SHCompanyCollector) FetchAll(conf model.StockConfig) []model.Company {
logger.Infow("收集上交所公司信息,开始.", "stockExchangeCode", s.GetStockExchange(), "configInfo", conf)
result := make([]model.Company, 0)
plates := enums.GetByStockExchange(conf)
for _, plate := range plates {
result = append(result, SHGetPlateData(conf, plate)...)
}
logger.Infow("收集上交所公司信息,结束.", "stockExchangeCode", s.GetStockExchange(), "configInfo", conf, "length", len(result))
return result
}
//获取每个板块的数据
func SHGetPlateData(conf model.StockConfig, plate enums.PlateEnum) []model.Company {
logger.Infow("收集上交所公司信息,收集指定板块信息,开始.", "stockExchangeCode", conf.StockExchangeCode, "plate", plate)
result := make([]model.Company, 0)
page := 1
for pageData := SHReadPageData(conf, page, plate); pageData != nil; {
result = append(result, pageData...)
page = page + 1
pageData = SHReadPageData(conf, page, plate)
}
logger.Infow("收集上交所公司信息,收集指定板块信息,结束.", "stockExchangeCode", conf.StockExchangeCode, "plate", plate)
return result
}
//读取每页的数据
func SHReadPageData(conf model.StockConfig, page int, plate enums.PlateEnum) []model.Company {
time.Sleep(time.Millisecond * 500)
client := &http.Client{}
pageStr := strconv.Itoa(page)
requestUrl := conf.CompanyInfoUrl + "&pageHelp.beginPage=" + pageStr + "&pageHelp.pageNo=" + pageStr + "&stockType=" + plate.Tab + "&_=" + strconv.Itoa(rand.Int())
logger.Infow("获取上交所公司列表.", "stockExchange", plate.StockExchange, "plate", plate.Tab, "url", requestUrl)
request, err := http.NewRequest("GET", requestUrl, nil)
if err != nil {
logger.Errorw("获取上交所公司列表构造请求参数异常.", "stockExchange", plate.StockExchange, "plate", plate.Tab, "url", requestUrl, "err", err)
return nil
}
request.Header.Add("Cookie", COOKIE)
request.Header.Add("User-Agent", USERAGENT)
request.Header.Add("Referer", Referer)
response, err := client.Do(request)
if nil != err {
logger.Errorw("获取上交所公司列表数据异常.", "stockExchange", plate.StockExchange, "plate", plate.Tab, "url", requestUrl, "err", err)
return nil
}
responseDataByte, err := ioutil.ReadAll(response.Body)
if nil != err {
logger.Errorw("读取上交所公司列表数据异常.", "stockExchange", plate.StockExchange, "plate", plate.Tab, "url", requestUrl, "err", err)
return nil
}
responseDataPoint := &SHResponse{}
err = json.Unmarshal(responseDataByte, &responseDataPoint)
if err != nil {
logger.Errorw("读取上交所公司列表,解析数据出现异常.", "stockExchange", plate.StockExchange, "plate", plate.Tab, "url", requestUrl, "err", err)
return nil
}
if nil == responseDataPoint || len(responseDataPoint.Data) == 0 {
return nil
}
return SHResponseToCompanyMapper(*responseDataPoint, plate)
}
func SHResponseToCompanyMapper(response SHResponse, plate enums.PlateEnum) []model.Company {
result := make([]model.Company, 0)
for _, d := range response.Data {
company := model.Company{
StockExchange: plate.StockExchange,
Code: d.StockCode,
Plate: plate.Code,
ShortName: d.CompanySimpleName,
FullName: "-",
IndustryCode: "-",
IndustryName: "-",
ListingDate: d.ListingDate,
}
result = append(result, company)
}
logger.Infow("数据转换", "length", len(response.Data), "resultLength", len(result))
return result
}
|
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package ekalog
import (
"github.com/qioalice/ekago/v2/internal/ekaletter"
)
func init() {
// Init log levels.
initLevels()
// Create first N *Error objects and fill its pool by them.
initEntryPool()
// Initialize package's Logger (first base logger).
initBaseLogger()
// Initialize the gate's functions to link ekalog <-> ekaerr packages.
ekaletter.BridgeLogErr2 = logErr
ekaletter.BridgeLogwErr2 = logErrw
}
|
package main
import (
"fmt"
"net"
"os"
//"runtime"
)
func errFunc(err error, info string) {
if err != nil {
fmt.Println(info, err)
//return // 返回函数
//runtime.Goexit() // 结束当前go程
os.Exit(1) // 结束当前进程
}
}
func main() {
listener, err := net.Listen("tcp", "127.0.0.1:8900")
errFunc(err, "net.Listener err:")
defer listener.Close()
conn, err := listener.Accept()
errFunc(err, "Accept err:")
defer conn.Close()
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if n == 0 {
return
}
errFunc(err, "conn.Read:")
fmt.Printf("|%s|\n", string(buf[:n]))
}
|
package set
import (
"fmt"
"sort"
)
// Set -
type Set interface {
Have(...interface{}) bool
Subset(Set) bool
Superset(Set) bool
Add(...interface{})
Remove(...interface{})
Clear()
Or(Set) Set
And(Set) Set
Xor(Set) Set
Copy() Set
Keys() []string
}
type set struct {
Values map[interface{}]struct{}
}
func (s *set) Have(keys ...interface{}) bool {
for _, key := range keys {
if _, ok := s.Values[key]; !ok {
return false
}
}
return true
}
func (s *set) Subset(t Set) bool {
keys := []interface{}{}
for key := range s.Values {
keys = append(keys, key)
}
return t.Have(keys...)
}
func (s *set) Superset(t Set) bool {
return t.Subset(s)
}
func (s *set) Add(keys ...interface{}) {
for _, key := range keys {
s.Values[key] = struct{}{}
}
}
func (s *set) Remove(keys ...interface{}) {
for _, key := range keys {
delete(s.Values, key)
}
}
func (s *set) Clear() {
s.Values = map[interface{}]struct{}{}
}
func (s *set) Or(t Set) Set {
r := t.Copy()
for key := range s.Values {
r.Add(key)
}
return r
}
func (s *set) And(t Set) Set {
r := &set{}
r.Clear()
for key := range s.Values {
if t.Have(key) {
r.Values[key] = struct{}{}
}
}
return r
}
func (s *set) Xor(t Set) Set {
r := t.Copy()
for key := range s.Values {
if t.Have(key) {
r.Remove(key)
} else {
r.Add(key)
}
}
return r
}
func (s *set) Copy() Set {
r := &set{}
r.Clear()
for key := range s.Values {
r.Values[key] = struct{}{}
}
return r
}
func (s *set) Keys() []string {
r := []string{}
for key := range s.Values {
r = append(r, fmt.Sprint(key))
}
sort.Strings(r)
return r
}
// New -
func New(keys ...interface{}) Set {
r := &set{}
r.Clear()
r.Add(keys...)
return r
}
|
package sound
import (
"fmt"
"testing"
)
func Test_NewSong(t *testing.T) {
type testData struct {
bpm int
title string
duration float64
pattern map[string][8]int
errResponse error
songResponse *Song
}
tests := map[string]testData{
"HappyPath": {
bpm: 128,
title: "test",
duration: 100,
pattern: map[string][8]int{
"test1": {0, 1, 0, 1, 0, 1, 1, 0},
"test2": {0, 1, 0, 1, 0, 1, 1, 0},
"test3": {0, 1, 0, 1, 0, 1, 1, 0},
},
songResponse: &Song{
Title: "test",
BPM: 128,
Duration: 100,
Sequence: []string{"|_", "|test1+test2+test3", "|_", "|test1+test2+test3", "|_", "|test1+test2+test3", "|test1+test2+test3", "|_|"},
Step: 0.234375,
},
},
"Error-NegativeBPM": {
bpm: -128,
title: "test",
duration: 100,
pattern: map[string][8]int{
"test1": {0, 1, 0, 1, 0, 1, 1, 0},
"test2": {0, 1, 0, 1, 0, 1, 1, 0},
"test3": {0, 1, 0, 1, 0, 1, 1, 0},
},
errResponse: fmt.Errorf("bpm must be between 1 and 999"),
},
"Error-NegativeDuration": {
bpm: 128,
title: "test",
duration: -100,
pattern: map[string][8]int{
"test1": {0, 1, 0, 1, 0, 1, 1, 0},
"test2": {0, 1, 0, 1, 0, 1, 1, 0},
"test3": {0, 1, 0, 1, 0, 1, 1, 0},
},
errResponse: fmt.Errorf("song duration must be between 1 and 999"),
},
"Error-NoPattern": {
bpm: 128,
title: "test",
duration: 100,
errResponse: fmt.Errorf("song requires a pattern"),
},
}
for _, v := range tests {
s, err := NewSong(v.bpm, v.title, v.duration, v.pattern)
if v.errResponse != nil {
if v.errResponse.Error() != err.Error() {
t.Error(fmt.Sprintf("Expected err to be %v but got %v", v.errResponse, err))
} else if s != nil {
t.Error(fmt.Sprintf("Expected song to be nil but got: %v", s))
}
} else {
if v.songResponse != s {
if s != nil && len(s.Sequence) != len(v.songResponse.Sequence) {
t.Error(fmt.Sprintf("Expected song to be %v but got %v", v.songResponse, s))
}
}
}
}
}
|
package main
import (
"net/http"
"github.com/patrickoliveros/bookings/api"
"github.com/patrickoliveros/bookings/internal/config"
"github.com/patrickoliveros/bookings/internal/pages"
"github.com/go-chi/chi"
"github.com/go-chi/chi/v5/middleware"
)
func routes(app *config.AppConfig) http.Handler {
mux := chi.NewRouter()
setMiddlewares(mux)
getRequests(mux)
postRequests(mux)
setSecurePages(mux)
setAPIEndpoints(mux)
enableStaticFiles(mux)
return mux
}
func setMiddlewares(mux *chi.Mux) {
mux.Use(middleware.Recoverer)
mux.Use(NoSurf)
mux.Use(SessionLoad)
}
func getRequests(mux *chi.Mux) {
mux.Get("/", pages.Repo.HomePage)
mux.Get("/about", pages.Repo.AboutPage)
mux.Get("/reservations", pages.Repo.ReservationsPage)
mux.Get("/make-reservation", pages.Repo.MakeReservationPage)
mux.Get("/reservation-summary", pages.Repo.SummaryMakeReservationPage)
mux.Get("/contact", pages.Repo.ContactPage)
mux.Get("/rooms/generals-quarters", pages.Repo.RoomsGeneral)
mux.Get("/rooms/majors-suite", pages.Repo.RoomsMajor)
mux.Get("/choose-room/{id}", pages.Repo.ChooseRoom)
mux.Get("/book-room", pages.Repo.BookRoom)
mux.Get("/login", pages.Repo.LoginPage)
mux.Get("/logout", pages.Repo.LogoutPage)
mux.Get("/favicon.ico", pages.Repo.Favicon)
}
func postRequests(mux *chi.Mux) {
mux.Post("/reservations", pages.Repo.PostReservationsPage)
mux.Post("/make-reservation", pages.Repo.PostMakeReservationPage)
mux.Post("/availability", pages.Repo.AvailabilityReservationsPage)
mux.Post("/login", pages.Repo.PostLoginPage)
}
func setSecurePages(mux *chi.Mux) {
mux.Route("/admin", func(mux chi.Router) {
// mux.Use(helpers.Auth)
adminGetPages(mux)
adminPostPages(mux)
})
}
func setAPIEndpoints(mux *chi.Mux) {
mux.Route("/api", func(mux chi.Router) {
// mux.Use(helpers.Auth)
// adminGetPages(mux)
// adminPostPages(mux)
mux.Get("/articles", api.GetArticles)
})
}
func adminGetPages(mux chi.Router) {
mux.Get("/dashboard", pages.Repo.AdminDashBoard)
mux.Get("/reservations-new", pages.Repo.AdminReservationsNew)
mux.Get("/reservations-all", pages.Repo.AdminReservationsAll)
mux.Get("/reservations-calendar", pages.Repo.AdminReservationsCalendar)
mux.Get("/reservation/{id}", pages.Repo.AdminReservationsById)
mux.Get("/process-reservation/{id}", pages.Repo.AdminProcessReservation)
}
func adminPostPages(mux chi.Router) {
mux.Post("/dashboard", pages.Repo.AdminDashBoard)
mux.Post("/reservations-new", pages.Repo.AdminReservationsNew)
mux.Post("/reservations-all", pages.Repo.AdminReservationsAll)
mux.Post("/reservations-calendar", pages.Repo.AdminPostReservationsCalendar)
mux.Post("/reservation/{id}", pages.Repo.AdminPostReservationsById)
}
func enableStaticFiles(mux *chi.Mux) {
mux.Handle("/static/*", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
}
|
package persist
import (
"database/sql"
"github.com/Miniand/venditio/model"
"os"
)
func DatabaseDriver() string {
driver := os.Getenv("DATABASE_DRIVER")
if driver == "" {
driver = "sqlite3"
}
return driver
}
func DatabaseOptions() string {
options := os.Getenv("DATABASE_OPTIONS")
if options == "" {
options = "database.sqlite"
}
return options
}
func Connect() (*sql.DB, error) {
return sql.Open(DatabaseDriver(), DatabaseOptions())
}
func SyncSchemaSql(db *sql.DB, s *Schema) ([]string, error) {
dialect, err := DatabaseDialect(DatabaseDriver())
if err != nil {
return nil, err
}
tSql := []string{}
for _, t := range s.Tables {
s, err := dialect.SyncTableSchemaSql(db, t)
if err != nil {
return nil, err
}
tSql = append(tSql, s...)
}
return tSql, nil
}
func RowsToModels(rows *sql.Rows, t *Table) (models []model.Model, err error) {
var cols []string
for rows.Next() {
if cols == nil {
if cols, err = rows.Columns(); err != nil {
return
}
}
m := model.Model{}
scans := make([]interface{}, len(cols))
for i, c := range cols {
if t.Columns[c] != nil {
scans[i] = t.Columns[c].Type.RawType()
} else {
scans[i] = &sql.NullString{}
}
}
if err = rows.Scan(scans...); err != nil {
return
}
for i, c := range cols {
switch dt := scans[i].(type) {
case *sql.NullBool:
if dt.Valid {
m[c] = dt.Bool
}
case *sql.NullInt64:
if dt.Valid {
m[c] = dt.Int64
}
case *sql.NullFloat64:
if dt.Valid {
m[c] = dt.Float64
}
case *sql.NullString:
if dt.Valid {
m[c] = dt.String
}
default:
if scans[i] != nil {
m[c] = scans[i]
}
}
}
models = append(models, m)
}
return
}
|
// 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 compare
import (
"fmt"
"reflect"
"github.com/golang/protobuf/proto"
)
// Action is the optional return value type of functions passes to
// Register and Custom.Register.
type Action int
const (
// Done is returned by custom comparison functions when the two objects
// require no further comparisons.
Done Action = iota
// Fallback is returned by custom comparison functions when the comparison of
// the two objects should continue with the fallback comparison method.
Fallback
)
type customKey struct {
reference reflect.Type
value reflect.Type
}
var (
globalCustom = &Custom{}
comparatorType = reflect.TypeOf(Comparator{})
actionType = reflect.TypeOf(Done)
protoType = reflect.TypeOf((*proto.Message)(nil)).Elem()
protoComparator = reflect.ValueOf(compareProtos)
)
// Custom is a collection of custom comparators that will be used instead of
// the default comparison methods when comparing objects of the registered types.
type Custom struct {
funcs map[customKey]reflect.Value
}
// Register assigns the function f with signature func(comparator, T, T) to
// be used as the comparator for instances of type T when using
// Custom.Compare(). f may return nothing or a CompareAction.
// Register will panic if f does not match the expected signature, or if a
// comparator for type T has already been registered with this Custom.
func (c *Custom) Register(f interface{}) {
v := reflect.ValueOf(f)
t := v.Type()
if t.Kind() != reflect.Func {
panic(fmt.Sprintf("Invalid function %v", t))
}
if t.NumIn() != 3 {
panic(fmt.Sprintf("Compare functions must have 3 args, got %v", t))
}
if t.In(0) != comparatorType {
panic(fmt.Sprintf("First argument must be compare.Comparator, got %v", t.In(0)))
}
if !(t.NumOut() == 0 || (t.NumOut() == 1 && t.Out(0) == actionType)) {
panic(fmt.Sprintf("Compare functions must either have no return values or a single Action"))
}
key := customKey{t.In(1), t.In(2)}
if key.reference != key.value {
panic(fmt.Sprintf("Comparison arguments must be of the same type, got %v and %v", key.reference, key.value))
}
if c.funcs == nil {
c.funcs = map[customKey]reflect.Value{}
} else if _, found := c.funcs[key]; found {
panic(fmt.Sprintf("%v to %v already registered", key.reference, key.value))
}
c.funcs[key] = v
}
// Compare delivers all the differences it finds to the specified Handler.
// Compare uses the list of custom comparison handlers registered with
// Custom.Register(), falling back to the default comparison method for the type
// when no custom comparison function has been registered with this custom.
// If the reference and value are equal, the handler will never be invoked.
func (c *Custom) Compare(reference, value interface{}, handler Handler) {
compare(reference, value, handler, c)
}
// DeepEqual compares a value against a reference using the custom comparators
// and returns true if they are equal.
func (c *Custom) DeepEqual(reference, value interface{}) bool {
var d test
c.Compare(reference, value, d.set)
return !bool(d)
}
// Diff returns the differences between the reference and the value.
// Diff uses the list of custom comparison handlers registered with
// Custom.Register(), falling back to the default comparison method for the type
// when no custom comparison function has been registered with this custom.
// The maximum number of differences is controlled by limit, which must be >0.
// If they compare equal, the length of the returned slice will be 0.
func (c *Custom) Diff(reference, value interface{}, limit int) []Path {
diffs := make(collect, 0, limit)
c.Compare(reference, value, diffs.add)
return ([]Path)(diffs)
}
func (c *Custom) call(key customKey, args []reflect.Value) Action {
if c == nil {
return Fallback
}
comparator, found := c.funcs[key]
if !found {
if !key.reference.Implements(protoType) {
return c.fallback().call(key, args)
}
comparator = protoComparator
}
action := Done
if res := comparator.Call(args); len(res) > 0 {
action = res[0].Interface().(Action)
}
switch action {
case Done:
return Done
case Fallback:
return c.fallback().call(key, args)
default:
panic(fmt.Errorf("Unknown action %v", action))
}
}
func (c *Custom) fallback() *Custom {
if c == globalCustom {
return nil
}
return globalCustom
}
func compareProtos(c Comparator, reference proto.Message, value interface{}) {
if v, ok := value.(proto.Message); !ok || !proto.Equal(reference, v) {
c.AddDiff(reference, value)
}
}
|
package routes
import (
"QRcodeBillApi/helper"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/monitor"
)
func Setup(app *fiber.App) {
app.Get("/dashboard", monitor.New())
app.Get("/api/register/:value/:key", helper.Login)
app.Get("/api/table/:number", helper.BringTable)
app.Get("api/allzip", helper.AllZip)
app.Post("/api/menu", helper.Menu)
app.Get("/api/menu-view", helper.MenuView)
app.Get("/api/admin", helper.Admin)
}
|
package models
import (
"encoding/json"
"log"
)
type OfferAllContent struct {
Id int64 `json:"id"`
Offer_uid string `json:"offer_uid"`
Merchant_uid string `json:"merchant_uid"`
Offer_point float64 `json:"offer_point"`
Offer_cat_id int64 `json:"offer_cat_id"`
Offer_image_banner string `json:"offer_image_banner"`
Offer_image_poster string `json:"offer_image_poster"`
Used int64 `json:"used"`
Quantity int64 `json:"quantity"`
Name_en string `json:"name_en"`
Name_th string `json:"name_th"`
Condition_offer_en string `json:"condition_offer_en"`
Condition_offer_th string `json:"condition_offer_th"`
Description_en string `json:"description_en"`
Description_th string `json:"description_th"`
Status int64 `json:"status"`
Value string `json:"value"`
Offer_type string `json:"offer_type"`
Create_at int64 `json:"create_at"`
Update_at int64 `json:"update_at"`
}
func (offer *OfferAllContent) Save(service_name string) (string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var (
err error
)
tx, err := DB.Begin()
if err != nil {
return "err", err
}
SQL_INSERT_OFMETA := `INSERT INTO ` + offerMeta_table + `
(offer_uid, offer_point, merchant_uid, offer_cat_id, offer_image_banner, offer_image_poster,
used, quantity, status ,value, offer_type, create_at, update_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`
_, err1 := tx.Exec(SQL_INSERT_OFMETA, offer.Offer_uid, offer.Offer_point, offer.Merchant_uid,
offer.Offer_cat_id, offer.Offer_image_banner, offer.Offer_image_poster,
offer.Used, offer.Quantity, offer.Status, offer.Value, offer.Offer_type, offer.Create_at, offer.Update_at)
log.Println(err1)
if err1 != nil {
tx.Rollback()
return "err", err1
}
SQL_INSERT_OFCONTENT_EN := `INSERT INTO ` + offerContent_table + `
(name, offer_uid, condition_offer, description, lang, create_at, update_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
`
_, err2 := tx.Exec(SQL_INSERT_OFCONTENT_EN, offer.Name_en, offer.Offer_uid, offer.Condition_offer_en,
offer.Description_en, "en", offer.Create_at, offer.Update_at)
if err2 != nil {
tx.Rollback()
return "err", err1
}
SQL_INSERT_OFCONTENT_TH := `INSERT INTO ` + offerContent_table + `
(name, offer_uid, condition_offer, description, lang, create_at, update_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
`
_, err3 := tx.Exec(SQL_INSERT_OFCONTENT_TH, offer.Name_th, offer.Offer_uid, offer.Condition_offer_th,
offer.Description_th, "th", offer.Create_at, offer.Update_at)
if err3 != nil {
tx.Rollback()
return "err", err1
}
tx.Commit()
defer CloseDb()
return "success", nil
}
func (offer *OfferAllContent) Update(service_name string) (string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var (
err error
)
tx, err := DB.Begin()
if err != nil {
return "err", err
}
UPDATE_OFFER_META := `UPDATE ` + offerMeta_table + ` SET
offer_point=? , offer_cat_id=?, offer_image_banner=?,
offer_image_poster=?, used=?, quantity=?, status=?, value=?, offer_type=?, update_at=?
WHERE offer_uid=?`
_, err1 := tx.Exec(UPDATE_OFFER_META,
offer.Offer_point, offer.Offer_cat_id, offer.Offer_image_banner,
offer.Offer_image_poster, offer.Used, offer.Quantity, offer.Status, offer.Value, offer.Offer_type, offer.Update_at, offer.Offer_uid)
if err1 != nil {
tx.Rollback()
return "err", err1
}
UPDATE_OFFER_CONTENT_EN := `UPDATE ` + offerContent_table + ` SET
name=?, condition_offer=?, description=?, update_at=? WHERE offer_uid=? AND lang='en'`
_, err2 := tx.Exec(UPDATE_OFFER_CONTENT_EN,
offer.Name_en, offer.Condition_offer_en, offer.Description_en, offer.Update_at, offer.Offer_uid)
if err2 != nil {
tx.Rollback()
return "err", err2
}
UPDATE_OFFER_CONTENT_TH := `UPDATE ` + offerContent_table + ` SET
name=?, condition_offer=?, description=?, update_at=? WHERE offer_uid=? AND lang='th'`
_, err3 := tx.Exec(UPDATE_OFFER_CONTENT_TH,
offer.Name_th, offer.Condition_offer_th, offer.Description_th, offer.Update_at, offer.Offer_uid)
if err3 != nil {
tx.Rollback()
return "err", err3
}
tx.Commit()
defer CloseDb()
return "success", nil
}
func (offer *OfferAllContent) Delete(service_name string) (string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var (
err error
)
tx, err := DB.Begin()
if err != nil {
return "err", err
}
SQL_DELETE_OFFERMETA := "DELETE from " + offerMeta_table + " WHERE offer_uid=?"
_, err = tx.Exec(SQL_DELETE_OFFERMETA, offer.Offer_uid)
if err != nil {
tx.Rollback()
return "err", err
}
SQL_DELETE_OFFERCONTENT := "DELETE from " + offerContent_table + " WHERE offer_uid=?"
_, err = tx.Exec(SQL_DELETE_OFFERCONTENT, offer.Offer_uid)
if err != nil {
tx.Rollback()
return "err", err
}
tx.Commit()
defer CloseDb()
return "success", nil
}
func (offer *OfferAllContent) ListsOfferByMerchant(service_name string) (string, string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var oac OfferAllContent
SQL_DELETE_OFFERMETA := "SELECT * FROM " + offerMeta_table + " WHERE merchant_uid=?"
rows, err := DB.Query(SQL_DELETE_OFFERMETA, offer.Merchant_uid)
if err != nil {
return "", "err", err
}
offers := make([]*OfferAllContent, 0, 17)
for rows.Next() {
err := rows.Scan(&oac.Id, &oac.Offer_uid, &oac.Offer_point, &oac.Merchant_uid,
&oac.Offer_cat_id, &oac.Offer_image_banner, &oac.Offer_image_poster,
&oac.Used, &oac.Quantity, &oac.Status, &oac.Value, &oac.Offer_type, &oac.Create_at, &oac.Update_at)
if err != nil {
return "", "err", err
}
SQL_SELECT_OFFER_TH := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows1, err := DB.Query(SQL_SELECT_OFFER_TH, oac.Offer_uid, "th")
if err != nil {
return "", "err", err
}
for rows1.Next() {
err := rows1.Scan(&oac.Name_th, &oac.Condition_offer_th, &oac.Description_th)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_EN := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows2, err := DB.Query(SQL_SELECT_OFFER_EN, oac.Offer_uid, "en")
if err != nil {
return "", "err", err
}
for rows2.Next() {
err := rows2.Scan(&oac.Name_en, &oac.Condition_offer_en, &oac.Description_en)
if err != nil {
return "", "err", err
}
}
offers = append(offers, &OfferAllContent{
oac.Id, oac.Offer_uid, oac.Merchant_uid, oac.Offer_point, oac.Offer_cat_id, oac.Offer_image_banner, oac.Offer_image_poster,
oac.Used, oac.Quantity, oac.Name_en, oac.Name_th, oac.Condition_offer_en, oac.Condition_offer_th,
oac.Description_en, oac.Description_th, oac.Status, oac.Value, oac.Offer_type, oac.Create_at, oac.Update_at,
})
}
// log.Println(offers)
s, _ := json.Marshal(offers)
offers_of_merchant := string(s)
return offers_of_merchant, "success", err
}
func (offer *OfferAllContent) ListsOffersMerchantStatus(service_name string) (string, string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var oac OfferAllContent
SQL_DELETE_OFFERMETA := "SELECT * FROM " + offerMeta_table + " WHERE merchant_uid=? AND status = 1"
rows, err := DB.Query(SQL_DELETE_OFFERMETA, offer.Merchant_uid)
if err != nil {
return "", "err", err
}
offers := make([]*OfferAllContent, 0, 17)
for rows.Next() {
err := rows.Scan(&oac.Id, &oac.Offer_uid, &oac.Offer_point, &oac.Merchant_uid,
&oac.Offer_cat_id, &oac.Offer_image_banner, &oac.Offer_image_poster,
&oac.Used, &oac.Quantity, &oac.Status, &oac.Value, &oac.Offer_type, &oac.Create_at, &oac.Update_at)
if err != nil {
return "", "err", err
}
SQL_SELECT_OFFER_TH := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows1, err := DB.Query(SQL_SELECT_OFFER_TH, oac.Offer_uid, "th")
if err != nil {
return "", "err", err
}
for rows1.Next() {
err := rows1.Scan(&oac.Name_th, &oac.Condition_offer_th, &oac.Description_th)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_EN := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows2, err := DB.Query(SQL_SELECT_OFFER_EN, oac.Offer_uid, "en")
if err != nil {
return "", "err", err
}
for rows2.Next() {
err := rows2.Scan(&oac.Name_en, &oac.Condition_offer_en, &oac.Description_en)
if err != nil {
return "", "err", err
}
}
offers = append(offers, &OfferAllContent{
oac.Id, oac.Offer_uid, oac.Merchant_uid, oac.Offer_point, oac.Offer_cat_id, oac.Offer_image_banner, oac.Offer_image_poster,
oac.Used, oac.Quantity, oac.Name_en, oac.Name_th, oac.Condition_offer_en, oac.Condition_offer_th,
oac.Description_en, oac.Description_th, oac.Status, oac.Value, oac.Offer_type, oac.Create_at, oac.Update_at,
})
}
// log.Println(offers)
s, _ := json.Marshal(offers)
offers_of_merchant := string(s)
return offers_of_merchant, "success", err
}
func ListsAllOffer(service_name string) (string, string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var oac OfferAllContent
SQL_SELECT_OFFERMETA := "SELECT * FROM " + offerMeta_table
rows, err := DB.Query(SQL_SELECT_OFFERMETA)
if err != nil {
return "", "err", err
}
offers := make([]*OfferAllContent, 0, 17)
for rows.Next() {
err := rows.Scan(&oac.Id, &oac.Offer_uid, &oac.Offer_point, &oac.Merchant_uid,
&oac.Offer_cat_id, &oac.Offer_image_banner, &oac.Offer_image_poster,
&oac.Used, &oac.Quantity, &oac.Status, &oac.Value, &oac.Offer_type, &oac.Create_at, &oac.Update_at)
if err != nil {
return "", "err", err
}
SQL_SELECT_OFFER_TH := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows1, err := DB.Query(SQL_SELECT_OFFER_TH, oac.Offer_uid, "th")
if err != nil {
return "", "err", err
}
for rows1.Next() {
err := rows1.Scan(&oac.Name_th, &oac.Condition_offer_th, &oac.Description_th)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_EN := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows2, err := DB.Query(SQL_SELECT_OFFER_EN, oac.Offer_uid, "en")
if err != nil {
return "", "err", err
}
for rows2.Next() {
err := rows2.Scan(&oac.Name_en, &oac.Condition_offer_en, &oac.Description_en)
if err != nil {
return "", "err", err
}
}
offers = append(offers, &OfferAllContent{
oac.Id, oac.Offer_uid, oac.Merchant_uid, oac.Offer_point, oac.Offer_cat_id, oac.Offer_image_banner, oac.Offer_image_poster,
oac.Used, oac.Quantity, oac.Name_en, oac.Name_th, oac.Condition_offer_en, oac.Condition_offer_th,
oac.Description_en, oac.Description_th, oac.Status, oac.Value, oac.Offer_type, oac.Create_at, oac.Update_at,
})
}
// log.Println(offers)
s, _ := json.Marshal(offers)
offers_of_merchant := string(s)
return offers_of_merchant, "success", err
}
func ListsAllOfferByStatus(service_name string, status string) (string, string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var oac OfferAllContent
SQL_SELECT_OFFERMETA := "SELECT * FROM " + offerMeta_table + " WHERE status = ?"
rows, err := DB.Query(SQL_SELECT_OFFERMETA, status)
if err != nil {
return "", "err", err
}
offers := make([]*OfferAllContent, 0, 17)
for rows.Next() {
err := rows.Scan(&oac.Id, &oac.Offer_uid, &oac.Offer_point, &oac.Merchant_uid,
&oac.Offer_cat_id, &oac.Offer_image_banner, &oac.Offer_image_poster,
&oac.Used, &oac.Quantity, &oac.Status, &oac.Value, &oac.Offer_type, &oac.Create_at, &oac.Update_at)
if err != nil {
return "", "err", err
}
SQL_SELECT_OFFER_TH := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows1, err := DB.Query(SQL_SELECT_OFFER_TH, oac.Offer_uid, "th")
if err != nil {
return "", "err", err
}
for rows1.Next() {
err := rows1.Scan(&oac.Name_th, &oac.Condition_offer_th, &oac.Description_th)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_EN := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows2, err := DB.Query(SQL_SELECT_OFFER_EN, oac.Offer_uid, "en")
if err != nil {
return "", "err", err
}
for rows2.Next() {
err := rows2.Scan(&oac.Name_en, &oac.Condition_offer_en, &oac.Description_en)
if err != nil {
return "", "err", err
}
}
offers = append(offers, &OfferAllContent{
oac.Id, oac.Offer_uid, oac.Merchant_uid, oac.Offer_point, oac.Offer_cat_id, oac.Offer_image_banner, oac.Offer_image_poster,
oac.Used, oac.Quantity, oac.Name_en, oac.Name_th, oac.Condition_offer_en, oac.Condition_offer_th,
oac.Description_en, oac.Description_th, oac.Status, oac.Value, oac.Offer_type, oac.Create_at, oac.Update_at,
})
}
// log.Println(offers)
s, _ := json.Marshal(offers)
offers_of_merchant := string(s)
return offers_of_merchant, "success", err
}
func (offer *OfferAllContent) ShowOfferInfo(service_name string) (string, string, error) {
offerMeta_table := service_name + "_offer_meta"
offerContent_table := service_name + "_offer_content"
ConnectDb()
var (
err error
)
var oac OfferAllContent
SQL_SELECT_OFFERMETA := "SELECT * FROM " + offerMeta_table + " WHERE offer_uid=?"
rows, err := DB.Query(SQL_SELECT_OFFERMETA, offer.Offer_uid)
if err != nil {
return "", "err", err
}
// offers := make([]*OfferAllContent, 0, 17)
for rows.Next() {
err := rows.Scan(&oac.Id, &oac.Offer_uid, &oac.Offer_point, &oac.Merchant_uid,
&oac.Offer_cat_id, &oac.Offer_image_banner, &oac.Offer_image_poster,
&oac.Used, &oac.Quantity, &oac.Status, &oac.Value, &oac.Offer_type, &oac.Create_at, &oac.Update_at)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_TH := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows1, err := DB.Query(SQL_SELECT_OFFER_TH, oac.Offer_uid, "th")
if err != nil {
return "", "err", err
}
for rows1.Next() {
err := rows1.Scan(&oac.Name_th, &oac.Condition_offer_th, &oac.Description_th)
if err != nil {
return "", "err", err
}
}
SQL_SELECT_OFFER_EN := "SELECT name, condition_offer, description FROM " + offerContent_table + " WHERE offer_uid=? AND lang=?"
rows2, err := DB.Query(SQL_SELECT_OFFER_EN, oac.Offer_uid, "en")
if err != nil {
return "", "err", err
}
for rows2.Next() {
err := rows2.Scan(&oac.Name_en, &oac.Condition_offer_en, &oac.Description_en)
if err != nil {
return "", "err", err
}
}
result := OfferAllContent{
oac.Id, oac.Offer_uid, oac.Merchant_uid, oac.Offer_point, oac.Offer_cat_id, oac.Offer_image_banner, oac.Offer_image_poster,
oac.Used, oac.Quantity, oac.Name_en, oac.Name_th, oac.Condition_offer_en, oac.Condition_offer_th,
oac.Description_en, oac.Description_th, oac.Status, oac.Value, oac.Offer_type, oac.Create_at, oac.Update_at,
}
s, _ := json.Marshal(result)
offers_info := string(s)
// log.Println(string(s))
return offers_info, "success", err
}
|
package main
import (
"net/http"
"database/sql"
"encoding/json"
"gopkg.in/validator.v2"
)
type credRequest struct {
Username string `json:"username" validate:"min=3,max=64,nonzero"`
Password string `json:"password" validate:"min=8,max=128,nonzero"`
}
type tokenResponse struct {
AccessToken string `json:"accessToken"`
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
var creds credRequest
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
http.Error(w, "malformed request", http.StatusBadRequest); return
}
if err := validator.Validate(creds); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest); return
}
/* query db */
id, err := RegisterUser(creds.Username, creds.Password)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest); return
}
/* return access token */
tokenString, err := GenerateToken(id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError); return
}
token := tokenResponse{AccessToken: tokenString}
w.Header().Add("content-type", "application/json")
json.NewEncoder(w).Encode(token)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
var creds credRequest
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
http.Error(w, "malformed request", http.StatusBadRequest); return
}
if err := validator.Validate(creds); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest); return
}
/* query db */
id, err := AuthenticateUser(creds.Username, creds.Password)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusUnauthorized)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
/* return token */
tokenString, err := GenerateToken(id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError); return
}
token := tokenResponse{AccessToken: tokenString}
w.Header().Add("content-type", "application/json")
json.NewEncoder(w).Encode(token)
}
func AuthRoutes(mux *http.ServeMux) {
mux.Handle("/auth/register", RestrictMethod("POST", http.HandlerFunc(registerHandler)))
mux.Handle("/auth/login", RestrictMethod("POST", http.HandlerFunc(loginHandler)))
}
|
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information
package processgroup_test
import (
"io"
"os"
"os/exec"
"testing"
"time"
"github.com/stretchr/testify/require"
"storj.io/common/processgroup"
"storj.io/common/testcontext"
)
func TestProcessGroup(t *testing.T) {
ctx := testcontext.New(t)
source := ctx.File("main.go")
binary := ctx.File("main.exe")
err := os.WriteFile(source, []byte(code), 0644)
require.NoError(t, err)
{
/* #nosec G204 */ // This is a test and both parameters' values are controlled
cmd := exec.Command("go", "build", "-o", binary, source)
cmd.Dir = ctx.Dir()
_, err := cmd.CombinedOutput()
require.NoError(t, err)
}
{
/* #nosec G204 */ // This is a test and the parameter's values is controlled
cmd := exec.Command(binary)
cmd.Dir = ctx.Dir()
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
processgroup.Setup(cmd)
started := time.Now()
err := cmd.Start()
require.NoError(t, err)
processgroup.Kill(cmd)
_ = cmd.Wait() // since we kill it, we might get an error
duration := time.Since(started)
require.Truef(t, duration < 10*time.Second, "completed in %s", duration)
}
}
const code = `package main
import "time"
func main() {
time.Sleep(20*time.Second)
}
`
|
package grpcx
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"github.com/socialpoint-labs/bsk/contextx"
)
// Daemon represents a runnable gRPC daemon.
//
// A gRPC Daemon will manage the lifecycle of the given gRPC server, gracefully shutting it down
// once the runner context is done.
//
// Typically, you'll want to pass one or more Applications as options. The daemon will register the gRPC
// endpoints of every application and run it with the runner context.
// A daemon can run without any Applications. This can be interesting for certain use cases where you want
// to manage the server by yourself and delegate the lifecycle management.
//
// Errors that might happen running the gRPC server will be passed through an optional error func.
// If none is given, they'll be printed to the standard output.
type Daemon struct {
svr *grpc.Server
lis net.Listener
apps []Application
ef func(error)
}
// Application is a contextx.Runner that can register gRPC services
type Application interface {
contextx.Runner
RegisterGRPC(grpc.ServiceRegistrar)
}
type DaemonOption func(*daemonOptions)
type daemonOptions struct {
apps []Application
ef func(error)
}
func WithApplications(apps ...Application) DaemonOption {
return func(opts *daemonOptions) {
opts.apps = apps
}
}
func WithErrorFunc(ef func(error)) DaemonOption {
return func(opts *daemonOptions) {
opts.ef = ef
}
}
// NewDaemon creates a gRPC Daemon for the given gRPC server and listener.
func NewDaemon(svr *grpc.Server, lis net.Listener, opts ...DaemonOption) Daemon {
options := &daemonOptions{
ef: defaultErrorFunc,
}
for _, opt := range opts {
opt(options)
}
return Daemon{
svr: svr,
lis: lis,
apps: options.apps,
ef: options.ef,
}
}
// Run registers every application of the Daemon with a gRPC server and runs them,
// then starts the server and gracefully shuts it down once the context is done.
func (d Daemon) Run(ctx context.Context) {
for _, app := range d.apps {
app.RegisterGRPC(d.svr)
go app.Run(ctx)
}
defer d.svr.GracefulStop()
go func() {
if err := d.svr.Serve(d.lis); err != nil {
d.ef(err)
return
}
}()
<-ctx.Done()
}
func defaultErrorFunc(err error) {
log.Println(err.Error())
}
|
package migration
import (
"encoding/base32"
"fmt"
"net/url"
)
var (
typeString = map[Payload_OtpType]string{
Payload_OTP_TYPE_HOTP: "hotp",
Payload_OTP_TYPE_TOTP: "totp",
}
algString = map[Payload_Algorithm]string{
Payload_ALGORITHM_SHA1: "SHA1",
Payload_ALGORITHM_SHA256: "SHA256",
Payload_ALGORITHM_SHA512: "SHA512",
Payload_ALGORITHM_MD5: "MD5",
}
digitsString = map[Payload_DigitCount]string{
Payload_DIGIT_COUNT_SIX: "6",
Payload_DIGIT_COUNT_EIGHT: "8",
}
)
func (op *Payload_OtpParameters) SecretString() string {
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(op.Secret)
}
func (op *Payload_OtpParameters) SecretTuples() []string {
secret := op.SecretString()
// pad secret to multiple of 4×4
tuples := make([]string, len(secret)/4)
for i := range tuples {
tuples[i] = secret[4*i : 4*i+4]
}
return tuples
}
// URL of otp parameters
func (op *Payload_OtpParameters) URL() *url.URL {
v := make(url.Values)
// required
v.Add("secret", op.SecretString())
// strongly recommended
if op.Issuer != "" {
v.Add("issuer", op.Issuer)
}
// optional
if op.Algorithm != Payload_ALGORITHM_UNSPECIFIED {
v.Add("algorithm", algString[op.Algorithm])
}
// optional
if op.Digits != Payload_DIGIT_COUNT_UNSPECIFIED {
v.Add("digits", digitsString[op.Digits])
}
// required if type is hotp
if op.Type == Payload_OTP_TYPE_HOTP {
v.Add("counter", fmt.Sprint(op.Counter))
}
// optional if type is totp
if op.Type == Payload_OTP_TYPE_TOTP {
v.Add("period", "30") // default value
}
return &url.URL{
Scheme: "otpauth",
Host: typeString[op.Type],
Path: op.Name,
RawQuery: v.Encode(),
}
}
|
package examples
import (
"io"
"math/rand"
"os"
"github.com/go-echarts/go-echarts/v2/charts"
"github.com/go-echarts/go-echarts/v2/components"
"github.com/go-echarts/go-echarts/v2/opts"
)
var dimensions = []string{"Visit", "Add", "Order", "Payment", "Deal"}
func genFunnelKvItems() []opts.FunnelData {
items := make([]opts.FunnelData, 0)
for i := 0; i < len(dimensions); i++ {
items = append(items, opts.FunnelData{Name: dimensions[i], Value: rand.Intn(50)})
}
return items
}
func funnelBase() *charts.Funnel {
funnel := charts.NewFunnel()
funnel.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "basic funnel example"}),
)
funnel.AddSeries("Analytics", genFunnelKvItems())
return funnel
}
// TODO: check the different from echarts side
func funnelShowLabel() *charts.Funnel {
funnel := charts.NewFunnel()
funnel.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "show label"}),
)
funnel.AddSeries("Analytics", genFunnelKvItems()).
SetSeriesOptions(charts.WithLabelOpts(
opts.Label{
Show: true,
Position: "left",
},
))
return funnel
}
type FunnelExamples struct{}
func (FunnelExamples) Examples() {
page := components.NewPage()
page.AddCharts(
funnelBase(),
funnelShowLabel(),
)
f, err := os.Create("examples/html/funnel.html")
if err != nil {
panic(err)
}
page.Render(io.MultiWriter(f))
}
|
// 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
// PageSizeations under the License.
package shell
import (
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud/aliyun"
"yunion.io/x/onecloud/pkg/util/shellutils"
)
func init() {
type CenListOptions struct {
PageSize int `help:"page size"`
PageNumber int `help:"page PageNumber"`
}
shellutils.R(&CenListOptions{}, "cen-list", "List cloud enterprise network", func(cli *aliyun.SRegion, args *CenListOptions) error {
scens, e := cli.GetClient().DescribeCens(args.PageNumber, args.PageSize)
if e != nil {
return e
}
printList(scens.Cens.Cen, scens.TotalCount, args.PageNumber, args.PageSize, []string{})
return nil
})
type CenChildListOptions struct {
ID string `help:"cen id"`
PageSize int `help:"page size"`
PageNumber int `help:"page PageNumber"`
}
shellutils.R(&CenChildListOptions{}, "cen-child-list", "List cloud enterprise network childs", func(cli *aliyun.SRegion, args *CenChildListOptions) error {
schilds, e := cli.GetClient().DescribeCenAttachedChildInstances(args.ID, args.PageNumber, args.PageSize)
if e != nil {
return e
}
printList(schilds.ChildInstances.ChildInstance, schilds.TotalCount, args.PageNumber, args.PageSize, []string{})
return nil
})
type CenCreateOptions struct {
Name string
Description string
}
shellutils.R(&CenCreateOptions{}, "cen-create", "Create cloud enterprise network", func(cli *aliyun.SRegion, args *CenCreateOptions) error {
opts := cloudprovider.SInterVpcNetworkCreateOptions{}
opts.Name = args.Name
opts.Desc = args.Description
scen, e := cli.GetClient().CreateCen(&opts)
if e != nil {
return e
}
print(scen)
return nil
})
type CenDeleteOptions struct {
ID string
}
shellutils.R(&CenDeleteOptions{}, "cen-delete", "delete cloud enterprise network", func(cli *aliyun.SRegion, args *CenDeleteOptions) error {
e := cli.GetClient().DeleteCen(args.ID)
if e != nil {
return e
}
return nil
})
type CenAddVpcOptions struct {
ID string
VpcId string
VpcRegionId string
}
shellutils.R(&CenAddVpcOptions{}, "cen-add-vpc", "add vpc to cloud enterprise network", func(cli *aliyun.SRegion, args *CenAddVpcOptions) error {
instance := aliyun.SCenAttachInstanceInput{
InstanceType: "VPC",
InstanceId: args.VpcId,
InstanceRegion: args.VpcRegionId,
}
e := cli.GetClient().AttachCenChildInstance(args.ID, instance)
if e != nil {
return e
}
return nil
})
type CenRemoveVpcOptions struct {
ID string
VpcId string
VpcRegionId string
}
shellutils.R(&CenRemoveVpcOptions{}, "cen-remove-vpc", "remove vpc to cloud enterprise network", func(cli *aliyun.SRegion, args *CenRemoveVpcOptions) error {
instance := aliyun.SCenAttachInstanceInput{
InstanceType: "VPC",
InstanceId: args.VpcId,
InstanceRegion: args.VpcRegionId,
}
e := cli.GetClient().DetachCenChildInstance(args.ID, instance)
if e != nil {
return e
}
return nil
})
}
|
// Copyright 2019 - 2022 The Samply Community
//
// 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 fhir
import "encoding/json"
// THIS FILE IS GENERATED BY https://github.com/samply/golang-fhir-models
// PLEASE DO NOT EDIT BY HAND
// MedicinalProductUndesirableEffect is documented here http://hl7.org/fhir/StructureDefinition/MedicinalProductUndesirableEffect
type MedicinalProductUndesirableEffect struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"`
ImplicitRules *string `bson:"implicitRules,omitempty" json:"implicitRules,omitempty"`
Language *string `bson:"language,omitempty" json:"language,omitempty"`
Text *Narrative `bson:"text,omitempty" json:"text,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Subject []Reference `bson:"subject,omitempty" json:"subject,omitempty"`
SymptomConditionEffect *CodeableConcept `bson:"symptomConditionEffect,omitempty" json:"symptomConditionEffect,omitempty"`
Classification *CodeableConcept `bson:"classification,omitempty" json:"classification,omitempty"`
FrequencyOfOccurrence *CodeableConcept `bson:"frequencyOfOccurrence,omitempty" json:"frequencyOfOccurrence,omitempty"`
Population []Population `bson:"population,omitempty" json:"population,omitempty"`
}
type OtherMedicinalProductUndesirableEffect MedicinalProductUndesirableEffect
// MarshalJSON marshals the given MedicinalProductUndesirableEffect as JSON into a byte slice
func (r MedicinalProductUndesirableEffect) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
OtherMedicinalProductUndesirableEffect
ResourceType string `json:"resourceType"`
}{
OtherMedicinalProductUndesirableEffect: OtherMedicinalProductUndesirableEffect(r),
ResourceType: "MedicinalProductUndesirableEffect",
})
}
// UnmarshalMedicinalProductUndesirableEffect unmarshals a MedicinalProductUndesirableEffect.
func UnmarshalMedicinalProductUndesirableEffect(b []byte) (MedicinalProductUndesirableEffect, error) {
var medicinalProductUndesirableEffect MedicinalProductUndesirableEffect
if err := json.Unmarshal(b, &medicinalProductUndesirableEffect); err != nil {
return medicinalProductUndesirableEffect, err
}
return medicinalProductUndesirableEffect, nil
}
|
// Copyright © 2020 Weald Technology Trading
// 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 signer
import (
context "context"
"fmt"
"github.com/opentracing/opentracing-go"
"github.com/wealdtech/walletd/core"
"github.com/wealdtech/walletd/services/checker"
"github.com/wealdtech/walletd/services/ruler"
)
// Checkpoint is a copy of the Ethereum 2 Checkpoint struct with SSZ size information.
type Checkpoint struct {
Epoch uint64
Root []byte `ssz-size:"32"`
}
// BeaconAttestation is a copy of the Ethereum 2 BeaconAttestation struct with SSZ size information.
type BeaconAttestation struct {
Slot uint64
CommitteeIndex uint64
BeaconBlockRoot []byte `ssz-size:"32"`
Source *Checkpoint
Target *Checkpoint
}
// SignBeaconAttestation signs a attestation for a beacon block.
func (s *Service) SignBeaconAttestation(ctx context.Context, credentials *checker.Credentials, accountName string, pubKey []byte, data *ruler.SignBeaconAttestationData) (core.RulesResult, []byte) {
span, ctx := opentracing.StartSpanFromContext(ctx, "services.signer.SignBeaconAttestation")
defer span.Finish()
log := log.With().Str("action", "SignBeaconAttestation").Logger()
log.Debug().Msg("Request received")
wallet, account, checkRes := s.preCheck(ctx, credentials, accountName, pubKey, ruler.ActionSignBeaconAttestation)
if checkRes != core.APPROVED {
return checkRes, nil
}
accountName = fmt.Sprintf("%s/%s", wallet.Name(), account.Name())
log = log.With().Str("account", accountName).Logger()
// Confirm approval via rules.
result := s.ruler.RunRules(ctx, ruler.ActionSignBeaconAttestation, wallet.Name(), account.Name(), account.PublicKey().Marshal(), data)
switch result {
case core.DENIED:
log.Debug().Str("result", "denied").Msg("Denied by rules")
return core.DENIED, nil
case core.FAILED:
log.Warn().Str("result", "failed").Msg("Rules check failed")
return core.FAILED, nil
}
// Create a local copy of the data; we need ssz size information to calculate the correct root.
attestation := &BeaconAttestation{
Slot: data.Slot,
CommitteeIndex: data.CommitteeIndex,
BeaconBlockRoot: data.BeaconBlockRoot,
Source: &Checkpoint{
Epoch: data.Source.Epoch,
Root: data.Source.Root,
},
Target: &Checkpoint{
Epoch: data.Target.Epoch,
Root: data.Target.Root,
},
}
// Sign it.
signingRoot, err := generateSigningRootFromData(ctx, attestation, data.Domain)
if err != nil {
log.Warn().Err(err).Str("result", "failed").Msg("Failed to generate signing root")
return core.FAILED, nil
}
signature, err := signRoot(ctx, account, signingRoot[:])
if err != nil {
log.Warn().Err(err).Str("result", "failed").Msg("Failed to sign")
return core.FAILED, nil
}
log.Debug().Str("result", "succeeded").Msg("Success")
return core.APPROVED, signature
}
|
package goroutines
import "fmt"
import "time"
func gofun(name string) {
for i := 0; i < 3; i++ {
fmt.Println(name, ":", i)
}
time.Sleep(2000 * time.Millisecond)
fmt.Println("Done", name)
}
func testGoRoutines() {
gofun("Direct call")
go gofun("goroutine")
go func(msg string) {
time.Sleep(4000 * time.Millisecond)
fmt.Println(msg)
}("go anonymous")
time.Sleep(5000 * time.Millisecond)
fmt.Println("Done testGoRoutines")
}
|
package server
// all functions under this package
func Insert(a configor) (num int64, err error) {
num, err = a.GetTabler().Insert()
if err != nil {
return
}
return a.GetCacher().Insert()
}
func Delete(a configor) (num int64, err error) {
num, err = a.GetTabler().Delete()
if err != nil {
return
}
return a.GetCacher().Delete()
}
func Update(a configor) (num int64, err error) {
num, err = a.GetTabler().Update()
if err != nil {
return
}
return a.GetCacher().Update()
}
func Get(a configor) (exist bool, err error) {
exist, _ = a.GetCacher().Get()
if !exist || err != nil {
exist, err = a.GetTabler().Get()
}
return
}
|
package odoo
import (
"fmt"
)
// ResLang represents res.lang model.
type ResLang struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
Active *Bool `xmlrpc:"active,omptempty"`
Code *String `xmlrpc:"code,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty"`
DateFormat *String `xmlrpc:"date_format,omptempty"`
DecimalPoint *String `xmlrpc:"decimal_point,omptempty"`
Direction *Selection `xmlrpc:"direction,omptempty"`
DisplayName *String `xmlrpc:"display_name,omptempty"`
Grouping *String `xmlrpc:"grouping,omptempty"`
Id *Int `xmlrpc:"id,omptempty"`
IsoCode *String `xmlrpc:"iso_code,omptempty"`
Name *String `xmlrpc:"name,omptempty"`
ThousandsSep *String `xmlrpc:"thousands_sep,omptempty"`
TimeFormat *String `xmlrpc:"time_format,omptempty"`
Translatable *Bool `xmlrpc:"translatable,omptempty"`
WriteDate *Time `xmlrpc:"write_date,omptempty"`
WriteUid *Many2One `xmlrpc:"write_uid,omptempty"`
}
// ResLangs represents array of res.lang model.
type ResLangs []ResLang
// ResLangModel is the odoo model name.
const ResLangModel = "res.lang"
// Many2One convert ResLang to *Many2One.
func (rl *ResLang) Many2One() *Many2One {
return NewMany2One(rl.Id.Get(), "")
}
// CreateResLang creates a new res.lang model and returns its id.
func (c *Client) CreateResLang(rl *ResLang) (int64, error) {
ids, err := c.CreateResLangs([]*ResLang{rl})
if err != nil {
return -1, err
}
if len(ids) == 0 {
return -1, nil
}
return ids[0], nil
}
// CreateResLang creates a new res.lang model and returns its id.
func (c *Client) CreateResLangs(rls []*ResLang) ([]int64, error) {
var vv []interface{}
for _, v := range rls {
vv = append(vv, v)
}
return c.Create(ResLangModel, vv)
}
// UpdateResLang updates an existing res.lang record.
func (c *Client) UpdateResLang(rl *ResLang) error {
return c.UpdateResLangs([]int64{rl.Id.Get()}, rl)
}
// UpdateResLangs updates existing res.lang records.
// All records (represented by ids) will be updated by rl values.
func (c *Client) UpdateResLangs(ids []int64, rl *ResLang) error {
return c.Update(ResLangModel, ids, rl)
}
// DeleteResLang deletes an existing res.lang record.
func (c *Client) DeleteResLang(id int64) error {
return c.DeleteResLangs([]int64{id})
}
// DeleteResLangs deletes existing res.lang records.
func (c *Client) DeleteResLangs(ids []int64) error {
return c.Delete(ResLangModel, ids)
}
// GetResLang gets res.lang existing record.
func (c *Client) GetResLang(id int64) (*ResLang, error) {
rls, err := c.GetResLangs([]int64{id})
if err != nil {
return nil, err
}
if rls != nil && len(*rls) > 0 {
return &((*rls)[0]), nil
}
return nil, fmt.Errorf("id %v of res.lang not found", id)
}
// GetResLangs gets res.lang existing records.
func (c *Client) GetResLangs(ids []int64) (*ResLangs, error) {
rls := &ResLangs{}
if err := c.Read(ResLangModel, ids, nil, rls); err != nil {
return nil, err
}
return rls, nil
}
// FindResLang finds res.lang record by querying it with criteria.
func (c *Client) FindResLang(criteria *Criteria) (*ResLang, error) {
rls := &ResLangs{}
if err := c.SearchRead(ResLangModel, criteria, NewOptions().Limit(1), rls); err != nil {
return nil, err
}
if rls != nil && len(*rls) > 0 {
return &((*rls)[0]), nil
}
return nil, fmt.Errorf("res.lang was not found with criteria %v", criteria)
}
// FindResLangs finds res.lang records by querying it
// and filtering it with criteria and options.
func (c *Client) FindResLangs(criteria *Criteria, options *Options) (*ResLangs, error) {
rls := &ResLangs{}
if err := c.SearchRead(ResLangModel, criteria, options, rls); err != nil {
return nil, err
}
return rls, nil
}
// FindResLangIds finds records ids by querying it
// and filtering it with criteria and options.
func (c *Client) FindResLangIds(criteria *Criteria, options *Options) ([]int64, error) {
ids, err := c.Search(ResLangModel, criteria, options)
if err != nil {
return []int64{}, err
}
return ids, nil
}
// FindResLangId finds record id by querying it with criteria.
func (c *Client) FindResLangId(criteria *Criteria, options *Options) (int64, error) {
ids, err := c.Search(ResLangModel, criteria, options)
if err != nil {
return -1, err
}
if len(ids) > 0 {
return ids[0], nil
}
return -1, fmt.Errorf("res.lang was not found with criteria %v and options %v", criteria, options)
}
|
package main
import (
"log"
"net/http"
"github.com/goinaction/code/chapter9/listing17/handlers"
)
func main() {
handlers.Routes()
log.Println("listener: started: listening on :4000")
http.ListenAndServe(":4000", nil)
} |
package odoo
import (
"fmt"
)
// AccountFiscalPositionTax represents account.fiscal.position.tax model.
type AccountFiscalPositionTax struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty"`
DisplayName *String `xmlrpc:"display_name,omptempty"`
Id *Int `xmlrpc:"id,omptempty"`
PositionId *Many2One `xmlrpc:"position_id,omptempty"`
TaxDestId *Many2One `xmlrpc:"tax_dest_id,omptempty"`
TaxSrcId *Many2One `xmlrpc:"tax_src_id,omptempty"`
WriteDate *Time `xmlrpc:"write_date,omptempty"`
WriteUid *Many2One `xmlrpc:"write_uid,omptempty"`
}
// AccountFiscalPositionTaxs represents array of account.fiscal.position.tax model.
type AccountFiscalPositionTaxs []AccountFiscalPositionTax
// AccountFiscalPositionTaxModel is the odoo model name.
const AccountFiscalPositionTaxModel = "account.fiscal.position.tax"
// Many2One convert AccountFiscalPositionTax to *Many2One.
func (afpt *AccountFiscalPositionTax) Many2One() *Many2One {
return NewMany2One(afpt.Id.Get(), "")
}
// CreateAccountFiscalPositionTax creates a new account.fiscal.position.tax model and returns its id.
func (c *Client) CreateAccountFiscalPositionTax(afpt *AccountFiscalPositionTax) (int64, error) {
ids, err := c.CreateAccountFiscalPositionTaxs([]*AccountFiscalPositionTax{afpt})
if err != nil {
return -1, err
}
if len(ids) == 0 {
return -1, nil
}
return ids[0], nil
}
// CreateAccountFiscalPositionTax creates a new account.fiscal.position.tax model and returns its id.
func (c *Client) CreateAccountFiscalPositionTaxs(afpts []*AccountFiscalPositionTax) ([]int64, error) {
var vv []interface{}
for _, v := range afpts {
vv = append(vv, v)
}
return c.Create(AccountFiscalPositionTaxModel, vv)
}
// UpdateAccountFiscalPositionTax updates an existing account.fiscal.position.tax record.
func (c *Client) UpdateAccountFiscalPositionTax(afpt *AccountFiscalPositionTax) error {
return c.UpdateAccountFiscalPositionTaxs([]int64{afpt.Id.Get()}, afpt)
}
// UpdateAccountFiscalPositionTaxs updates existing account.fiscal.position.tax records.
// All records (represented by ids) will be updated by afpt values.
func (c *Client) UpdateAccountFiscalPositionTaxs(ids []int64, afpt *AccountFiscalPositionTax) error {
return c.Update(AccountFiscalPositionTaxModel, ids, afpt)
}
// DeleteAccountFiscalPositionTax deletes an existing account.fiscal.position.tax record.
func (c *Client) DeleteAccountFiscalPositionTax(id int64) error {
return c.DeleteAccountFiscalPositionTaxs([]int64{id})
}
// DeleteAccountFiscalPositionTaxs deletes existing account.fiscal.position.tax records.
func (c *Client) DeleteAccountFiscalPositionTaxs(ids []int64) error {
return c.Delete(AccountFiscalPositionTaxModel, ids)
}
// GetAccountFiscalPositionTax gets account.fiscal.position.tax existing record.
func (c *Client) GetAccountFiscalPositionTax(id int64) (*AccountFiscalPositionTax, error) {
afpts, err := c.GetAccountFiscalPositionTaxs([]int64{id})
if err != nil {
return nil, err
}
if afpts != nil && len(*afpts) > 0 {
return &((*afpts)[0]), nil
}
return nil, fmt.Errorf("id %v of account.fiscal.position.tax not found", id)
}
// GetAccountFiscalPositionTaxs gets account.fiscal.position.tax existing records.
func (c *Client) GetAccountFiscalPositionTaxs(ids []int64) (*AccountFiscalPositionTaxs, error) {
afpts := &AccountFiscalPositionTaxs{}
if err := c.Read(AccountFiscalPositionTaxModel, ids, nil, afpts); err != nil {
return nil, err
}
return afpts, nil
}
// FindAccountFiscalPositionTax finds account.fiscal.position.tax record by querying it with criteria.
func (c *Client) FindAccountFiscalPositionTax(criteria *Criteria) (*AccountFiscalPositionTax, error) {
afpts := &AccountFiscalPositionTaxs{}
if err := c.SearchRead(AccountFiscalPositionTaxModel, criteria, NewOptions().Limit(1), afpts); err != nil {
return nil, err
}
if afpts != nil && len(*afpts) > 0 {
return &((*afpts)[0]), nil
}
return nil, fmt.Errorf("account.fiscal.position.tax was not found with criteria %v", criteria)
}
// FindAccountFiscalPositionTaxs finds account.fiscal.position.tax records by querying it
// and filtering it with criteria and options.
func (c *Client) FindAccountFiscalPositionTaxs(criteria *Criteria, options *Options) (*AccountFiscalPositionTaxs, error) {
afpts := &AccountFiscalPositionTaxs{}
if err := c.SearchRead(AccountFiscalPositionTaxModel, criteria, options, afpts); err != nil {
return nil, err
}
return afpts, nil
}
// FindAccountFiscalPositionTaxIds finds records ids by querying it
// and filtering it with criteria and options.
func (c *Client) FindAccountFiscalPositionTaxIds(criteria *Criteria, options *Options) ([]int64, error) {
ids, err := c.Search(AccountFiscalPositionTaxModel, criteria, options)
if err != nil {
return []int64{}, err
}
return ids, nil
}
// FindAccountFiscalPositionTaxId finds record id by querying it with criteria.
func (c *Client) FindAccountFiscalPositionTaxId(criteria *Criteria, options *Options) (int64, error) {
ids, err := c.Search(AccountFiscalPositionTaxModel, criteria, options)
if err != nil {
return -1, err
}
if len(ids) > 0 {
return ids[0], nil
}
return -1, fmt.Errorf("account.fiscal.position.tax was not found with criteria %v and options %v", criteria, options)
}
|
// Copyright (C) 2019 rameshvk. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.
package partition
import (
"context"
"fmt"
"hash/crc32"
"sort"
"strconv"
"sync"
)
// NewHashRing returns a picker which uses a consistent hashing scheme
//
// The scheme is implemented using a hash ring of crc32 hashes.
func NewHashRing() func(ctx context.Context, list []string, hash uint64) string {
ring := &hashring{factor: 1000}
return ring.Pick
}
type hashring struct {
factor int // how many time to duplicate a single key for getting uniform spread
sync.Mutex
list []string
hashes []uint32 // sorted
lookup map[uint32]string // hash => list entry
}
func (h *hashring) Pick(ctx context.Context, list []string, hash uint64) string {
if len(list) == 0 {
return ""
}
hash32 := crc32.ChecksumIEEE([]byte(fmt.Sprint(hash)))
hashes, lookup := h.getSortedHashes(list)
idx := sort.Search(len(hashes), func(i int) bool { return hashes[i] >= hash32 })
if idx == len(hashes) {
idx = 0
}
return lookup[hashes[idx]]
}
func (h *hashring) getSortedHashes(list []string) ([]uint32, map[uint32]string) {
h.Lock()
defer h.Unlock()
if h.listsDifferent(h.list, list) {
h.list = list
h.hashes, h.lookup = h.calculateSortedHashes(list)
}
return h.hashes, h.lookup
}
func (h *hashring) calculateSortedHashes(list []string) ([]uint32, map[uint32]string) {
hashes := make([]uint32, len(list)*h.factor)
dict := map[uint32]string{}
for kk := range list {
for ff := 0; ff < h.factor; ff++ {
data := []byte(strconv.Itoa(ff*12394+1) + "-" + list[kk])
idx := kk*h.factor + ff
hashes[idx] = crc32.ChecksumIEEE(data)
dict[hashes[idx]] = list[kk]
}
}
sort.Slice(hashes, func(i, j int) bool { return hashes[i] < hashes[j] })
return hashes, dict
}
func (h *hashring) listsDifferent(l1, l2 []string) bool {
if len(l1) != len(l2) {
return true
}
for kk := range l1 {
if l1[kk] != l2[kk] {
return true
}
}
return false
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// Package avl - an AVL balanced tree with the addition of parent
// pointers to allow iteration through the nodes
//
// Note: an individual tree is not thread safe, so either access only
// in a single go routine or use mutex/rwmutex to restrict
// access.
//
// The base algorithm was described in an old book by Niklaus Wirth
// called Algorithms + Data Structures = Programs.
//
// This version allows for data associated with key, which can be
// overwritten by an insert with the same key. Also delete no does
// not copy data around so that previous nodes can be deleted during
// iteration.
package avl
|
package models
import (
"bytes"
"crypto/md5"
"encoding/hex"
"html/template"
"net/smtp"
"os"
"strconv"
"strings"
"time"
)
/*
* user : example@example.com login smtp server user
* password: xxxxx login smtp server password
* host: smtp.example.com:port smtp.163.com:25
* to: example@example.com;example1@163.com;example2@sina.com.cn;...
* subject:The subject of mail
* body: The content of mail
* mailtyoe: mail type html or text
*/
func sendMail(user, password, host, to, subject, body, mailtype string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", user, password, hp[0])
var content_type string
if mailtype == "html" {
content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
} else {
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host, auth, user, send_to, msg)
return err
}
func ForGotSend(to string, vcode string) {
user := "WeNedFound@163.com"
password := "TimeToFound"
host := "smtp.163.com:25"
subject := "Verification account From Found"
body := `
<html>
<body>
<h3>
{{.}}
</h3>
</body>
</html>
`
var buf bytes.Buffer
t := template.New("email")
t, _ = t.Parse(body)
t.Execute(&buf, vcode)
sendMail(user, password, host, to, subject, buf.String(), "html")
}
func MakeVcode(uname string) string {
p := uname + time.Now().Format("2006-01-02 15:04:05") + strconv.Itoa(os.Getpid())
md := md5.New()
md.Write([]byte(p))
sum := md.Sum(nil)
return hex.EncodeToString(sum)
}
|
package repository
import (
"context"
"github.com/caos/zitadel/internal/iam/model"
)
type IamRepository interface {
Health(ctx context.Context) error
IamByID(ctx context.Context, id string) (*model.Iam, error)
}
|
package slog
import (
"fmt"
"log"
"os"
"strings"
"sync"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var rootLogger = NewDebugLogger(``, zapcore.DebugLevel)
//必须先初始化rootLogger,否则调用此方法将抛出空指针错误
func NewLogger(cfg *Conf, tags ...string) *zap.Logger {
if cfg == nil {
log.Printf("获取日志配置出错[%v]\n", cfg)
}
//初始化日志组件,建议在主程序启动前调用此方法
rootLogger = MustInitRootLoggerFromCfg(*cfg)
return rootLogger.With(NewTagField(tags...))
}
//用于调试的日志器
func NewDebugLogger(tag string, level zapcore.Level) *zap.Logger {
c := zap.NewDevelopmentConfig()
c.Level = zap.NewAtomicLevelAt(level)
c.DisableStacktrace = true
c.EncoderConfig.EncodeCaller = zapcore.FullCallerEncoder
c.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
logger, err := c.Build()
if err != nil {
panic(fmt.Errorf(`create debug logger err[%v]`, err))
}
if tag == "" {
return logger
}
return logger.With(NewTagField(tag))
}
func NewTagField(tags ...string) zap.Field {
return zap.String(LogTagFieldName, strings.Join(tags, `.`))
}
// 根据日志配置初始化日志组件
func MustInitRootLoggerFromCfg(cfg Conf) *zap.Logger {
cfg = cfg.Normalize()
level := zap.NewAtomicLevelAt(cfg.Level)
encoderCfg := zap.NewDevelopmentEncoderConfig()
if !cfg.DisableColor {
encoderCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
if !cfg.EnableShortCaller {
encoderCfg.EncodeCaller = zapcore.FullCallerEncoder
}
var (
options []zap.Option
allCore []zapcore.Core // 如果需要使用日志系统.请添加对应core, 需处理 encoder,writer,core
)
// 如需过滤日志标签,请添加encoder的处理
var encoder zapcore.Encoder
if cfg.Encoding == `json` {
encoder = zapcore.NewJSONEncoder(encoderCfg)
} else {
encoder = zapcore.NewConsoleEncoder(encoderCfg)
}
// 如果writer不支持并发访问,必须使用锁独占writer
// 文件是不支持并发写入的. 详情见zapcore.Lock(), zap.CombineWriteSyncers()
var writers []zapcore.WriteSyncer
if cfg.WriteToConsole {
writers = append(writers, zapcore.AddSync(os.Stdout))
}
if cfg.WriteToLogFile {
w := zapcore.AddSync(&lumberjack.Logger{
Filename: cfg.LogFilePath,
MaxSize: cfg.LogFileMaxSize,
MaxBackups: cfg.LogFileMaxBackups,
MaxAge: cfg.LogFileMaxAge,
Compress: cfg.CompressLogFile,
})
writers = append(writers, w)
}
if cfg.Debug {
options = append(options, zap.Development())
}
if !cfg.DisableCaller {
options = append(options, zap.AddCaller(), zap.AddCallerSkip(cfg.CallerSkip))
}
if cfg.EnableStackTrace {
options = append(options, zap.AddStacktrace(level))
}
core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(writers...), level)
allCore = append(allCore, core)
core = zapcore.NewTee(allCore...)
return zap.New(core, options...)
}
//清空缓存的日志,此方法应在主程序退出前调用
func Flush() error {
if rootLogger != nil {
return rootLogger.Sync()
}
return nil
}
// 提供给标准库log使用
func StdLogger(logger *zap.Logger) *log.Logger {
logCh := make(chan string, 100)
var wg sync.WaitGroup
wg.Add(1)
go func() {
wg.Done()
for {
logStr := <-logCh
logger.Info(logStr[:len(logStr)-1])
}
}()
wg.Wait()
return log.New(&Writer{
LogCh: logCh,
}, "", log.Lmsgprefix)
}
type Writer struct {
LogCh chan string
}
func (w *Writer) Write(p []byte) (n int, err error) {
n = len(p)
w.LogCh <- string(p)
return
}
|
package main
import (
"database/sql"
_ "github.com/lib/pq"
"log"
"fmt"
)
func main () {
db, err := sql.Open("postgres", "password=password host=localhost dbname=mit_workshop sslmode=disable")
if err != nil {
log.Fatal(err)
}
var insert_users string = "Insert into Users(id, email) values($1, $2)"
insert_users_prepare, err := db.Prepare(insert_users)
if err!= nil {
log.Fatal(err)
}
defer insert_users_prepare.Close()
insert_res, err := insert_users_prepare.Exec(1, "praveen@yopmail.com")
if err != nil || insert_res == nil{
log.Fatal(err)
}
email_query, err := db.Query("SELECT email FROM users where id = 1")
if err != nil {
log.Fatal(err)
}
defer email_query.Close()
for email_query.Next() {
var email string
err := email_query.Scan(&email)
if err != nil {
log.Fatal(err)
}
fmt.Println("Email:", email)
}
db.Close()
}
|
package main
import "fmt"
func main() {
a := 43
fmt.Println(a)
fmt.Println(&a)
var b *int = &a
fmt.Println(b)
fmt.Println(*b)
*b = 42 //o valor nesse endereco de memoria vai para 42
fmt.Println(a)
}
// isso é importante
// nos podemos passar o endereco de memoria ao invez de um monte de valores
// (nos passamos uma REFERENCIA)
// isso faz nossos programas mais eficiente
// nos nao precisamos passar grandes quantidades de dados
// nos passamos apenas o endereco
//
// tudo é transmitido por valor em go
// quando passamos endereco de memoria, nos estamos passando (transmitindo) um valor.
|
package main
import "fmt"
func Min(x, y int) int {
if x < y {
return x
}
return y
}
func minDistance(word1 string, word2 string) int {
if len(word1) == 0 {
return len(word2)
}
if len(word2) == 0 {
return len(word1)
}
mat := make([][]int, len(word1)+1)
for i := 0; i <= len(word1); i = i + 1 {
mat[i] = make([]int, len(word2)+1)
mat[i][0] = i
}
for i := 0; i <= len(word2); i = i + 1 {
mat[0][i] = i
}
mat[0][0] = 0
for i := 1; i <= len(word1); i = i + 1 {
for j := 1; j <= len(word2); j = j + 1 {
if word1[i-1] == word2[j-1] {
mat[i][j] = mat[i-1][j-1]
} else {
mat[i][j] = Min(Min(mat[i-1][j], mat[i][j-1]), mat[i-1][j-1]) + 1
}
}
}
return mat[len(word1)][len(word2)]
}
func main() {
x := "intention"
y := "execution"
x = "plasma"
y = "altruism"
// x = "horse"
// y = "ros"
// x := "int"
// y := "fat"
fmt.Println(minDistance(x, y))
}
|
package com
//内容||文章
import (
"JsGo/JsBench/JsContent"
"JsGo/JsHttp"
"JsGo/JsLogger"
"JsGo/JsStore/JsRedis"
"JunSie/constant"
"JunSie/util"
"encoding/json"
"fmt"
)
type XM_Contents struct {
JsContent.Contents
}
func Init_content() {
JsHttp.WhiteHttps("/newcontent", NewContent) //创建内容
JsHttp.WhiteHttp("/querycontent", QueryContent) //查询内容
JsHttp.WhiteHttp("/querymorecontents", QueryMoreContents) //查询多个内容
JsHttp.WhiteHttps("/modcontent", ModContent) //修改多个内容
JsHttp.WhiteHttps("/delcontentdb", DelContentDB) //永久删除内容
JsHttp.WhiteHttps("/delcontentmark", DelContentMark) //标记删除内容
JsHttp.WhiteHttps("/updowncontent", UpdownContent) //上下架内容
JsHttp.WhiteHttp("/getpagecontent", GetPageContent) //获取分页内容
JsHttp.WhiteHttp("/getcontentnums", GetContentNums) //获取不同状态内容的数量
JsHttp.WhiteHttps("/newcontentdraft", SaveContentDraft) //保存内容草稿
JsHttp.WhiteHttps("/removecontentdraft", QueryContentDraft) //查询内容草稿
JsHttp.WhiteHttp("/getcontentductdraft", RemoveContentDraft) ///删除某一个内容草稿
JsHttp.WhiteHttps("/removecontenttag", RemoveContentTag) //移除产品的某一个标签
JsHttp.WhiteHttp("/getcontenttags", GetContentTags) //获取产品的所有标签
JsHttp.WhiteHttp("/getcontentstatics", GetContentStatics) //获取内容统计
JsHttp.WhiteHttps("/newcontentvisit", NewContentVisit) //内容访问
JsHttp.WhiteHttps("/newcontentpraise", NewContentPraise) //内容点赞
JsHttp.WhiteHttps("/newcontentattention", NewContentAttention) //内容关注
JsHttp.WhiteHttps("/cancelcontentpraise", RemoveContentPraise) //内容取消点赞
JsHttp.WhiteHttps("/cancelcontentattention", RemoveContentAttention) //内容取消关注
JsHttp.WhiteHttps("/cancelcontentatvisit", RemoveArtVisit) //删除内容访问(+)
}
func Init_contentMall() {
JsHttp.WhiteHttps("/newcontent", NewContent) //创建内容
JsHttp.WhiteHttps("/querycontent", QueryContent) //查询内容
JsHttp.WhiteHttps("/querymorecontents", QueryMoreContents) //查询多个内容
JsHttp.WhiteHttps("/modcontent", ModContent) //修改多个内容
JsHttp.WhiteHttps("/delcontentdb", DelContentDB) //永久删除内容
JsHttp.WhiteHttps("/delcontentmark", DelContentMark) //标记删除内容
JsHttp.WhiteHttps("/updowncontent", UpdownContent) //上下架内容
JsHttp.WhiteHttps("/getpagecontent", GetPageContent) //获取分页内容
JsHttp.WhiteHttps("/getcontentnums", GetContentNums) //获取不同状态内容的数量
JsHttp.WhiteHttps("/newcontentdraft", SaveContentDraft) //保存内容草稿
JsHttp.WhiteHttps("/removecontentdraft", QueryContentDraft) //查询内容草稿
JsHttp.WhiteHttps("/getcontentductdraft", RemoveContentDraft) ///删除某一个内容草稿
JsHttp.WhiteHttps("/removecontenttag", RemoveContentTag) //移除产品的某一个标签
JsHttp.WhiteHttps("/getcontenttags", GetContentTags) //获取产品的所有标签
JsHttp.WhiteHttps("/getcontentstatics", GetContentStatics) //获取内容统计
JsHttp.WhiteHttps("/newcontentvisit", NewContentVisit) //内容访问
JsHttp.WhiteHttps("/newcontentpraise", NewContentPraise) //内容点赞
JsHttp.WhiteHttps("/newcontentattention", NewContentAttention) //内容关注
JsHttp.WhiteHttps("/cancelcontentpraise", RemoveContentPraise) //内容取消点赞
JsHttp.WhiteHttps("/cancelcontentattention", RemoveContentAttention) //内容取消关注
JsHttp.WhiteHttps("/cancelcontentatvisit", RemoveArtVisit) //删除内容访问(+)
}
//新建内容
func NewContent(s *JsHttp.Session) {
type Para struct {
CT XM_Contents //内容结构
Tags []string //标签列表
}
st := &Para{}
if err := s.GetPara(st); err != nil {
s.Forward("1", err.Error(), st)
return
}
st.CT.ID = util.IDer(constant.DB_Content)
st.CT.CreatDate = util.CurDate()
if st.CT.UID == "" {
info := "NewContent,UID is empty\n"
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if st.CT.Status == "" {
st.CT.Status = constant.Status_ON
}
if err := JsRedis.Redis_hset(constant.DB_Content, st.CT.ID, &st.CT); err != nil {
s.Forward("1", err.Error(), st)
return
}
//建立内容搜索索引
go creatContentSearchIndex(&st.CT)
go appendToGlobalContent(st.CT.ID)
if len(st.Tags) > 0 {
go Content2Tag(st.CT.ID, st.Tags)
}
TagLinkA(st.CT.ID, st.Tags)
// if erro := tage.TagLinkA(st.CT.ID, st.Tags); erro != nil {
// info := "Tage contect fail:" + erro.Error()
// JsLogger.Error(info)
// s.Forward("1", info, nil)
// return
// }
s.Forward("0", "success", st)
}
//查询内容
func QueryContent(s *JsHttp.Session) {
type info struct {
ID string //id
}
st := &info{}
if err := s.GetPara(st); err != nil {
s.Forward("1", err.Error(), nil)
return
}
data, err := Getcontent(st.ID)
if err != nil {
s.Forward("1", err.Error(), nil)
return
}
s.Forward("0", "success", data)
}
//查询多个内容
func QueryMoreContents(s *JsHttp.Session) {
type Info struct {
IDs []string ////产品id列表
}
st := &Info{}
if err := s.GetPara(st); err != nil {
info := "QueryMoreContents,GetPara:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if len(st.IDs) < 0 {
info := "QueryMoreContents param IDs is empty\n"
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
s.Forward("0", "success", getMoreContents(st.IDs))
}
//修改内容
func ModContent(s *JsHttp.Session) {
type Para struct {
CT XM_Contents //内容结构
Tags []string //标签列表
}
st := &Para{}
if err := s.GetPara(st); err != nil {
info := "ModContent,GetPara:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
data := &XM_Contents{}
if err := JsRedis.Redis_hget(constant.DB_Content, st.CT.ID, data); err != nil {
info := "ModContent Redis_get:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, data)
return
}
d, e := json.Marshal(st.CT)
if e != nil {
info := e.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if err := json.Unmarshal(d, data); err != nil {
info := err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if err := JsRedis.Redis_hset(constant.DB_Content, data.ID, data); err != nil {
info := err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
go changeContentTag(data.ID, st.Tags)
s.Forward("0", "success", data)
}
//数据库直接删除内容
func DelContentDB(s *JsHttp.Session) {
type Para struct {
ID string
}
st := &Para{}
if err := s.GetPara(st); err != nil {
s.Forward("1", err.Error(), nil)
return
}
if st.ID == "" {
info := "DelContentDB param ID is empty\n"
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if ok, e := JsRedis.Redis_hexists(constant.DB_Content, st.ID); e == nil && ok {
if err := JsRedis.Redis_hdel(constant.DB_Content, st.ID); err != nil {
info := "DelContentDB" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
}
go delFromGlobalContent(st.ID)
s.Forward("0", "success", nil)
}
//标记删除内容
func DelContentMark(s *JsHttp.Session) {
type Info struct {
ID string
}
st := &Info{}
if err := s.GetPara(st); err != nil {
info := "DelContentMark,GetPara:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if st.ID == "" {
info := "DelContentMark param ID is empty\n"
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
data := &XM_Contents{}
if err := JsRedis.Redis_hget(constant.DB_Content, st.ID, data); err != nil {
info := "DelContentMark,Redis_hset:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
data.DelTag = true
if err := JsRedis.Redis_hset(constant.DB_Content, st.ID, data); err != nil {
info := "DelContentMark,Redis_hset:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
go delFromGlobalContent(st.ID)
s.Forward("0", "success", data)
}
//上下架内容
func UpdownContent(s *JsHttp.Session) {
type Info struct {
ID string //id
IsUp bool //是否上架
}
st := &Info{}
if err := s.GetPara(st); err != nil {
info := "UpdownContent,GetPara:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if st.ID == "" {
info := "UpdownContent param ID is empty\n"
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
data := &XM_Contents{}
if err := JsRedis.Redis_hget(constant.DB_Content, st.ID, data); err != nil {
info := "UpdownContent,Redis_get:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
if st.IsUp {
data.Status = constant.Status_ON
} else {
data.Status = constant.Status_OFF
}
if err := JsRedis.Redis_hset(constant.DB_Content, st.ID, data); err != nil {
info := "UpdownContent,Redis_get:" + err.Error()
JsLogger.Error(info)
s.Forward("1", info, nil)
return
}
s.Forward("0", "success", data)
}
//查询单个内容
func Getcontent(id string) (*XM_Contents, error) {
data := &XM_Contents{}
return data, JsRedis.Redis_hget(constant.DB_Content, id, data)
}
//获取多个内容信息(摘要)
func getMoreContents(ids []string) []*JsContent.ContentsAbs {
data := []*JsContent.ContentsAbs{}
fmt.Printf("id = %v\n", ids)
for _, v := range ids {
retData := &JsContent.ContentsAbs{}
err := JsRedis.Redis_hget(constant.DB_Content, v, retData)
if err != nil {
JsLogger.Error(err.Error())
continue
}
data = append(data, retData)
}
return data
}
|
package commands
import (
"context"
"fmt"
"github.com/TRON-US/go-btfs/core/commands/cmdenv"
cmds "github.com/TRON-US/go-btfs-cmds"
coreiface "github.com/TRON-US/interface-go-btfs-core"
"github.com/TRON-US/interface-go-btfs-core/options"
"github.com/TRON-US/interface-go-btfs-core/path"
ipld "github.com/ipfs/go-ipld-format"
)
const (
rmForceOptionName = "force"
)
var RmCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Remove files or directories from a local btfs node.",
ShortDescription: `Removes all blocks under <hash> recursively from a local btfs node.`,
},
Arguments: []cmds.Argument{
cmds.StringArg("hash", true, true, "The hash(es) of the file(s)/directory(s) to be removed from the local btfs node.").EnableStdin(),
},
Options: []cmds.Option{
cmds.BoolOption(rmForceOptionName, "f", "Forcibly remove the object, even if there are constraints (such as host-stored file).").WithDefault(false),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
if err != nil {
return err
}
// do not perform online operations for local delete
api, err := cmdenv.GetApi(env, req, options.Api.Offline(true), options.Api.FetchBlocks(false))
if err != nil {
return err
}
force, _ := req.Options[rmForceOptionName].(bool)
var results stringList
for _, b := range req.Arguments {
// Make sure node exists
p := path.New(b)
node, err := api.ResolveNode(req.Context, p)
if err != nil {
return err
}
_, pinned, err := n.Pinning.IsPinned(node.Cid())
if err != nil {
return err
}
if pinned {
// Since we are removing a file, we need to set recursive flag to true
err = api.Pin().Rm(req.Context, p, options.Pin.RmRecursive(true), options.Pin.RmForce(force))
if err != nil {
return err
}
}
// Rm all child links
err = rmAllDags(req.Context, api, node, &results, map[string]bool{})
if err != nil {
return err
}
}
return cmds.EmitOnce(res, results)
},
Type: stringList{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
},
}
func rmAllDags(ctx context.Context, api coreiface.CoreAPI, node ipld.Node, res *stringList,
removed map[string]bool) error {
for _, nl := range node.Links() {
// Skipped just removed nodes
if _, ok := removed[nl.Cid.String()]; ok {
continue
}
// Resolve, recurse, then finally remove
rn, err := api.ResolveNode(ctx, path.IpfsPath(nl.Cid))
if err != nil {
res.Strings = append(res.Strings, fmt.Sprintf("Error resolving object %s", nl.Cid))
continue // continue with other nodes
}
if err := rmAllDags(ctx, api, rn, res, removed); err != nil {
continue // continue with other nodes
}
}
ncid := node.Cid()
if err := api.Dag().Remove(ctx, ncid); err != nil {
res.Strings = append(res.Strings, fmt.Sprintf("Error removing object %s", ncid))
return err
} else {
res.Strings = append(res.Strings, fmt.Sprintf("Removed %s", ncid))
removed[ncid.String()] = true
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.