text:
// Copyright (c) 2020 Tailscale Inc & 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 filter contains a stateful packet filter.
package filter

import (
	"fmt"
	"net"
	"sync"
	"time"

	"github.com/golang/groupcache/lru"
	"golang.org/x/time/rate"
	"tailscale.com/tailcfg"
	"tailscale.com/types/logger"
	"tailscale.com/wgengine/packet"
)

type filterState struct {
	mu  sync.Mutex
	lru *lru.Cache // of tuple
}

// Filter is a stateful packet filter.
type Filter struct {
	logf logger.Logf
	// localNets is the list of IP prefixes that we know to be "local"
	// to this node. All packets coming in over tailscale must have a
	// destination within localNets, regardless of the policy filter
	// below. A nil localNets rejects all incoming traffic.
	localNets []Net
	// matches is a list of match->action rules applied to all packets
	// arriving over tailscale tunnels. Matches are checked in order,
	// and processing stops at the first matching rule. The default
	// policy if no rules match is to drop the packet.
	matches Matches
	// state is the connection tracking state attached to this
	// filter. It is used to allow incoming traffic that is a response
	// to an outbound connection that this node made, even if those
	// incoming packets don't get accepted by matches above.
	state *filterState
}

// Response is a verdict: either a Drop, Accept, or noVerdict skip to
// continue processing.
type Response int

const (
	Drop Response = iota
	Accept
	noVerdict // Returned from subfilters to continue processing.
)

func (r Response) String() string {
	switch r {
	case Drop:
		return "Drop"
	case Accept:
		return "Accept"
	case noVerdict:
		return "noVerdict"
	default:
		return "???"
	}
}

// RunFlags controls the filter's debug log verbosity at runtime.
type RunFlags int

const (
	LogDrops RunFlags = 1 << iota
	LogAccepts
	HexdumpDrops
	HexdumpAccepts
)

type tuple struct {
	SrcIP   packet.IP
	DstIP   packet.IP
	SrcPort uint16
	DstPort uint16
}

const lruMax = 512 // max entries in UDP LRU cache

// MatchAllowAll matches all packets.
var MatchAllowAll = Matches{
	Match{[]NetPortRange{NetPortRangeAny}, []Net{NetAny}},
}

// NewAllowAll returns a packet filter that accepts everything to and
// from localNets.
func NewAllowAll(localNets []Net, logf logger.Logf) *Filter {
	return New(MatchAllowAll, localNets, nil, logf)
}

// NewAllowNone returns a packet filter that rejects everything.
func NewAllowNone(logf logger.Logf) *Filter {
	return New(nil, nil, nil, logf)
}

// New creates a new packet filter. The filter enforces that incoming
// packets must be destined to an IP in localNets, and must be allowed
// by matches. If shareStateWith is non-nil, the returned filter
// shares state with the previous one, to enable rules to be changed
// at runtime without breaking existing flows.
func New(matches Matches, localNets []Net, shareStateWith *Filter, logf logger.Logf) *Filter {
	var state *filterState
	if shareStateWith != nil {
		state = shareStateWith.state
	} else {
		state = &filterState{
			lru: lru.New(lruMax),
		}
	}
	f := &Filter{
		logf:      logf,
		matches:   matches,
		localNets: localNets,
		state:     state,
	}
	return f
}

func maybeHexdump(flag RunFlags, b []byte) string {
	if flag == 0 {
		return ""
	}
	return packet.Hexdump(b) + "\n"
}

// MatchesFromFilterRules parse a number of wire-format FilterRule values into
// the Matches format.
// If an error is returned, the Matches result is still valid, containing the rules that
// were successfully converted.
func MatchesFromFilterRules(pf []tailcfg.FilterRule) (Matches, error) {
	mm := make([]Match, 0, len(pf))
	var erracc error

	for _, r := range pf {
		m := Match{}

		for i, s := range r.SrcIPs {
			bits := 32
			if len(r.SrcBits) > i {
				bits = r.SrcBits[i]
			}
			net, err := parseIP(s, bits)
			if err != nil && erracc == nil {
				erracc = err
				continue
			}
			m.Srcs = append(m.Srcs, net)
		}

		for _, d := range r.DstPorts {
			bits := 32
			if d.Bits != nil {
				bits = *d.Bits
			}
			net, err := parseIP(d.IP, bits)
			if err != nil && erracc == nil {
				erracc = err
				continue
			}
			m.Dsts = append(m.Dsts, NetPortRange{
				Net: net,
				Ports: PortRange{
					First: d.Ports.First,
					Last:  d.Ports.Last,
				},
			})
		}

		mm = append(mm, m)
	}
	return mm, erracc
}

func parseIP(host string, defaultBits int) (Net, error) {
	ip := net.ParseIP(host)
	if ip != nil && ip.IsUnspecified() {
		// For clarity, reject 0.0.0.0 as an input
		return NetNone, fmt.Errorf("ports=%#v: to allow all IP addresses, use *:port, not 0.0.0.0:port", host)
	} else if ip == nil && host == "*" {
		// User explicitly requested wildcard dst ip
		return NetAny, nil
	} else {
		if ip != nil {
			ip = ip.To4()
		}
		if ip == nil || len(ip) != 4 {
			return NetNone, fmt.Errorf("ports=%#v: invalid IPv4 address", host)
		}
		if len(ip) == 4 && (defaultBits < 0 || defaultBits > 32) {
			return NetNone, fmt.Errorf("invalid CIDR size %d for host %q", defaultBits, host)
		}
		return Net{
			IP:   NewIP(ip),
			Mask: Netmask(defaultBits),
		}, nil
	}
}

// TODO(apenwarr): use a bigger bucket for specifically TCP SYN accept logging?
//   Logging is a quick way to record every newly opened TCP connection, but
//   we have to be cautious about flooding the logs vs letting people use
//   flood protection to hide their traffic. We could use a rate limiter in
//   the actual *filter* for SYN accepts, perhaps.
var acceptBucket = rate.NewLimiter(rate.Every(10*time.Second), 3)
var dropBucket = rate.NewLimiter(rate.Every(5*time.Second), 10)

func (f *Filter) logRateLimit(runflags RunFlags, q *packet.ParsedPacket, dir direction, r Response, why string) {
	var verdict string

	if r == Drop && omitDropLogging(q, dir) {
		return
	}

	if r == Drop && (runflags&LogDrops) != 0 && dropBucket.Allow() {
		verdict = "Drop"
		runflags &= HexdumpDrops
	} else if r == Accept && (runflags&LogAccepts) != 0 && acceptBucket.Allow() {
		verdict = "Accept"
		runflags &= HexdumpAccepts
	}

	// Note: it is crucial that q.String() be called only if {accept,drop}Bucket.Allow() passes,
	// since it causes an allocation.
	if verdict != "" {
		b := q.Buffer()
		f.logf("%s: %s %d %s\n%s", verdict, q.String(), len(b), why, maybeHexdump(runflags, b))
	}
}

// RunIn determines whether this node is allowed to receive q from a Tailscale peer.
func (f *Filter) RunIn(q *packet.ParsedPacket, rf RunFlags) Response {
	dir := in
	r := f.pre(q, rf, dir)
	if r == Accept || r == Drop {
		// already logged
		return r
	}

	r, why := f.runIn(q)
	f.logRateLimit(rf, q, dir, r, why)
	return r
}

// RunOut determines whether this node is allowed to send q to a Tailscale peer.
func (f *Filter) RunOut(q *packet.ParsedPacket, rf RunFlags) Response {
	dir := out
	r := f.pre(q, rf, dir)
	if r == Drop || r == Accept {
		// already logged
		return r
	}
	r, why := f.runOut(q)
	f.logRateLimit(rf, q, dir, r, why)
	return r
}

func (f *Filter) runIn(q *packet.ParsedPacket) (r Response, why string) {
	// A compromised peer could try to send us packets for
	// destinations we didn't explicitly advertise. This check is to
	// prevent that.
	if !ipInList(q.DstIP, f.localNets) {
		return Drop, "destination not allowed"
	}

	if q.IPVersion == 6 {
		// TODO: support IPv6.
		return Drop, "no rules matched"
	}

	switch q.IPProto {
	case packet.ICMP:
		if q.IsEchoResponse() || q.IsError() {
			// ICMP responses are allowed.
			// TODO(apenwarr): consider using conntrack state.
			//  We could choose to reject all packets that aren't
			//  related to an existing ICMP-Echo, TCP, or UDP
			//  session.
			return Accept, "icmp response ok"
		} else if matchIPWithoutPorts(f.matches, q) {
			// If any port is open to an IP, allow ICMP to it.
			return Accept, "icmp ok"
		}
	case packet.TCP:
		// For TCP, we want to allow *outgoing* connections,
		// which means we want to allow return packets on those
		// connections. To make this restriction work, we need to
		// allow non-SYN packets (continuation of an existing session)
		// to arrive. This should be okay since a new incoming session
		// can't be initiated without first sending a SYN.
		// It happens to also be much faster.
		// TODO(apenwarr): Skip the rest of decoding in this path?
		if q.IPProto == packet.TCP && !q.IsTCPSyn() {
			return Accept, "tcp non-syn"
		}
		if matchIPPorts(f.matches, q) {
			return Accept, "tcp ok"
		}
	case packet.UDP:
		t := tuple{q.SrcIP, q.DstIP, q.SrcPort, q.DstPort}

		f.state.mu.Lock()
		_, ok := f.state.lru.Get(t)
		f.state.mu.Unlock()

		if ok {
			return Accept, "udp cached"
		}
		if matchIPPorts(f.matches, q) {
			return Accept, "udp ok"
		}
	default:
		return Drop, "Unknown proto"
	}
	return Drop, "no rules matched"
}

func (f *Filter) runOut(q *packet.ParsedPacket) (r Response, why string) {
	if q.IPProto == packet.UDP {
		t := tuple{q.DstIP, q.SrcIP, q.DstPort, q.SrcPort}
		var ti interface{} = t // allocate once, rather than twice inside mutex

		f.state.mu.Lock()
		f.state.lru.Add(ti, ti)
		f.state.mu.Unlock()
	}
	return Accept, "ok out"
}

// direction is whether a packet was flowing in to this machine, or flowing out.
type direction int

const (
	in direction = iota
	out
)

func (d direction) String() string {
	switch d {
	case in:
		return "in"
	case out:
		return "out"
	default:
		return fmt.Sprintf("[??dir=%d]", int(d))
	}
}

func (f *Filter) pre(q *packet.ParsedPacket, rf RunFlags, dir direction) Response {
	if len(q.Buffer()) == 0 {
		// wireguard keepalive packet, always permit.
		return Accept
	}
	if len(q.Buffer()) < 20 {
		f.logRateLimit(rf, q, dir, Drop, "too short")
		return Drop
	}

	if q.IPVersion == 6 {
		f.logRateLimit(rf, q, dir, Drop, "ipv6")
		return Drop
	}
	switch q.IPProto {
	case packet.Unknown:
		// Unknown packets are dangerous; always drop them.
		f.logRateLimit(rf, q, dir, Drop, "unknown")
		return Drop
	case packet.Fragment:
		// Fragments after the first always need to be passed through.
		// Very small fragments are considered Junk by ParsedPacket.
		f.logRateLimit(rf, q, dir, Accept, "fragment")
		return Accept
	}

	return noVerdict
}

const (
	// ipv6AllRoutersLinkLocal is ff02::2 (All link-local routers)
	ipv6AllRoutersLinkLocal = "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02"
	// ipv6AllMLDv2CapableRouters is ff02::16 (All MLDv2-capable routers)
	ipv6AllMLDv2CapableRouters = "\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16"
)

// omitDropLogging reports whether packet p, which has already been
// deemded a packet to Drop, should bypass the [rate-limited] logging.
// We don't want to log scary & spammy reject warnings for packets that
// are totally normal, like IPv6 route announcements.
func omitDropLogging(p *packet.ParsedPacket, dir direction) bool {
	b := p.Buffer()
	switch dir {
	case out:
		switch p.IPVersion {
		case 4:
			// ParsedPacket.Decode zeros out ParsedPacket.IPProtocol for protocols
			// it doesn't know about, so parse it out ourselves if needed.
			ipProto := p.IPProto
			if ipProto == 0 && len(b) > 8 {
				ipProto = packet.IPProto(b[9])
			}
			// Omit logging about outgoing IGMP.
			if ipProto == packet.IGMP {
				return true
			}
		case 6:
			if len(b) < 40 {
				return false
			}
			src, dst := b[8:8+16], b[24:24+16]
			// Omit logging for outgoing IPv6 ICMP-v6 queries to ff02::2,
			// as sent by the OS, looking for routers.
			if p.IPProto == packet.ICMPv6 {
				if isLinkLocalV6(src) && string(dst) == ipv6AllRoutersLinkLocal {
					return true
				}
			}
			if string(dst) == ipv6AllMLDv2CapableRouters {
				return true
			}
			// Actually, just catch all multicast.
			if dst[0] == 0xff {
				return true
			}
		}
	}
	return false
}

// isLinkLocalV6 reports whether src is in fe80::/10.
func isLinkLocalV6(src []byte) bool {
	return len(src) == 16 && src[0] == 0xfe && src[1]>>6 == 0x80>>6
}


text:
@inproceedings{cpa_github,
    Author = {Jamie Thompson},
    Title = {Custom Pod Autoscaler GitHub},
    Year = 2020,
    Url = "https://github.com/jthomperoo/custom-pod-autoscaler"
}

@inproceedings{cpao_github,
    Author = {Jamie Thompson},
    Title = {Custom Pod Autoscaler Operator GitHub},
    Year = 2020,
    Url = "https://github.com/jthomperoo/custom-pod-autoscaler-operator"
}

@inproceedings{semantic_versioning,
    Author = {Tom Preston-Werner},
    Title = {Semantic Versioning 2.0.0},
    Year = 2013,
    Url = "https://semver.org/"
}

@inproceedings{keep_a_changelog,
    Author = {Olivier Lacan, Tyler Fortune},
    Title = {keep a changelog 1.1.0},
    Year = 2019,
    Url = "https://keepachangelog.com/en/1.1.0/"
}
@inproceedings{golang_faq,
    Author = {"golang.org"},
    Title = {Frequently Asked Questions (FAQ)},
    Year = 2019,
    Url = "https://golang.org/doc/faq"
}

@inproceedings{kubernetes_io_hpa,
    Author = {"Cloud Native Computing Foundation"},
    Title = "Horizontal Pod Autoscaler",
    Year = 2020,
    Url =
    "https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale"
}

@inproceedings{sysdig_custom_metrics,
    Author = {Mateo Burillo},
    Title = "Kubernetes pod autoscaler using custom metrics",
    Year = 2019,
    Url = "https://sysdig.com/blog/kubernetes-autoscaler/"
}

@inproceedings{agones_overview,
    Author = {"agones.dev"},
    Title = "Agones - Overview",
    Year = 2020,
    Url = "https://agones.dev/site/docs/overview/"
}

@inproceedings{agones_autoscaler_specification,
    Author = {"agones.dev"},
    Title = "Agones - Fleet Autoscaler Specification",
    Year = 2020,
    Url = "https://agones.dev/site/docs/reference/fleetautoscaler/"
}

@inproceedings{k8s_specific_downscale,
    Author = {Robert Bailey},
    Title = "Scale down a deployment by removing specific pods",
    Year = 2020,
    Url = "https://github.com/kubernetes/kubernetes/issues/45509"
}

@inproceedings{k8s_main_page,
    Author = {"kubernetes.io"},
    Title = "Production-Grade Container Orchestration - Kubernetes",
    Year = 2020,
    Url = "https://kubernetes.io/"
}

@inproceedings{docker_container,
    Author = {"docker.com"},
    Title = "What is a Container?",
    Year = 2020,
    Url = "https://www.docker.com/resources/what-container"
}

@inproceedings{k8s_pod_concept,
    Author = {"kubernetes.io"},
    Title = "Pods",
    Year = 2020,
    Url = "https://kubernetes.io/docs/concepts/workloads/pods/pod/"
}

@inproceedings{k8s_node_concept,
    Author = {"kubernetes.io"},
    Title = "Nodes",
    Year = 2020,
    Url = "https://kubernetes.io/docs/concepts/architecture/nodes/"
}

@inproceedings{container_adoption_survey,
    Author = {"Portworx and Aqua Security"},
    Title = "2019 Container Adoption Survey",
    Year = 2019,
    Url = "https://portworx.com/wp-content/uploads/2019/05/2019-container-adoption-survey.pdf"
}

@inproceedings{operator_framework_issue,
    Author = {Jamie Thompson},
    Title = "Use imported struct in OpenAPI definition",
    Year = 2019,
    Url = "https://github.com/operator-framework/operator-sdk/issues/2193"
}

license_type: permissive

branch_name: refs/heads/master

extension: bib


text:
#include <iostream>
#include <memory>
#include <functional>
#include <string>

#include <satori/satori.hpp>
#include <uv.h>

int main(int argc, const char** argv) {

  using namespace satori;

  // Take a path from the command-line arguments
  if (!argv[1]) {
    std::cerr << "Usage: file_path " << std::endl;
    return 1;
  }

  auto filePath = std::string(argv[1]);

  // Create a Satori event loop
  auto satori = Satori();

  auto const onOpen = [=](ssize_t const file) mutable {

    auto const onRead = [=](int error, StringView const buffer) mutable {
      if (error < 0) {
        std::cerr << errorName(error) << " " << errorMessage(error) << std::endl;
        exit(1);
        return;
      }
      std::cout << buffer;
    };

    auto const onReadEnd = [=]() mutable {
      std::cout << std::flush;
      satori.closeFile(file);
    };

    satori.readFile(file, onRead, onReadEnd);
  };

  satori.openFile(filePath, O_RDONLY, S_IRUSR, onOpen);

  // Start the loop
  satori.run();

  return 0;
}

license: MIT

repository: LoopPerfect/satori

repo_name: LoopPerfect/satori

gha_license_id: MIT

extension: cpp


text:
// Copyright 2020 Michael Li <alimy@gility.net>. All rights reserved.
// Use of this source code is governed by Apache License 2.0 that
// can be found in the LICENSE file.

package v1

import (
	. "github.com/alimy/mir/v2"
	. "github.com/alimy/mir/v2/engine"
)

func init() {
	AddEntry(new(Registry))
}

// Registry crates registry api define
type Registry struct {
	Group           Group  `mir:"/api/v1"`
	Register        Post   `mir:"account/register"`
	Login           Post   `mir:"account/login"`
	TokensInfo      Post   `mir:"account/tokens"`
	GenerateTokens  Put    `mir:"account/tokens"`
	RevokeTokens    Delete `mir:"account/tokens"`
	TokenByName     Get    `mir:"account/tokens/{name}"`
	Categories      Get    `mir:"categories"`
	SearchCrates    Get    `mir:"crates"`
	PublishCrates   Put    `mir:"crates/new"`
	SuggestCrates   Get    `mir:"crates/suggest"`
	CrateInfo       Get    `mir:"crates/{name}"`
	CrateOwnersInfo Get    `mir:"crates/{name}/owners"`
	PutCrateOwners  Put    `mir:"crates/{name}/owners"`
	DelCrateOwners  Delete `mir:"crates/{name}/owners"`
	YankCrate       Delete `mir:"crates/{name}/{version}/yank"`
	UnyankCrate     Put    `mir:"crates/{name}/{version}/unyank"`
	DownloadCrate   Get    `mir:"crates/{name}/{version}/download"`
}

repository: alimy/hori

repo_name: alimy/hori

extension: go


text:
package cronsun

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"os/exec"
	"os/user"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"syscall"
	"time"

	client "github.com/coreos/etcd/clientv3"

	"github.com/sunny5156/cronsun/conf"
	"github.com/sunny5156/cronsun/log"
	"github.com/sunny5156/cronsun/node/cron"
	"github.com/sunny5156/cronsun/utils"
)

const (
	DefaultJobGroup = "default"
)

const (
	KindCommon   = iota
	KindAlone    // 任何时间段只允许单机执行
	KindInterval // 一个任务执行间隔内允许执行一次
)

// 需要执行的 cron cmd 命令
// 注册到 /cronsun/cmd/groupName/<id>
type Job struct {
	ID      string     `json:"id"`
	Name    string     `json:"name"`
	Group   string     `json:"group"`
	Command string     `json:"cmd"`
	User    string     `json:"user"`
	Rules   []*JobRule `json:"rules"`
	Pause   bool       `json:"pause"`   // 可手工控制的状态
	Timeout int64      `json:"timeout"` // 任务执行时间超时设置，大于 0 时有效
	// 设置任务在单个节点上可以同时允许多少个
	// 针对两次任务执行间隔比任务执行时间要长的任务启用
	Parallels int64 `json:"parallels"`
	// 执行任务失败重试次数
	// 默认为 0，不重试
	Retry int `json:"retry"`
	// 执行任务失败重试时间间隔
	// 单位秒，如果不大于 0 则马上重试
	Interval int `json:"interval"`
	// 任务类型
	// 0: 普通任务
	// 1: 单机任务
	// 如果为单机任务，node 加载任务的时候 Parallels 设置 1
	Kind int `json:"kind"`
	// 平均执行时间，单位 ms
	AvgTime int64 `json:"avg_time"`
	// 执行失败发送通知
	FailNotify bool `json:"fail_notify"`
	// 发送通知地址
	To []string `json:"to"`
	// 单独对任务指定日志清除时间
	LogExpiration int `json:"log_expiration"`

	// 执行任务的结点，用于记录 job log
	runOn    string
	hostname string
	ip       string
	// 用于存储分隔后的任务
	cmd []string
	// 控制同时执行任务数
	Count *int64 `json:"-"`
}

type JobRule struct {
	ID             string   `json:"id"`
	Timer          string   `json:"timer"`
	GroupIDs       []string `json:"gids"`
	NodeIDs        []string `json:"nids"`
	ExcludeNodeIDs []string `json:"exclude_nids"`

	Schedule cron.Schedule `json:"-"`
}

// 任务锁
type locker struct {
	kind  int
	ttl   int64
	lID   client.LeaseID
	timer *time.Timer
	done  chan struct{}
}

func (l *locker) keepAlive() {
	duration := time.Duration(l.ttl)*time.Second - 500*time.Millisecond
	l.timer = time.NewTimer(duration)
	for {
		select {
		case <-l.done:
			return
		case <-l.timer.C:
			_, err := DefalutClient.KeepAliveOnce(l.lID)
			if err != nil {
				log.Warnf("lock keep alive err: %s", err.Error())
				return
			}
			l.timer.Reset(duration)
		}
	}
}

func (l *locker) unlock() {
	if l.kind != KindAlone {
		return
	}

	close(l.done)
	l.timer.Stop()
	if _, err := DefalutClient.Revoke(l.lID); err != nil {
		log.Warnf("unlock revoke err: %s", err.Error())
	}
}

type Cmd struct {
	*Job
	*JobRule
}

func (c *Cmd) GetID() string {
	return c.Job.ID + c.JobRule.ID
}

func (c *Cmd) Run() {
	// 同时执行任务数限制
	if c.Job.limit() {
		return
	}
	defer c.Job.unlimit()

	if c.Job.Kind != KindCommon {
		lk := c.lock()
		if lk == nil {
			return
		}
		defer lk.unlock()
	}

	if c.Job.Retry <= 0 {
		c.Job.Run()
		return
	}

	for i := 0; i < c.Job.Retry; i++ {
		if c.Job.Run() {
			return
		}

		if c.Job.Interval > 0 {
			time.Sleep(time.Duration(c.Job.Interval) * time.Second)
		}
	}
}

func (j *Job) limit() bool {
	if j.Parallels == 0 {
		return false
	}

	count := atomic.AddInt64(j.Count, 1)
	if j.Parallels < count {
		atomic.AddInt64(j.Count, -1)
		j.Fail(time.Now(), fmt.Sprintf("job[%s] running on[%s] running:[%d]", j.Key(), j.runOn, count))
		return true
	}

	return false
}

func (j *Job) unlimit() {
	if j.Parallels == 0 {
		return
	}
	atomic.AddInt64(j.Count, -1)
}

func (j *Job) Init(nodeID, hostname, ip string) {
	var c int64
	j.Count, j.runOn, j.hostname, j.ip = &c, nodeID, hostname, ip
}

func (c *Cmd) lockTtl() int64 {
	now := time.Now()
	prev := c.JobRule.Schedule.Next(now)
	ttl := int64(c.JobRule.Schedule.Next(prev).Sub(prev) / time.Second)
	if ttl == 0 {
		return 0
	}

	if c.Job.Kind == KindInterval {
		ttl -= 2
		if ttl > conf.Config.LockTtl {
			ttl = conf.Config.LockTtl
		}
		if ttl < 1 {
			ttl = 1
		}
		return ttl
	}

	cost := c.Job.AvgTime / 1e3
	if c.Job.AvgTime/1e3-cost*1e3 > 0 {
		cost += 1
	}
	// 如果执行间隔时间不大于执行时间，把过期时间设置为执行时间的下限-1
	// 以便下次执行的时候，能获取到 lock
	if ttl >= cost {
		ttl -= cost
	}

	if ttl > conf.Config.LockTtl {
		ttl = conf.Config.LockTtl
	}

	// 支持的最小时间间隔 2s
	if ttl < 2 {
		ttl = 2
	}

	return ttl
}

func (c *Cmd) newLock() *locker {
	return &locker{
		kind: c.Job.Kind,
		ttl:  c.lockTtl(),
		done: make(chan struct{}),
	}
}

func (c *Cmd) lock() *locker {
	lk := c.newLock()
	// 非法的 rule
	if lk.ttl == 0 {
		return nil
	}

	resp, err := DefalutClient.Grant(lk.ttl)
	if err != nil {
		log.Infof("job[%s] didn't get a lock, err: %s", c.Job.Key(), err.Error())
		return nil
	}

	ok, err := DefalutClient.GetLock(c.Job.ID, resp.ID)
	if err != nil {
		log.Infof("job[%s] didn't get a lock, err: %s", c.Job.Key(), err.Error())
		return nil
	}

	if !ok {
		return nil
	}

	lk.lID = resp.ID
	if lk.kind == KindAlone {
		go lk.keepAlive()
	}
	return lk
}

// 优先取结点里的值，更新 group 时可用 gid 判断是否对 job 进行处理
func (rule *JobRule) included(nid string, gs map[string]*Group) bool {
	for i, count := 0, len(rule.NodeIDs); i < count; i++ {
		if nid == rule.NodeIDs[i] {
			return true
		}
	}

	for _, gid := range rule.GroupIDs {
		if g, ok := gs[gid]; ok && g.Included(nid) {
			return true
		}
	}

	return false
}

// 验证 timer 字段
func (rule *JobRule) Valid() error {
	// 注意 interface nil 的比较
	if rule.Schedule != nil {
		return nil
	}

	if len(rule.Timer) == 0 {
		return ErrNilRule
	}

	sch, err := cron.Parse(rule.Timer)
	if err != nil {
		return fmt.Errorf("invalid JobRule[%s], parse err: %s", rule.Timer, err.Error())
	}

	rule.Schedule = sch
	return nil
}

// Note: this function did't check the job.
func GetJob(group, id string) (job *Job, err error) {
	job, _, err = GetJobAndRev(group, id)
	return
}

func GetJobAndRev(group, id string) (job *Job, rev int64, err error) {
	resp, err := DefalutClient.Get(JobKey(group, id))
	if err != nil {
		return
	}

	if resp.Count == 0 {
		err = ErrNotFound
		return
	}

	rev = resp.Kvs[0].ModRevision
	if err = json.Unmarshal(resp.Kvs[0].Value, &job); err != nil {
		return
	}

	job.splitCmd()
	return
}

func DeleteJob(group, id string) (resp *client.DeleteResponse, err error) {
	return DefalutClient.Delete(JobKey(group, id))
}

func GetJobs() (jobs map[string]*Job, err error) {
	resp, err := DefalutClient.Get(conf.Config.Cmd, client.WithPrefix())
	if err != nil {
		return
	}

	count := len(resp.Kvs)
	jobs = make(map[string]*Job, count)
	if count == 0 {
		return
	}

	for _, j := range resp.Kvs {
		job := new(Job)
		if e := json.Unmarshal(j.Value, job); e != nil {
			log.Warnf("job[%s] umarshal err: %s", string(j.Key), e.Error())
			continue
		}

		if err := job.Valid(); err != nil {
			log.Warnf("job[%s] is invalid: %s", string(j.Key), err.Error())
			continue
		}

		job.alone()
		jobs[job.ID] = job
	}
	return
}

func WatchJobs() client.WatchChan {
	return DefalutClient.Watch(conf.Config.Cmd, client.WithPrefix())
}

func GetJobFromKv(key, value []byte) (job *Job, err error) {
	job = new(Job)
	if err = json.Unmarshal(value, job); err != nil {
		err = fmt.Errorf("job[%s] umarshal err: %s", string(key), err.Error())
		return
	}

	err = job.Valid()
	job.alone()
	return
}

func (j *Job) alone() {
	if j.Kind == KindAlone {
		j.Parallels = 1
	}
}

func (j *Job) splitCmd() {
	ps := strings.SplitN(j.Command, " ", 2)
	if len(ps) == 1 {
		j.cmd = ps
		return
	}

	j.cmd = make([]string, 0, 2)
	j.cmd = append(j.cmd, ps[0])
	j.cmd = append(j.cmd, utils.ParseCmdArguments(ps[1])...)
}

func (j *Job) String() string {
	data, err := json.Marshal(j)
	if err != nil {
		return err.Error()
	}
	return string(data)
}

// Run 执行任务
func (j *Job) Run() bool {
	var (
		cmd         *exec.Cmd
		proc        *Process
		sysProcAttr *syscall.SysProcAttr
	)

	t := time.Now()
	// 用户权限控制
	if len(j.User) > 0 {
		u, err := user.Lookup(j.User)
		if err != nil {
			j.Fail(t, err.Error())
			return false
		}

		uid, err := strconv.Atoi(u.Uid)
		if err != nil {
			j.Fail(t, "not support run with user on windows")
			return false
		}
		if uid != _Uid {
			gid, _ := strconv.Atoi(u.Gid)
			sysProcAttr = &syscall.SysProcAttr{
				Credential: &syscall.Credential{
					Uid: uint32(uid),
					Gid: uint32(gid),
				},
			}
		}
	}

	// 超时控制
	if j.Timeout > 0 {
		ctx, cancel := context.WithTimeout(context.Background(), time.Duration(j.Timeout)*time.Second)
		defer cancel()
		cmd = exec.CommandContext(ctx, j.cmd[0], j.cmd[1:]...)
	} else {
		cmd = exec.Command(j.cmd[0], j.cmd[1:]...)
	}
	cmd.SysProcAttr = sysProcAttr
	var b bytes.Buffer
	cmd.Stdout = &b
	cmd.Stderr = &b
	if err := cmd.Start(); err != nil {
		j.Fail(t, fmt.Sprintf("%s\n%s", b.String(), err.Error()))
		return false
	}

	proc = &Process{
		ID:     strconv.Itoa(cmd.Process.Pid),
		JobID:  j.ID,
		Group:  j.Group,
		NodeID: j.runOn,
		Time:   t,
	}
	proc.Start()
	defer proc.Stop()

	if err := cmd.Wait(); err != nil {
		j.Fail(t, fmt.Sprintf("%s\n%s", b.String(), err.Error()))
		return false
	}

	j.Success(t, b.String())
	return true
}

func (j *Job) RunWithRecovery() {
	defer func() {
		if r := recover(); r != nil {
			const size = 64 << 10
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			log.Warnf("panic running job: %v\n%s", r, buf)
		}
	}()
	j.Run()
}

// 从 etcd 的 key 中取 id
func GetIDFromKey(key string) string {
	index := strings.LastIndex(key, "/")
	if index < 0 {
		return ""
	}

	return key[index+1:]
}

func JobKey(group, id string) string {
	return conf.Config.Cmd + group + "/" + id
}

func (j *Job) Key() string {
	return JobKey(j.Group, j.ID)
}

func (j *Job) Check() error {
	j.ID = strings.TrimSpace(j.ID)
	if !IsValidAsKeyPath(j.ID) {
		return ErrIllegalJobId
	}

	j.Name = strings.TrimSpace(j.Name)
	if len(j.Name) == 0 {
		return ErrEmptyJobName
	}

	j.Group = strings.TrimSpace(j.Group)
	if len(j.Group) == 0 {
		j.Group = DefaultJobGroup
	}

	if !IsValidAsKeyPath(j.Group) {
		return ErrIllegalJobGroupName
	}

	if j.LogExpiration < 0 {
		j.LogExpiration = 0
	}

	j.User = strings.TrimSpace(j.User)

	for i := range j.Rules {
		id := strings.TrimSpace(j.Rules[i].ID)
		if id == "" || strings.HasPrefix(id, "NEW") {
			j.Rules[i].ID = NextID()
		}
	}

	// 不修改 Command 的内容，简单判断是否为空
	if len(strings.TrimSpace(j.Command)) == 0 {
		return ErrEmptyJobCommand
	}

	return j.Valid()
}

// 执行结果写入 mongoDB
func (j *Job) Success(t time.Time, out string) {
	CreateJobLog(j, t, out, true)
}

func (j *Job) Fail(t time.Time, msg string) {
	j.Notify(t, msg)
	CreateJobLog(j, t, msg, false)
}

func (j *Job) Notify(t time.Time, msg string) {
	if !conf.Config.Mail.Enable || !j.FailNotify {
		return
	}

	ts := t.Format(time.RFC3339)
	body := "Job: " + j.Key() + "\n" +
		"Job name: " + j.Name + "\n" +
		"Job cmd: " + j.Command + "\n" +
		"Node: " + j.hostname + "|" + j.ip + "[" + j.runOn + "]\n" +
		"Time: " + ts + "\n" +
		"Error: " + msg

	m := Message{
		Subject: "[Cronsun] node[" + j.hostname + "|" + j.ip + "] job[" + j.ShortName() + "] time[" + ts + "] exec failed",
		Body:    body,
		To:      j.To,
	}

	data, err := json.Marshal(m)
	if err != nil {
		log.Warnf("job[%s] send notice fail, err: %s", j.Key(), err.Error())
		return
	}

	_, err = DefalutClient.Put(conf.Config.Noticer+"/"+j.runOn, string(data))
	if err != nil {
		log.Warnf("job[%s] send notice fail, err: %s", j.Key(), err.Error())
		return
	}
}

func (j *Job) Avg(t, et time.Time) {
	execTime := int64(et.Sub(t) / time.Millisecond)
	if j.AvgTime == 0 {
		j.AvgTime = execTime
		return
	}

	j.AvgTime = (j.AvgTime + execTime) / 2
}

func (j *Job) Cmds(nid string, gs map[string]*Group) (cmds map[string]*Cmd) {
	cmds = make(map[string]*Cmd)
	if j.Pause {
		return
	}

LOOP_TIMER_CMD:
	for _, r := range j.Rules {
		for _, id := range r.ExcludeNodeIDs {
			if nid == id {
				// 在当前定时器规则中，任务不会在该节点执行（节点被排除）
				// 但是任务可以在其它定时器中，在该节点被执行
				// 比如，一个定时器设置在凌晨 1 点执行，但是此时不想在这个节点执行，然后，
				// 同时又设置一个定时器在凌晨 2 点执行，这次这个任务由于某些原因，必须在当前节点执行
				// 下面的 LOOP_TIMER 标签，原因同上
				continue LOOP_TIMER_CMD
			}
		}

		if r.included(nid, gs) {
			cmd := &Cmd{
				Job:     j,
				JobRule: r,
			}
			cmds[cmd.GetID()] = cmd
		}
	}

	return
}

func (j Job) IsRunOn(nid string, gs map[string]*Group) bool {
LOOP_TIMER:
	for _, r := range j.Rules {
		for _, id := range r.ExcludeNodeIDs {
			if nid == id {
				continue LOOP_TIMER
			}
		}

		if r.included(nid, gs) {
			return true
		}
	}

	return false
}

// 安全选项验证
func (j *Job) Valid() error {
	if len(j.cmd) == 0 {
		j.splitCmd()
	}

	if err := j.ValidRules(); err != nil {
		return err
	}

	security := conf.Config.Security
	if !security.Open {
		return nil
	}

	if !j.validUser() {
		return ErrSecurityInvalidUser
	}

	if !j.validCmd() {
		return ErrSecurityInvalidCmd
	}

	return nil
}

func (j *Job) validUser() bool {
	if len(conf.Config.Security.Users) == 0 {
		return true
	}

	for _, u := range conf.Config.Security.Users {
		if j.User == u {
			return true
		}
	}
	return false
}

func (j *Job) validCmd() bool {
	if len(conf.Config.Security.Ext) == 0 {
		return true
	}
	for _, ext := range conf.Config.Security.Ext {
		if strings.HasSuffix(j.cmd[0], ext) {
			return true
		}
	}
	return false
}

func (j *Job) ValidRules() error {
	for _, r := range j.Rules {
		if err := r.Valid(); err != nil {
			return err
		}
	}
	return nil
}

func (j *Job) ShortName() string {
	if len(j.Name) <= 10 {
		return j.Name
	}

	names := []rune(j.Name)
	if len(names) <= 10 {
		return j.Name
	}

	return string(names[:10]) + "..."
}


text:
/*******************************************************************************
 * Copyright 2019 VMware 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 interval

import (
	"reflect"
	"testing"

	intervalErrors "github.com/edgexfoundry/edgex-go/internal/support/scheduler/errors"
	"github.com/edgexfoundry/edgex-go/internal/support/scheduler/operators/interval/mocks"
	contract "github.com/edgexfoundry/go-mod-core-contracts/models"
)

var ValidInterval = SuccessfulDatabaseResult[0]
var OtherValidInterval = SuccessfulDatabaseResult[1]
var InvalidStartInterval = SuccessfulDatabaseResult[2]
var InvalidEndInterval = SuccessfulDatabaseResult[3]
var InvalidFreqInterval = SuccessfulDatabaseResult[4]

func TestAddExecutor(t *testing.T) {

	tests := []struct {
		name             string
		mockDb           IntervalWriter
		scClient         SchedulerQueueWriter
		interval         contract.Interval
		expectedResult   string
		expectedError    bool
		expectedErrorVal error
	}{

		{
			name:             "Successful database call",
			mockDb:           createAddMockIntervalSuccess(),
			scClient:         createAddMockIntervalSCSuccess(),
			interval:         ValidInterval,
			expectedResult:   ValidInterval.ID,
			expectedError:    false,
			expectedErrorVal: nil,
		},
		{
			name:             "Error Interval In Use",
			mockDb:           createAddMockIntervalInUse(),
			scClient:         createAddMockIntervalSCSuccess(),
			interval:         ValidInterval,
			expectedResult:   "",
			expectedError:    true,
			expectedErrorVal: intervalErrors.NewErrIntervalNameInUse(SuccessfulDatabaseResult[0].Name),
		},
		{
			name:             "Error AddInterval",
			mockDb:           createAddMockIntervalError(),
			scClient:         createAddMockIntervalSCSuccess(),
			interval:         ValidInterval,
			expectedResult:   "",
			expectedError:    true,
			expectedErrorVal: Error,
		},
		{
			name:             "Error AddToQueue",
			mockDb:           createAddMockIntervalSuccess(),
			scClient:         createAddMockIntervalSCError(),
			interval:         ValidInterval,
			expectedResult:   ValidInterval.ID,
			expectedError:    true,
			expectedErrorVal: Error,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(tt *testing.T) {
			op := NewAddExecutor(test.mockDb, test.scClient, test.interval)
			actual, err := op.Execute()
			if test.expectedError && err == nil {
				t.Error("Expected an error")
				return
			}

			if !test.expectedError && err != nil {
				t.Errorf("Unexpectedly encountered error: %s", err.Error())
				return
			}

			if !reflect.DeepEqual(test.expectedResult, actual) {
				t.Errorf("Expected result does not match the observed.\nExpected: %v\nObserved: %v\n", test.expectedResult, actual)
				return
			}

			if test.expectedErrorVal != nil && err != nil {
				if test.expectedErrorVal.Error() != err.Error() {
					t.Errorf("Observed error doesn't match expected.\nExpected: %v\nActual: %v\n", test.expectedErrorVal.Error(), err.Error())
				}
			}
		})
	}
}

func createAddMockIntervalSuccess() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", Name).Return(OtherValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return(Id, nil)
	return &dbMock
}

func createAddMockIntervalInUse() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", Name).Return(ValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return(Id, nil)
	return &dbMock
}

func createAddMockIntervalInvalidFreq() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", InvalidFreqInterval.Name).Return(OtherValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return(Id, nil)
	return &dbMock
}

func createAddMockIntervalError() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", ValidInterval.Name).Return(OtherValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return("", Error)
	return &dbMock
}

func createAddMockInvalidStart() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", InvalidStartInterval.Name).Return(ValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return(Id, nil)
	return &dbMock
}

func createAddMockInvalidEnd() IntervalWriter {
	dbMock := mocks.IntervalWriter{}
	dbMock.On("IntervalByName", InvalidEndInterval.Name).Return(ValidInterval, nil)
	dbMock.On("AddInterval", ValidInterval).Return(Id, nil)
	return &dbMock
}

func createAddMockIntervalSCSuccess() SchedulerQueueWriter {
	dbMock := mocks.SchedulerQueueWriter{}
	dbMock.On("AddIntervalToQueue", ValidInterval).Return(nil)
	return &dbMock
}

func createAddMockIntervalSCError() SchedulerQueueWriter {
	dbMock := mocks.SchedulerQueueWriter{}
	dbMock.On("AddIntervalToQueue", ValidInterval).Return(Error)
	return &dbMock
}

repository: alihanyalcin/edgex-go

repo_name: alihanyalcin/edgex-go


text:
# base recipe: meta-openembedded/meta-oe/recipes-support/syslog-ng/syslog-ng_3.19.1.bb
# base branch: warrior

SUMMARY = "Enhanced system logging daemon"
DESCRIPTION = "syslog-ng is an enhanced log daemon, supporting a wide range of input \
and output methods: syslog, unstructured text, message queues, \
databases (SQL and NoSQL alike) and more."
HOMEPAGE = "https://www.syslog-ng.com/"

inherit debian-package
require recipes-debian/sources/syslog-ng.inc
DEBIAN_UNPACK_DIR = "${WORKDIR}/syslog-ng-syslog-ng-${PV}"

LICENSE = "GPL-2.0-with-OpenSSL-exception & LGPL-2.1-with-OpenSSL-exception"
LIC_FILES_CHKSUM = "file://COPYING;md5=24c0c5cb2c83d9f2ab725481e4df5240"

SRC_URI += " \
    file://configure.ac-add-option-enable-thread-tls-to-manage-.patch \
    file://fix-config-libnet.patch \
    file://fix-invalid-ownership.patch \
"

DEPENDS = " \
    libpcre glib-2.0 openssl ivykis \
    bison-native autoconf-archive-native \
"

PACKAGES =+ "${PN}-mod-journal"
FILES_${PN}-mod-journal = "${libdir}/syslog-ng/libsdjournal.so"

inherit autotools gettext systemd pkgconfig update-rc.d

EXTRA_OECONF = " \
    --enable-dynamic-linking \
    --disable-sub-streams \
    --disable-pacct \
    --localstatedir=${localstatedir}/lib/${BPN} \
    --sysconfdir=${sysconfdir}/${BPN} \
    --with-module-dir=${libdir}/${BPN} \
    --with-sysroot=${STAGING_DIR_HOST} \
    --without-mongoc --disable-mongodb \
    --with-librabbitmq-client=no \
    --disable-python \
    --disable-java --disable-java-modules \
    --with-ivykis=system \
    --with-systemd-journal=auto \
    ${CONFIG_TLS} \
"

CONFIG_TLS = "--enable-thread-tls"
CONFIG_TLS_arm = "${@oe.utils.conditional( "DEBUG_BUILD", "1", " --disable-thread-tls", " --enable-thread-tls", d )}"

PACKAGECONFIG ??= " \
    ${@bb.utils.filter('DISTRO_FEATURES', 'ipv6 systemd', d)} \
"
PACKAGECONFIG[ipv6] = "--enable-ipv6,--disable-ipv6,,"
PACKAGECONFIG[systemd] = "--enable-systemd --with-systemdsystemunitdir=${systemd_system_unitdir},\
                          --disable-systemd --without-systemdsystemunitdir,systemd,"
PACKAGECONFIG[linux-caps] = "--enable-linux-caps,--disable-linux-caps,libcap,"
PACKAGECONFIG[dbi] = "--enable-sql,--disable-sql,libdbi,"
PACKAGECONFIG[libnet] = "--enable-libnet --with-libnet=${STAGING_BINDIR_CROSS},--disable-libnet,libnet,"
PACKAGECONFIG[http] = "--enable-http,--disable-http,curl,"
PACKAGECONFIG[smtp] = "--enable-smtp --with-libesmtp=${STAGING_LIBDIR},--disable-smtp,libesmtp,"
PACKAGECONFIG[json] = "--enable-json --with-jsonc=system,--disable-json,json-c,"
PACKAGECONFIG[tcp-wrapper] = "--enable-tcp-wrapper,--disable-tcp-wrapper,tcp-wrappers,"
PACKAGECONFIG[geoip] = "--enable-geoip,--disable-geoip,geoip,"
PACKAGECONFIG[native] = "--enable-native,--disable-native,,"

do_configure_prepend() {
	# In Debian source, these folders are empty
	for i in ${S}/lib/ivykis ${S}/lib/jsonc; do
		test -d $i && rmdir --ignore-fail-on-non-empty $i
	done
}

do_install_append() {
	install -d ${D}${sysconfdir}/${BPN}/conf.d \
	           ${D}${sysconfdir}/default \
	           ${D}${sysconfdir}/init.d \
	           ${D}${sysconfdir}/logcheck/ignore.d.paranoid \
	           ${D}${sysconfdir}/logcheck/ignore.d.server \
	           ${D}${sysconfdir}/logcheck/violations.ignore.d \
	           ${D}${sysconfdir}/logrotate.d \
	           ${D}${systemd_system_unitdir} \
	           ${D}${localstatedir}/lib/${BPN}

	install -m 0644 ${S}/debian/syslog-ng-core.syslog-ng.default \
	                ${D}${sysconfdir}/default/syslog-ng
	install -m 0755 ${S}/debian/syslog-ng-core.syslog-ng.init \
	                ${D}${sysconfdir}/init.d/syslog-ng
	install -m 0644 ${S}/debian/syslog-ng-core.syslog-ng.logcheck.ignore.paranoid \
	                ${D}${sysconfdir}/logcheck/ignore.d.paranoid/syslog-ng
	install -m 0644 ${S}/debian/syslog-ng-core.syslog-ng.logcheck.ignore.server \
	                ${D}${sysconfdir}/logcheck/ignore.d.server/syslog-ng
	install -m 0644 ${S}/debian/syslog-ng-core.syslog-ng.logcheck.violations.ignore \
	                ${D}${sysconfdir}/logcheck/violations.ignore.d/syslog-ng
	install -m 0644 ${S}/debian/syslog-ng-core.syslog-ng.logrotate \
	                ${D}${sysconfdir}/logrotate.d/syslog-ng

	install -m 0644 ${S}/debian/syslog-ng.systemd ${D}${systemd_system_unitdir}/syslog-ng.service
	install -m 0644 ${S}/debian/syslog-ng.conf ${D}${sysconfdir}/${BPN}/
	install -m 0644 ${S}/debian/scl.conf ${D}${sysconfdir}/${BPN}/
	install -m 0644 ${S}/debian/tty10.linux.conf \
		        ${D}${datadir}/${BPN}/include/scl/system/tty10.conf

	rm -f ${D}${systemd_system_unitdir}/syslog-ng@.service
}

RDEPENDS_${PN} += "gawk lsb"
RCONFLICTS_${PN} = "busybox-syslog sysklogd rsyslog"

CONFFILES_${PN} = " \
    ${sysconfdir}/${BPN}/syslog-ng.conf \
    ${sysconfdir}/${BPN}/scl.conf"
SYSTEMD_SERVICE_${PN} = "syslog-ng.service"

INITSCRIPT_NAME = "syslog-ng"
INITSCRIPT_PARAMS = "start 20 2 3 4 5 . stop 90 0 1 6 ."

repository: meta-debian/meta-debian

repo_name: meta-debian/meta-debian

branch_name: refs/heads/warrior

gha_language: BitBake

extension: bb


text:
DESCRIPTION = "Diversity Radar is a GPS location based communicative application"
HOMEPAGE = "http://diversity.projects.openmoko.org/"
SECTION = "openmoko/applications"
LICENSE = "GPL"
DEPENDS = "python-evas python-edje python-ecore python-edbus python-dbus python-etk"
RDEPENDS_${PN} = "diversity-daemon"
PV = "0.0.4+svnr${SRCREV}"
PR = "r0.01"

SRC_URI = "svn://svn.projects.openmoko.org/svnroot/diversity/toys;module=diversity-radar;proto=http"

S = "${WORKDIR}/${PN}"

inherit setuptools

FILES_${PN} += "${prefix}/share/*"


text:
file(REMOVE_RECURSE
  "Amr_and_Pins"
  "Amr_and_Pins.pdb"
  "CMakeFiles/Amr_and_Pins.dir/main.cpp.o"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/Amr_and_Pins.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: wdjpng/soi

repo_name: wdjpng/soi

extension: cmake


text:
package drugtrace

// Codeandparentlist 结构体
type Codeandparentlist struct {
	// 追溯码
	Code string `json:"code,omitempty" xml:"code,omitempty"`
	// 码级别
	CodeLevel string `json:"code_level,omitempty" xml:"code_level,omitempty"`
	// 父码
	ParentCode string `json:"parent_code,omitempty" xml:"parent_code,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao

branch_name: refs/heads/main

gha_language: Go


text:
// Code generated by "go generate". Please don't change this file directly.

package synthetics

import (
	"github.com/awslabs/goformation/v7/cloudformation/policies"
)

// Canary_BaseScreenshot AWS CloudFormation Resource (AWS::Synthetics::Canary.BaseScreenshot)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html
type Canary_BaseScreenshot struct {

	// IgnoreCoordinates AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-ignorecoordinates
	IgnoreCoordinates []string `json:"IgnoreCoordinates,omitempty"`

	// ScreenshotName AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-screenshotname
	ScreenshotName string `json:"ScreenshotName"`

	// AWSCloudFormationDeletionPolicy represents a CloudFormation DeletionPolicy
	AWSCloudFormationDeletionPolicy policies.DeletionPolicy `json:"-"`

	// AWSCloudFormationUpdateReplacePolicy represents a CloudFormation UpdateReplacePolicy
	AWSCloudFormationUpdateReplacePolicy policies.UpdateReplacePolicy `json:"-"`

	// AWSCloudFormationDependsOn stores the logical ID of the resources to be created before this resource
	AWSCloudFormationDependsOn []string `json:"-"`

	// AWSCloudFormationMetadata stores structured data associated with this resource
	AWSCloudFormationMetadata map[string]interface{} `json:"-"`

	// AWSCloudFormationCondition stores the logical ID of the condition that must be satisfied for this resource to be created
	AWSCloudFormationCondition string `json:"-"`
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *Canary_BaseScreenshot) AWSCloudFormationType() string {
	return "AWS::Synthetics::Canary.BaseScreenshot"
}

repository: awslabs/goformation

repo_name: awslabs/goformation


text:
/*
Copyright 2019 Cisco Systems

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: l2vpn_generic_if_list_detail.proto

package cisco_ios_xr_l2vpn_oper_l2vpnv2_nodes_node_generic_interface_list_details_generic_interface_list_detail

import (
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package

type L2VpnGenericIfListDetail_KEYS struct {
	NodeId               string   `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
	InterfaceListName    string   `protobuf:"bytes,2,opt,name=interface_list_name,json=interfaceListName,proto3" json:"interface_list_name,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *L2VpnGenericIfListDetail_KEYS) Reset()         { *m = L2VpnGenericIfListDetail_KEYS{} }
func (m *L2VpnGenericIfListDetail_KEYS) String() string { return proto.CompactTextString(m) }
func (*L2VpnGenericIfListDetail_KEYS) ProtoMessage()    {}
func (*L2VpnGenericIfListDetail_KEYS) Descriptor() ([]byte, []int) {
	return fileDescriptor_0d38fde8f332160a, []int{0}
}

func (m *L2VpnGenericIfListDetail_KEYS) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_L2VpnGenericIfListDetail_KEYS.Unmarshal(m, b)
}
func (m *L2VpnGenericIfListDetail_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_L2VpnGenericIfListDetail_KEYS.Marshal(b, m, deterministic)
}
func (m *L2VpnGenericIfListDetail_KEYS) XXX_Merge(src proto.Message) {
	xxx_messageInfo_L2VpnGenericIfListDetail_KEYS.Merge(m, src)
}
func (m *L2VpnGenericIfListDetail_KEYS) XXX_Size() int {
	return xxx_messageInfo_L2VpnGenericIfListDetail_KEYS.Size(m)
}
func (m *L2VpnGenericIfListDetail_KEYS) XXX_DiscardUnknown() {
	xxx_messageInfo_L2VpnGenericIfListDetail_KEYS.DiscardUnknown(m)
}

var xxx_messageInfo_L2VpnGenericIfListDetail_KEYS proto.InternalMessageInfo

func (m *L2VpnGenericIfListDetail_KEYS) GetNodeId() string {
	if m != nil {
		return m.NodeId
	}
	return ""
}

func (m *L2VpnGenericIfListDetail_KEYS) GetInterfaceListName() string {
	if m != nil {
		return m.InterfaceListName
	}
	return ""
}

type InterfacesItem struct {
	Value                string   `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *InterfacesItem) Reset()         { *m = InterfacesItem{} }
func (m *InterfacesItem) String() string { return proto.CompactTextString(m) }
func (*InterfacesItem) ProtoMessage()    {}
func (*InterfacesItem) Descriptor() ([]byte, []int) {
	return fileDescriptor_0d38fde8f332160a, []int{1}
}

func (m *InterfacesItem) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_InterfacesItem.Unmarshal(m, b)
}
func (m *InterfacesItem) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_InterfacesItem.Marshal(b, m, deterministic)
}
func (m *InterfacesItem) XXX_Merge(src proto.Message) {
	xxx_messageInfo_InterfacesItem.Merge(m, src)
}
func (m *InterfacesItem) XXX_Size() int {
	return xxx_messageInfo_InterfacesItem.Size(m)
}
func (m *InterfacesItem) XXX_DiscardUnknown() {
	xxx_messageInfo_InterfacesItem.DiscardUnknown(m)
}

var xxx_messageInfo_InterfacesItem proto.InternalMessageInfo

func (m *InterfacesItem) GetValue() string {
	if m != nil {
		return m.Value
	}
	return ""
}

type L2VpnGenericIfList struct {
	InterfaceListNameXr  string            `protobuf:"bytes,1,opt,name=interface_list_name_xr,json=interfaceListNameXr,proto3" json:"interface_list_name_xr,omitempty"`
	InterfaceListId      uint32            `protobuf:"varint,2,opt,name=interface_list_id,json=interfaceListId,proto3" json:"interface_list_id,omitempty"`
	Interface            []*InterfacesItem `protobuf:"bytes,3,rep,name=interface,proto3" json:"interface,omitempty"`
	NumberOfInterfaces   uint32            `protobuf:"varint,4,opt,name=number_of_interfaces,json=numberOfInterfaces,proto3" json:"number_of_interfaces,omitempty"`
	Items                uint32            `protobuf:"varint,5,opt,name=items,proto3" json:"items,omitempty"`
	XXX_NoUnkeyedLiteral struct{}          `json:"-"`
	XXX_unrecognized     []byte            `json:"-"`
	XXX_sizecache        int32             `json:"-"`
}

func (m *L2VpnGenericIfList) Reset()         { *m = L2VpnGenericIfList{} }
func (m *L2VpnGenericIfList) String() string { return proto.CompactTextString(m) }
func (*L2VpnGenericIfList) ProtoMessage()    {}
func (*L2VpnGenericIfList) Descriptor() ([]byte, []int) {
	return fileDescriptor_0d38fde8f332160a, []int{2}
}

func (m *L2VpnGenericIfList) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_L2VpnGenericIfList.Unmarshal(m, b)
}
func (m *L2VpnGenericIfList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_L2VpnGenericIfList.Marshal(b, m, deterministic)
}
func (m *L2VpnGenericIfList) XXX_Merge(src proto.Message) {
	xxx_messageInfo_L2VpnGenericIfList.Merge(m, src)
}
func (m *L2VpnGenericIfList) XXX_Size() int {
	return xxx_messageInfo_L2VpnGenericIfList.Size(m)
}
func (m *L2VpnGenericIfList) XXX_DiscardUnknown() {
	xxx_messageInfo_L2VpnGenericIfList.DiscardUnknown(m)
}

var xxx_messageInfo_L2VpnGenericIfList proto.InternalMessageInfo

func (m *L2VpnGenericIfList) GetInterfaceListNameXr() string {
	if m != nil {
		return m.InterfaceListNameXr
	}
	return ""
}

func (m *L2VpnGenericIfList) GetInterfaceListId() uint32 {
	if m != nil {
		return m.InterfaceListId
	}
	return 0
}

func (m *L2VpnGenericIfList) GetInterface() []*InterfacesItem {
	if m != nil {
		return m.Interface
	}
	return nil
}

func (m *L2VpnGenericIfList) GetNumberOfInterfaces() uint32 {
	if m != nil {
		return m.NumberOfInterfaces
	}
	return 0
}

func (m *L2VpnGenericIfList) GetItems() uint32 {
	if m != nil {
		return m.Items
	}
	return 0
}

type L2VpnPwheRange struct {
	Lower                uint32   `protobuf:"varint,1,opt,name=lower,proto3" json:"lower,omitempty"`
	Upper                uint32   `protobuf:"varint,2,opt,name=upper,proto3" json:"upper,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *L2VpnPwheRange) Reset()         { *m = L2VpnPwheRange{} }
func (m *L2VpnPwheRange) String() string { return proto.CompactTextString(m) }
func (*L2VpnPwheRange) ProtoMessage()    {}
func (*L2VpnPwheRange) Descriptor() ([]byte, []int) {
	return fileDescriptor_0d38fde8f332160a, []int{3}
}

func (m *L2VpnPwheRange) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_L2VpnPwheRange.Unmarshal(m, b)
}
func (m *L2VpnPwheRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_L2VpnPwheRange.Marshal(b, m, deterministic)
}
func (m *L2VpnPwheRange) XXX_Merge(src proto.Message) {
	xxx_messageInfo_L2VpnPwheRange.Merge(m, src)
}
func (m *L2VpnPwheRange) XXX_Size() int {
	return xxx_messageInfo_L2VpnPwheRange.Size(m)
}
func (m *L2VpnPwheRange) XXX_DiscardUnknown() {
	xxx_messageInfo_L2VpnPwheRange.DiscardUnknown(m)
}

var xxx_messageInfo_L2VpnPwheRange proto.InternalMessageInfo

func (m *L2VpnPwheRange) GetLower() uint32 {
	if m != nil {
		return m.Lower
	}
	return 0
}

func (m *L2VpnPwheRange) GetUpper() uint32 {
	if m != nil {
		return m.Upper
	}
	return 0
}

type L2VpnGenericIfListDetail struct {
	Summary              *L2VpnGenericIfList `protobuf:"bytes,50,opt,name=summary,proto3" json:"summary,omitempty"`
	Interface            []*InterfacesItem   `protobuf:"bytes,51,rep,name=interface,proto3" json:"interface,omitempty"`
	Items                uint32              `protobuf:"varint,52,opt,name=items,proto3" json:"items,omitempty"`
	IsProvisioned        bool                `protobuf:"varint,53,opt,name=is_provisioned,json=isProvisioned,proto3" json:"is_provisioned,omitempty"`
	PsedowireEtherItems  uint32              `protobuf:"varint,54,opt,name=psedowire_ether_items,json=psedowireEtherItems,proto3" json:"psedowire_ether_items,omitempty"`
	PseudowireEtherRange []*L2VpnPwheRange   `protobuf:"bytes,55,rep,name=pseudowire_ether_range,json=pseudowireEtherRange,proto3" json:"pseudowire_ether_range,omitempty"`
	PseudowireIwItems    uint32              `protobuf:"varint,56,opt,name=pseudowire_iw_items,json=pseudowireIwItems,proto3" json:"pseudowire_iw_items,omitempty"`
	PseudowireIwRange    []*L2VpnPwheRange   `protobuf:"bytes,57,rep,name=pseudowire_iw_range,json=pseudowireIwRange,proto3" json:"pseudowire_iw_range,omitempty"`
	XXX_NoUnkeyedLiteral struct{}            `json:"-"`
	XXX_unrecognized     []byte              `json:"-"`
	XXX_sizecache        int32               `json:"-"`
}

func (m *L2VpnGenericIfListDetail) Reset()         { *m = L2VpnGenericIfListDetail{} }
func (m *L2VpnGenericIfListDetail) String() string { return proto.CompactTextString(m) }
func (*L2VpnGenericIfListDetail) ProtoMessage()    {}
func (*L2VpnGenericIfListDetail) Descriptor() ([]byte, []int) {
	return fileDescriptor_0d38fde8f332160a, []int{4}
}

func (m *L2VpnGenericIfListDetail) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_L2VpnGenericIfListDetail.Unmarshal(m, b)
}
func (m *L2VpnGenericIfListDetail) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_L2VpnGenericIfListDetail.Marshal(b, m, deterministic)
}
func (m *L2VpnGenericIfListDetail) XXX_Merge(src proto.Message) {
	xxx_messageInfo_L2VpnGenericIfListDetail.Merge(m, src)
}
func (m *L2VpnGenericIfListDetail) XXX_Size() int {
	return xxx_messageInfo_L2VpnGenericIfListDetail.Size(m)
}
func (m *L2VpnGenericIfListDetail) XXX_DiscardUnknown() {
	xxx_messageInfo_L2VpnGenericIfListDetail.DiscardUnknown(m)
}

var xxx_messageInfo_L2VpnGenericIfListDetail proto.InternalMessageInfo

func (m *L2VpnGenericIfListDetail) GetSummary() *L2VpnGenericIfList {
	if m != nil {
		return m.Summary
	}
	return nil
}

func (m *L2VpnGenericIfListDetail) GetInterface() []*InterfacesItem {
	if m != nil {
		return m.Interface
	}
	return nil
}

func (m *L2VpnGenericIfListDetail) GetItems() uint32 {
	if m != nil {
		return m.Items
	}
	return 0
}

func (m *L2VpnGenericIfListDetail) GetIsProvisioned() bool {
	if m != nil {
		return m.IsProvisioned
	}
	return false
}

func (m *L2VpnGenericIfListDetail) GetPsedowireEtherItems() uint32 {
	if m != nil {
		return m.PsedowireEtherItems
	}
	return 0
}

func (m *L2VpnGenericIfListDetail) GetPseudowireEtherRange() []*L2VpnPwheRange {
	if m != nil {
		return m.PseudowireEtherRange
	}
	return nil
}

func (m *L2VpnGenericIfListDetail) GetPseudowireIwItems() uint32 {
	if m != nil {
		return m.PseudowireIwItems
	}
	return 0
}

func (m *L2VpnGenericIfListDetail) GetPseudowireIwRange() []*L2VpnPwheRange {
	if m != nil {
		return m.PseudowireIwRange
	}
	return nil
}

func init() {
	proto.RegisterType((*L2VpnGenericIfListDetail_KEYS)(nil), "cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.generic_interface_list_details.generic_interface_list_detail.l2vpn_generic_if_list_detail_KEYS")
	proto.RegisterType((*InterfacesItem)(nil), "cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.generic_interface_list_details.generic_interface_list_detail.interfaces_item")
	proto.RegisterType((*L2VpnGenericIfList)(nil), "cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.generic_interface_list_details.generic_interface_list_detail.l2vpn_generic_if_list")
	proto.RegisterType((*L2VpnPwheRange)(nil), "cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.generic_interface_list_details.generic_interface_list_detail.l2vpn_pwhe_range")
	proto.RegisterType((*L2VpnGenericIfListDetail)(nil), "cisco_ios_xr_l2vpn_oper.l2vpnv2.nodes.node.generic_interface_list_details.generic_interface_list_detail.l2vpn_generic_if_list_detail")
}

func init() { proto.RegisterFile("l2vpn_generic_if_list_detail.proto", fileDescriptor_0d38fde8f332160a) }

var fileDescriptor_0d38fde8f332160a = []byte{
	// 496 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0xbd, 0x8e, 0xd3, 0x40,
	0x10, 0x96, 0xef, 0xb8, 0x1c, 0x37, 0xa7, 0x70, 0x64, 0x93, 0x3b, 0x5c, 0x50, 0x04, 0x4b, 0x88,
	0x88, 0xc2, 0x42, 0x0e, 0xbf, 0x0d, 0xdd, 0x15, 0x16, 0x08, 0x90, 0x69, 0xa0, 0x5a, 0xf9, 0xe2,
	0x49, 0x6e, 0x25, 0x7b, 0x77, 0xb5, 0x6b, 0xc7, 0xb9, 0x86, 0xc7, 0x40, 0xbc, 0x02, 0x15, 0xcf,
	0x42, 0xc9, 0xdb, 0x20, 0xef, 0x1a, 0x3b, 0x31, 0x51, 0xca, 0x40, 0x13, 0x65, 0xe6, 0x9b, 0xf9,
	0xf6, 0xfb, 0x66, 0x46, 0x06, 0x2f, 0x0d, 0x96, 0x92, 0xd3, 0x05, 0x72, 0x54, 0x6c, 0x46, 0xd9,
	0x9c, 0xa6, 0x4c, 0xe7, 0x34, 0xc1, 0x3c, 0x66, 0xa9, 0x2f, 0x95, 0xc8, 0x05, 0x59, 0xcc, 0x98,
	0x9e, 0x09, 0xca, 0x84, 0xa6, 0x2b, 0x45, 0x6d, 0x83, 0x90, 0xa8, 0x7c, 0xf3, 0x77, 0x19, 0xf8,
	0x5c, 0x24, 0xa8, 0xcd, 0xaf, 0xdf, 0x10, 0xf1, 0x1c, 0xd5, 0x3c, 0x9e, 0xe1, 0x3a, 0x9f, 0xde,
	0x0d, 0x7b, 0x29, 0x3c, 0xd8, 0x25, 0x87, 0xbe, 0xb9, 0xfc, 0xfc, 0x91, 0xdc, 0x83, 0xe3, 0xea,
	0x25, 0xca, 0x12, 0xd7, 0x19, 0x3b, 0x93, 0x93, 0xa8, 0x57, 0x85, 0x61, 0x42, 0x7c, 0x18, 0x76,
	0x68, 0x79, 0x9c, 0xa1, 0x7b, 0x60, 0x8a, 0x06, 0x0d, 0xf4, 0x96, 0xe9, 0xfc, 0x5d, 0x9c, 0xa1,
	0xf7, 0x08, 0xce, 0x9a, 0xa4, 0xa6, 0x2c, 0xc7, 0x8c, 0x8c, 0xe0, 0x68, 0x19, 0xa7, 0x05, 0xd6,
	0xcc, 0x36, 0xf0, 0x7e, 0x1d, 0xc0, 0xf9, 0x56, 0x5d, 0x64, 0x0a, 0x17, 0x5b, 0x9e, 0xa4, 0x2b,
	0x55, 0x13, 0x0c, 0xff, 0x7a, 0xf5, 0x93, 0x22, 0x8f, 0x61, 0xd0, 0x69, 0x62, 0x89, 0x51, 0xd9,
	0x8f, 0xce, 0x36, 0xea, 0xc3, 0x84, 0x7c, 0x75, 0xe0, 0xa4, 0xc9, 0xb9, 0x87, 0xe3, 0xc3, 0xc9,
	0x69, 0xb0, 0xf2, 0xf7, 0xb4, 0x0f, 0xbf, 0x33, 0x9e, 0xa8, 0x95, 0x42, 0x9e, 0xc0, 0x88, 0x17,
	0xd9, 0x15, 0x2a, 0x2a, 0xe6, 0x6d, 0xb7, 0x76, 0x6f, 0x19, 0x1f, 0xc4, 0x62, 0xef, 0xe7, 0x61,
	0x83, 0x54, 0xb3, 0xad, 0x48, 0xb4, 0x7b, 0x64, 0x4a, 0x6c, 0xe0, 0xbd, 0x86, 0xbb, 0xd6, 0x80,
	0x2c, 0xaf, 0x91, 0xaa, 0x98, 0x2f, 0xb0, 0xaa, 0x4c, 0x45, 0x89, 0x76, 0x88, 0xfd, 0xc8, 0x06,
	0x55, 0xb6, 0x90, 0x12, 0x55, 0x3d, 0x2a, 0x1b, 0x78, 0x3f, 0x7b, 0x70, 0x7f, 0xd7, 0xcd, 0x90,
	0x6f, 0x0e, 0x1c, 0xeb, 0x22, 0xcb, 0x62, 0x75, 0xe3, 0x06, 0x63, 0x67, 0x72, 0x1a, 0x7c, 0xd9,
	0xdb, 0xfc, 0xb6, 0x0a, 0x8b, 0xfe, 0xc8, 0xe9, 0x2c, 0x77, 0xfa, 0xff, 0x2c, 0xb7, 0x59, 0xd5,
	0xd3, 0xb5, 0x55, 0x91, 0x87, 0x70, 0x87, 0x69, 0x2a, 0x95, 0x58, 0x32, 0xcd, 0x04, 0xc7, 0xc4,
	0x7d, 0x36, 0x76, 0x26, 0xb7, 0xa3, 0x3e, 0xd3, 0x1f, 0xda, 0x24, 0x09, 0xe0, 0x5c, 0x6a, 0x4c,
	0x44, 0xc9, 0x14, 0x52, 0xcc, 0xaf, 0x51, 0x51, 0x4b, 0xf6, 0xdc, 0x90, 0x0d, 0x1b, 0xf0, 0xb2,
	0xc2, 0x42, 0x43, 0xfd, 0xc3, 0x81, 0x0b, 0xa9, 0xb1, 0xd8, 0xe8, 0x32, 0xc7, 0xe0, 0xbe, 0x30,
	0x63, 0xb9, 0xd9, 0xf3, 0xce, 0xda, 0x6b, 0x8c, 0x46, 0xad, 0x30, 0xa3, 0x38, 0x32, 0x37, 0xea,
	0xc3, 0x70, 0x4d, 0x30, 0x2b, 0x6b, 0x8f, 0x2f, 0x8d, 0xc7, 0x41, 0x0b, 0x85, 0xa5, 0x75, 0xf8,
	0xdd, 0xe9, 0x36, 0x58, 0x7b, 0xaf, 0xfe, 0xb5, 0xbd, 0x0d, 0xad, 0xc6, 0xdb, 0x55, 0xcf, 0x7c,
	0xf6, 0xa7, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x79, 0x7a, 0x9f, 0x1a, 0x1c, 0x06, 0x00, 0x00,
}

repository: cisco-ie/cisco-proto

repo_name: cisco-ie/cisco-proto


text:
// Copyright 2021 Chaos Mesh 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 cmd

import (
	"context"
	"fmt"
	"strings"

	"github.com/hasura/go-graphql-client"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"

	cm "github.com/chaos-mesh/chaos-mesh/pkg/chaosctl/common"
)

type logsOptions struct {
	tail int64
	node string
}

type Component string

const (
	Manager   Component = "MANAGER"
	Daemon    Component = "DAEMON"
	Dashboard Component = "DASHBOARD"
	DnsServer Component = "DNSSERVER"
)

func NewLogsCmd() (*cobra.Command, error) {
	o := &logsOptions{}

	logsCmd := &cobra.Command{
		Use:   `logs [-t LINE]`,
		Short: `Print logs of controller-manager, chaos-daemon and chaos-dashboard`,
		Long: `Print logs of controller-manager, chaos-daemon and chaos-dashboard, to provide debug information.

Examples:
  # Default print all log of all chaosmesh components
  chaosctl logs

  # Print 100 log lines for chaosmesh components in node NODENAME
  chaosctl logs -t 100 -n NODENAME`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return o.Run(args)
		},
		SilenceErrors:     true,
		SilenceUsage:      true,
		ValidArgsFunction: noCompletions,
	}

	logsCmd.Flags().Int64VarP(&o.tail, "tail", "t", -1, "number of lines of recent log")
	logsCmd.Flags().StringVarP(&o.node, "node", "n", "", "the node of target pods")
	err := logsCmd.RegisterFlagCompletionFunc("node", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		clientset, err := cm.InitClientSet()
		if err != nil {
			return nil, cobra.ShellCompDirectiveDefault
		}
		return listNodes(toComplete, clientset.KubeCli)
	})
	if err != nil {
		return nil, err
	}
	return logsCmd, nil
}

// Run logs
func (o *logsOptions) Run(args []string) error {
	client, cancel, err := cm.CreateClient(context.TODO(), managerNamespace, managerSvc)
	if err != nil {
		return errors.Wrap(err, "failed to initialize clientset")
	}
	defer cancel()

	componentsNeeded := []Component{Manager, Daemon, Dashboard, DnsServer}
	for _, name := range componentsNeeded {
		var query struct {
			Namespace []struct {
				Component []struct {
					Name string
					Spec struct {
						NodeName string
					}
					Logs string
				} `graphql:"component(component: $component)"`
			} `graphql:"namespace(ns: $namespace)"`
		}

		variables := map[string]interface{}{
			"namespace": graphql.String(managerNamespace),
			"component": name,
		}

		err := client.QueryClient.Query(context.TODO(), &query, variables)
		if err != nil {
			return err
		}

		if len(query.Namespace) == 0 {
			return fmt.Errorf("no namespace %s found", managerNamespace)
		}

		for _, component := range query.Namespace[0].Component {
			if o.node != "" && component.Spec.NodeName != o.node {
				// ignore component on this node
				continue
			}

			logLines := strings.Split(component.Logs, "\n")
			if o.tail > 0 {
				if len(logLines) > int(o.tail) {
					logLines = logLines[len(logLines)-int(o.tail)-1:]
				}
			}

			cm.PrettyPrint(fmt.Sprintf("[%s]", component.Name), 0, cm.Cyan)
			cm.PrettyPrint(strings.Join(logLines, "\n"), 1, cm.NoColor)
		}
	}
	return nil
}

func listNodes(toComplete string, c *kubernetes.Clientset) ([]string, cobra.ShellCompDirective) {
	// FIXME: get context from parameter
	nodes, err := c.CoreV1().Nodes().List(context.TODO(), v1.ListOptions{})
	if err != nil {
		return nil, cobra.ShellCompDirectiveDefault
	}
	var ret []string
	for _, ns := range nodes.Items {
		if strings.HasPrefix(ns.Name, toComplete) {
			ret = append(ret, ns.Name)
		}
	}
	return ret, cobra.ShellCompDirectiveNoFileComp
}

repository: chaos-mesh/chaos-mesh

repo_name: chaos-mesh/chaos-mesh


text:
DESCRIPTION = "Anopa rc"
HOMEPAGE = "http://jjacky.com/anopa/"
LICENSE = "GPLv3+"
SECTION = "base"
DEPENDS = "skalibs execline s6"
RDEPENDS_${PN} = "execline anopa-common s6"
RDEPENDS_${PN}-initrd = "execline anopa-common"
RDEPENDS_${PN}-common = "execline"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

SRCREV = "c371ecc5a81140ce5b384a4fff936fd00d4079db"
SRC_URI = "git://github.com/jjk-jacky/anopa;protocol=git;branch=next \
    "

S = "${WORKDIR}/git"

# Attempt to add debug symbols; sometimes 'aa-status -aL' crashes with a
# malloc corruption that's hard to track down
EXTRA_OEMAKE = "CFLAGS=-g LDFLAGS=-g"

do_configure() {
    ${S}/tools/gen-deps.sh > ${S}/package/deps.mak
	${S}/configure --enable-shared --enable-static --with-sysdeps=${STAGING_DIR_TARGET}/${libdir}/skalibs/sysdeps
    touch ${S}/-lskarnet
    touch ${S}/-ls6
    touch ${S}/-lexecline
}

do_install () {
    oe_runmake install DESTDIR=${D}
}

PACKAGES+="${PN}-initrd ${PN}-common"

FILES_${PN} = "/libexec/aa-stage1 /libexec/aa-stage2 /libexec/aa-stage3"
FILES_${PN}-initrd = "/libexec/aa-stage0 /libexec/aa-stage4"
FILES_${PN}-common = "/lib /bin"


text:
@book{Newman:2016,
 author		= {Sam Newman},
 title 		= {Budowanie mikrousług},
 year 		= {2019},
 publisher 	= {Helion}
}

@book{Ziade:2018,
 author		= {Tarek Ziadé},
 title 		= {Rozwijanie mikrousług w Pythonie. Budowa, testowanie, instalacja i skalowanie},
 year 		= {2018},
 publisher 	= {Helion}
}

@book{Wilton:2005,
 author		= {Paul Wilton, John Colby},
 title 		= {SQL. Od podstaw},
 year 		= {2005},
 publisher 	= {Helion}
}

@book{Rodger:2019,
 author		= {Richard Rodger},
 title 		= {Tao Mikrousług. Projektowanie i wdrażanie},
 year 		= {2019},
 publisher 	= {Helion}
}

@book{Hunt:2011,
 author		= {Andrew Hunt, David Thomas},
 title 		= {Pragmatyczny programista. Od czeladnika do mistrza},
 year 		= {2011},
 publisher 	= {Helion}
}

@book{Folwer:2019,
 author		= {Susan J. Fowler},
 title 		= {Mikrousługi. Wdrażanie i standaryzacja systemów w organizacji inżynierskiej},
 year 		= {2019},
 publisher 	= {Helion}
}

@book{Gamma:2017,
 author		= {Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides},
 title 		= {Wzorce projektowe. Elementy oprogramowania obiektowego wielokrotnego użytku},
 year 		= {2017},
 publisher 	= {Helion}
}

@article{Nations:2019,
  author    = {Daniel Nations},
  title     = {What Exactly Is a Web Application?},
  journal   = {Lifewire},
  year      = {2019},
  note      = {\url{https://www.lifewire.com/what-is-a-web-application-3486637}}
}

@article{Herman:2020,
  author    = {Michael Herman},
  title     = {Dockerizing \textit{Flask} with \textit{Postgres}, \textit{Gunicorn}, and \textit{Nginx}},
  journal   = {TestDriven Labs},
  year      = {2020},
  note      = {\url{https://testdriven.io/blog/dockerizing-flask-with-postgres-gunicorn-and-nginx/}}
}

@article{Herman:2017,
  author    = {Real Python (Michael Herman)},
  title     = {Token-Based Authentication With Flask},
  journal   = {Real Python},
  year      = {2017},
  note      = {\url{https://realpython.com/token-based-authentication-with-flask/}}
}

@article{Grinberg:2017,
  author    = {Miguel Grinberg},
  title     = {The \textit{Flask Mega-Tutorial}},
  journal   = {miguelgrinberg.com},
  year      = {2017},
  note      = {\url{https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world}}
}

@manual{msbuild,
 author		= {© Microsoft 2020},
 title 		= {Dokumentacja Microsoft Build},
 note 		= {\url{https://docs.microsoft.com/pl-pl/}}
}

@manual{ruby,
 author     = {"Rails", "Ruby on Rails" David Heinemeier Hansson. All rights reserved},
 title     = {Dokumentacja Ruby on Rails},
 note       = {\url{https://guides.rubyonrails.org}}
}

@manual{django,
 author		= {© 2005-2020 Django Software Foundation and individual contributors},
 title 		= {Dokumentacja Django w wersji 3.0},
 note 		= {\url{https://docs.djangoproject.com/en/3.0/}}
}

@manual{flask,
 author		= {© Copyright 2010 Pallets},
 title 		= {Dokumentacja Flaska w wersji 1.1.x},
 note 		= {\url{https://flask.palletsprojects.com/en/1.1.x/}}
}

@manual{vuejs,
 author		= {Copyright © 2014-2020 Evan You},
 title 		= {Dokumentacja Vue.JS w wersji 2.x},
 note 		= {\url{https://vuejs.org/v2/guide/}}
}

@manual{mdn,
 author		= {© 2005-2020 Mozilla and individual contributors},
 title 		= {MDN web docs},
 note 		= {\url{https://developer.mozilla.org/en-US/}}
}

@manual{docker,
 author		= {Copyright © 2013-2020 Docker Inc.},
 title 		= {Dokumentacja Dockera},
 note 		= {\url{https://docs.docker.com/}
}

@manual{nginx,
 author		= {Copyright © F5, Inc},
 title 		= {Dokumentacja Nginxa},
 note 		= {\url{https://docs.nginx.com}}
}

@manual{python,
 author     = {© Copyright 2001-2020, Python Software Foundation.},
 title      = {Dokumentacja języka Python 3.x},
 note       = {\url{https://docs.python.org/3/}},
}

@manual{flasksql,
 author     = {© Copyright 2010 Pallets},
 title      = {Dokumentacja biblioteki Flask-SQLAlchemy w wersji 2.x},
 note       = {\url{https://flask-sqlalchemy.palletsprojects.com/en/2.x/}},
}

@manual{http,
 author     = {Copyright © 1996-2003 W3C®},
 title      = {Oficjalna specyfikacja najnowszej wersji protokołu HTTP},
 note       = {\url{https://www.w3.org/Protocols/}},
}

@manual{nuxtjs,
 author     = {Brak informacji o autorze (wydane na podstawie licencji MIT)},
 title      = {Dokumentacja frameworku NuxtJS},
 note       = {\url{https://nuxtjs.org/guide}},
}

@manual{aws,
 author     = {© 2020, Amazon Web Services, Inc. or its affiliates.},
 title      = {Dokumentacja Amazon Web Services},
 note       = {\url{https://docs.aws.amazon.com}},
}

repository: krskibin/mono-micro

repo_name: krskibin/mono-micro


text:
// Copyright 2021 Fugue, 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 rego

import (
	"encoding/json"
	"path/filepath"

	"github.com/fugue/regula/v3/pkg/loader"
	"github.com/open-policy-agent/opa/ast"
	"github.com/open-policy-agent/opa/rego"
	"github.com/open-policy-agent/opa/types"
)

func resolvePath(path, location string) string {
	if !filepath.IsAbs(path) {
		if location == "" {
			location = "."
		} else {
			location = filepath.Dir(location)
		}
		path = filepath.Join(location, path)
	}
	return path
}

func loadToAstTerm(options loader.LoadPathsOptions) (*ast.Term, error) {
	configs, err := loader.LocalConfigurationLoader(options)()
	if err != nil {
		return nil, err
	}

	parseable := []interface{}{}

	raw, _ := json.Marshal(configs.RegulaInput())
	_ = json.Unmarshal(raw, &parseable)

	v, err := ast.InterfaceToValue(parseable)
	if err != nil {
		return nil, err
	}

	return ast.NewTerm(v), nil
}

func regulaLoad(ctx rego.BuiltinContext, a *ast.Term) (*ast.Term, error) {
	var path string
	if err := ast.As(a.Value, &path); err != nil {
		return nil, err
	}

	path = resolvePath(path, ctx.Location.File)

	return loadToAstTerm(loader.LoadPathsOptions{
		Paths:       []string{path},
		NoGitIgnore: false,
	})
}

func regulaLoadType(ctx rego.BuiltinContext, a *ast.Term, b *ast.Term) (*ast.Term, error) {
	var path string
	var inputTypeStr string
	if err := ast.As(a.Value, &path); err != nil {
		return nil, err
	}
	if err := ast.As(b.Value, &inputTypeStr); err != nil {
		return nil, err
	}

	inputType, err := loader.InputTypeFromString(inputTypeStr)
	if err != nil {
		return nil, err
	}

	path = resolvePath(path, ctx.Location.File)

	return loadToAstTerm(loader.LoadPathsOptions{
		Paths:       []string{path},
		InputTypes:  []loader.InputType{inputType},
		NoGitIgnore: false,
	})
}

func RegisterBuiltins() {
	rego.RegisterBuiltin1(
		&rego.Function{
			Name:    "regula_load",
			Decl:    types.NewFunction(types.Args(types.S), types.A),
			Memoize: true,
		},
		regulaLoad,
	)
	rego.RegisterBuiltin2(
		&rego.Function{
			Name:    "regula_load_type",
			Decl:    types.NewFunction(types.Args(types.S, types.S), types.A),
			Memoize: true,
		},
		regulaLoadType,
	)
}

repository: fugue/regula

repo_name: fugue/regula

gha_language: Open Policy Agent


text:
EXTRAPATHS:prepend := "${THISDIR}/${PN}:"

inherit allarch systemd

DESCRIPTION = "Service for starting fan at boot time to prevent overheating"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = " file://fan-startup.service "

RDEPENDS:${PN} = " bash systemd"

S = "${WORKDIR}"

do_install () {
    install -d ${D}/${systemd_unitdir}/system
    install -m 0644 ${WORKDIR}/fan-startup.service ${D}/${systemd_unitdir}/system/fan-startup.service
}

SYSTEMD_SERVICE:${PN} = "fan-startup.service"

COMPATIBLE_MACHINE = "(jetson-xavier|jetson-tx2|jetson-xavier-nx-devkit)"

repository: balena-os/balena-jetson

repo_name: balena-os/balena-jetson


text:
SUMMARY = "JSON::XS - JSON serialising/deserialising, done correctly and fast"
AUTHOR = "Marc Lehmann <schmorp@schmorp.de>"
HOMEPAGE = "https://metacpan.org/module/JSON::XS"
SECTION = "libs"
LICENSE = "Artistic-1.0 | GPL-1.0+"
LIC_FILES_CHKSUM = "file://COPYING;md5=043dba8b278e1db1b0ef93f30140b02b"

SRC_URI = "http://cpan.metacpan.org/authors/id/M/ML/MLEHMANN/JSON-XS-${PV}.tar.gz"
SRC_URI[md5sum] = "dda3c03335665cdeff91c37a269b833b"
SRC_URI[sha256sum] = "a62fdf2777b9ae206aef382dbb62c9a126ce2ceef0229edacee3f6a9c78900ea"

S = "${WORKDIR}/JSON-XS-${PV}"

inherit cpan

RDEPENDS_${PN} += "libcommon-sense-perl"

RPROVIDES_${PN} += "libjson-xs-boolean-perl"

BBCLASSEXTEND = "native"


text:
package main

/*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
import (
	// System Libraries
	"flag"
	"fmt"
	//"io/ioutil"
	//"net/http"
	"os"
	"path"
	"strconv"

	// External libraries
	// mine
	"gitlab.com/nolim1t/golang-httpd-test/bitcoind"
	"gitlab.com/nolim1t/golang-httpd-test/btcprice"
	"gitlab.com/nolim1t/golang-httpd-test/common"
	"gitlab.com/nolim1t/golang-httpd-test/jwt"
	"gitlab.com/nolim1t/golang-httpd-test/pineclient"

	// github
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"github.com/pelletier/go-toml"
	log "github.com/sirupsen/logrus"
	// non-github
	"gopkg.in/natefinch/lumberjack.v2"
)

// types
type (
	// How to read from Bitcoin client
	BitcoinClient interface {
		BlockCount() (int64, error)
		BlockchainInfo() (bitcoind.BlockchainInfoResponse, error)
		NetworkInfo() (bitcoind.NetworkInfoResponse, error)
		GetTransactionInfo(string) (bitcoind.VerboseTransactionInfo, error)
		GetMempoolContents() ([]string, error)
		PushTransaction(hex string) (string, error)
		GetBestBlockHash() (string, error)
		GetBlockHashByHeight(height int64) (string, error)
		GetBlock(hash string) (bitcoind.BitcoinBlockResponse, error)
		GetMempoolInfo() (bitcoind.MempoolInfoResponse, error)
		GetMiningInfo() (bitcoind.MiningInfoResponse, error)
		GetPeerInfo() ([]bitcoind.PeerInfo, error)
		GetBlockStats(int64) (bitcoind.BlockStatsResponse, error)
	}
)

// Globals
var (
	version, gitHash string
	// Accessing bitcoinclient
	btcClient BitcoinClient

	conf           common.Config
	showVersion    = flag.Bool("version", false, "Show version and exit")
	configFilePath = flag.String("config", common.DefaultConfigFile, "Path to a config file in TOML format")
)

// Functions

// Init function
func init() {
	flag.Parse()
	versionString := "debug"

	if version != "" && gitHash != "" {
		versionString = fmt.Sprintf("%s (git: %s)", version, gitHash)
	}

	if *showVersion {
		fmt.Println(versionString)
		os.Exit(0)
	}
	log.SetFormatter(&log.TextFormatter{
		FullTimestamp: true,
	})
	// Load configfile
	configFile, err := toml.LoadFile(common.CleanAndExpandPath(*configFilePath))
	// Config file
	if err != nil {
		panic(fmt.Errorf("unable to load %s:\n\t%w", *configFilePath, err))
	}
	err = configFile.Unmarshal(&conf)
	if err != nil {
		panic(fmt.Errorf("unable to process %s:\n\t%w", *configFilePath, err))
	}
	// set up logfile
	if conf.LogFile == "" {
		conf.LogFile = common.DefaultLogFile
	}
	fields := log.Fields{
		"version":   versionString,
		"log-file":  conf.LogFile,
		"conf-file": *configFilePath,
	}
	if conf.LogFile != "none" {
		log.SetOutput(&lumberjack.Logger{
			Filename:  common.CleanAndExpandPath(conf.LogFile),
			LocalTime: true,
			Compress:  true,
		})
		log.SetFormatter(&log.JSONFormatter{
			PrettyPrint: false, // so 'jq' always works in 'tail -f'
		})
		log.WithFields(fields).Println("server started")
	}
	// if bitcoin client enabled
	if conf.BitcoinClient {
		btcClient, err = bitcoind.New(conf.Bitcoind)
		if err != nil {
			panic(err)
		}
	}
}

// Test endpoint
func info(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

// JWT Endpoints
// Sign in
func signin(c *gin.Context) {
	if c.GetHeader("JWT") != "" {
		validate_key, err := jwt.ValidateKey(conf.JWTConfig.PrivKeyStore, c.GetHeader("JWT"))
		if validate_key == "valid" {
			c.JSON(200, gin.H{
				"message":   "OK",
				"signed_in": true,
			})
		} else {
			c.JSON(200, gin.H{
				"message":   fmt.Sprintf("Sign in token not valid: %s", err),
				"signed_in": false,
			})
		}
		return
	} else {
		fmt.Println("No JWT Header set, lets validate username and password")
	}
	if c.PostForm("username") != "" && c.PostForm("password") != "" {
		// todo: validate username and password
		var signed_key string = jwt.SignKey(conf.JWTConfig.PrivKeyStore, c.PostForm("username"))
		c.JSON(200, gin.H{
			"message": "OK",
			"jwt":     signed_key,
		})
	} else {
		c.JSON(401, gin.H{
			"message": "Please specify a 'username' and 'password'",
		})
	}
}

// Bitcoin endpoints
// begin: bitcoin functions
func blockCount(c *gin.Context) {
	blockcount, err := btcClient.BlockCount()
	if err != nil {
		c.JSON(500, gin.H{
			"message": "Can't get blockchain count",
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "OK",
		"count":   blockcount,
	})
}

func blockchainInfo(c *gin.Context) {
	blockchainInforesp, err := btcClient.BlockchainInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"message": "Can't get blockchain info",
		})
		return
	}

	c.JSON(200, gin.H{
		"message":        "OK",
		"blockchaininfo": blockchainInforesp,
	})
}
func networkInfo(c *gin.Context) {
	networkInfoResp, err := btcClient.NetworkInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"message": "Can't get network info",
		})
		return
	}
	c.JSON(200, gin.H{
		"message":     "OK",
		"networkinfo": networkInfoResp,
	})
}
func miningInfo(c *gin.Context) {
	miningInfoResp, err := btcClient.GetMiningInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Can't get mining info: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message":    "OK",
		"mininginfo": miningInfoResp,
	})
}

func blockchainTxInfo(c *gin.Context) {
	txInforesp, err := btcClient.GetTransactionInfo(c.Param("id"))
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Can't access transaction index: %s", err),
		})
		return
	}

	c.JSON(200, gin.H{
		"message": "OK",
		"txinfo":  txInforesp,
	})
}
func mempoolContents(c *gin.Context) {
	// GetMempoolContents() (mempoolcontents []string, err error)
	mempoolInfo, err := btcClient.GetMempoolContents()
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Can't access mempool: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "OK",
		"mempool": mempoolInfo,
	})
}
func pushTransaction(c *gin.Context) {
	// PushTransaction(hex string) (txid string, err error)
	pushTxRes, err := btcClient.PushTransaction(c.PostForm("hex"))
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Can't broadcast transaction: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "OK",
		"txid":    pushTxRes,
	})
}
func getBestBlockHash(c *gin.Context) {
	// GetBestBlockHash() (blockhash string, err error)
	bestblock, err := btcClient.GetBestBlockHash()
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting the block hash: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message":   "OK",
		"blockhash": bestblock,
	})
}

// get blockhash by height
func getBlockHashByHeight(c *gin.Context) {
	// GetBlockHashByHeight(height int64) (blockhash string, err error)
	heightInt, errtoInt := strconv.ParseInt(c.Param("id"), 10, 64)
	if errtoInt != nil {
		c.JSON(500, gin.H{
			"message": "Error converting input to integer",
		})
		return
	}
	blockhash, err := btcClient.GetBlockHashByHeight(heightInt)
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting the block hash: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message":   "OK",
		"blockhash": blockhash,
	})
}

// get Block info
func getBlock(c *gin.Context) {
	// GetBlock(hash string) (blockinfo BitcoinBlockResponse, err error)
	bitcoinblock, err := btcClient.GetBlock(c.Param("id"))
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting block: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "OK",
		"block":   bitcoinblock,
	})
}
func getBlockStats(c *gin.Context) {
	// GetBlockStats(int64) (bitcoind.BlockStatsResponse, error)
	blockHeight, blockIdErr := strconv.ParseInt(c.Param("id"), 10, 64)
	if blockIdErr != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error converting param to block height: %s", blockIdErr),
		})
		return
	}
	blockstats, err := btcClient.GetBlockStats(blockHeight)
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting block stats: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message":    "OK",
		"blockstats": blockstats,
	})
}

// mempool info
func getMempoolInfo(c *gin.Context) {
	// GetMempoolInfo() (mempoolinfo bitcoind.MempoolInfoResponse, err error)
	mempool, err := btcClient.GetMempoolInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting mempool info: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "OK",
		"mempool": mempool,
	})
}

// peer info
func getPeerInfo(c *gin.Context) {
	// GetPeerInfo() ([]bitcoind.PeerInfo, error)
	peerinfo, err := btcClient.GetPeerInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error getting peer info: %s", err),
		})
		return
	}
	c.JSON(200, gin.H{
		"peerinfo": peerinfo,
		"message":  "OK",
	})
}

// index endpoint
// PinePhone Endpoints
func batStatus(c *gin.Context) {
	c.JSON(200, gin.H{
		"status": pineclient.GetStatus(),
	})
}

func batCapacity(c *gin.Context) {
	c.JSON(200, gin.H{
		"percent": pineclient.GetCapacity(),
	})
}
func cpuTemp(c *gin.Context) {
	c.JSON(200, gin.H{
		"cputemp": pineclient.GetCPUTemp(),
	})
}
func gpuTemp(c *gin.Context) {
	c.JSON(200, gin.H{
		"gputemp": pineclient.GetGPUTemp(),
	})
}

// querystring test
func testQueryString(c *gin.Context) {
	param1 := c.DefaultQuery("param1", "none")
	if param1 == "none" {
		c.JSON(200, gin.H{
			"message": "show this message if there is no query string",
		})
	} else {
		c.JSON(200, gin.H{
			"message": param1,
		})
	}
}

// BTC Price
func getBtcPrice(c *gin.Context) {
	price, err := btcprice.GetPriceFeed(conf)
	if err != nil {
		c.JSON(500, gin.H{
			"message": fmt.Sprintf("Error reading price: %s", err),
		})
	} else {
		// return string (GetPriceFeed actually returns []byte
		c.String(200, string(price))
	}
}

// Main entrypoint
func main() {
	router := gin.Default()
	router.Use(cors.Default())
	router.Use(gzip.Gzip(gzip.DefaultCompression))
	r := router.Group("/api")
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, common.FormatRoutes(router.Routes()))
	})
	r.GET("/info", info)
	if conf.BitcoinClient {
		fmt.Println("Bitcoin client enabled")
		r.GET("/test", testQueryString)
		// Bitcoin Blockchain Querying
		r.GET("/blocks", blockCount)                    // blockcount
		r.GET("/blockchaininfo", blockchainInfo)        // blockchainInfo
		r.GET("/networkinfo", networkInfo)              // networkInfo
		r.GET("/mempoolinfo", getMempoolInfo)           // get mempool stats
		r.GET("/mininginfo", miningInfo)                // mininginfo
		r.GET("/peerinfo", getPeerInfo)                 // peerinfo
		r.GET("/txid/:id", blockchainTxInfo)            // txid
		r.GET("/mempool", mempoolContents)              // mempool contents
		r.POST("/pushtx", pushTransaction)              // Push transaction
		r.GET("/getblockhash", getBestBlockHash)        // Get best blockhash
		r.GET("/blockheight/:id", getBlockHashByHeight) // get blockhash by height
		r.GET("/block/:id", getBlock)                   // getBlock
		r.GET("/blockstats/:id", getBlockStats)         // getBlockStats
		// BTC Price API
		r.GET("/btcprice", getBtcPrice)
	} else {
		fmt.Println("Bitcoin client not enabled")
	}
	if conf.AuthScheme == "JWT" {
		fmt.Println("Authentication endpoints")
		r.POST("login", signin) // Signin Endpoint
	}
	// Pinephone stuff
	r.GET("/batteryStatus", batStatus)
	r.GET("/batteryCapacity", batCapacity)
	r.GET("/cpuTemp", cpuTemp)
	r.GET("/gpuTemp", gpuTemp)
	if conf.Port == 0 {
		conf.Port = 8080
	}
	var staticFilePath string
	if conf.StaticDir != "" {
		staticFilePath = path.Join(conf.StaticDir, "index.html")
		fmt.Println(conf.StaticDir)
		fmt.Println(staticFilePath)
		router.StaticFile("/", common.CleanAndExpandPath(staticFilePath))
	}
	log.WithFields(log.Fields{
		"routes":      common.FormatRoutes(router.Routes()),
		"port":        conf.Port,
		"static-file": staticFilePath,
	}).Println("gin router defined")
	err := router.Run(fmt.Sprintf(":%d", conf.Port))

	if err != nil {
		panic(err)
	}
}

license: Unlicense


text:
% This file was created with JabRef 2.10.
% Encoding: Cp1252

@Book{montecarlofineng,
  Title                    = {[FURTHER READING] Monte Carlo Methods in Financial Engineering},
  Author                   = {P. Glasserman},
  Publisher                = {Springer},
  Year                     = {2003}
}

@Book{intelligentinvestor,
  Title                    = {The Intelligent Investor},
  Author                   = {Benjamin Graham},
  Publisher                = {Harper Business},
  Year                     = {1973},
  Edition                  = {Fourth Revised}
}

@Book{pyfinanceoreilly,
  Title                    = {Python for Finance},
  Author                   = {Yves Hilpisch},
  Publisher                = {O'Reilly Media Inc},
  Year                     = {2014}
}

@Online{fundamentalanalysis,
  Title                    = {Fundamental Analysis},
  Author                   = {investopedia.com},
  Url                      = {http://www.investopedia.com/university/fundamentalanalysis/}
}

@Online{investing101,
  Title                    = {Investing 101},
  Author                   = {investopedia.com},
  Url                      = {http://www.investopedia.com/university/beginner/}
}

@Online{stockbasics,
  Title                    = {Stock Basics},
  Author                   = {investopedia.com},
  Url                      = {http://www.investopedia.com/university/stocks/}
}

@Book{mathsoffinderivs,
  Title                    = {[FURTHER READING] The Mathematics of Financial Derivatives: A Student Introduction},
  Author                   = {P. Wilmot, S. Howison, J. Dewynne},
  Publisher                = {Cambridge University Press},
  Year                     = {1995}
}

@Book{advancedquantcpp,
  Title                    = {Advanced Quantative Finance With C++},
  Author                   = {Alonso Pena},
  Publisher                = {Packt Publishing},
  Year                     = {2014}
}

@Book{fooledbyrandomness,
  Title                    = {Fooled By Randomness},
  Author                   = {Nicholas Nasim Taleb},
  Publisher                = {Penguin},
  Year                     = {2005}
}

@comment{jabref-entrytype: Online: req[author;title;url] opt[comment;note;year]}

repository: will-hart/interesting-notes

repo_name: will-hart/interesting-notes


text:
DESCRIPTION = "Tools for Cuberevo"
SECTION = "base"
PRIORITY = "required"
LICENSE = "proprietary"
MAINTAINER = "Felix Domke <tmbinc@elitedvb.net>"

KV_cuberevo = "${@base_contains('PREFERRED_VERSION_linux-cuberevo', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo', '2.6.23', '20110522', '20090820', d)}"

#KV_cuberevo = "${@base_contains('PREFERRED_VERSION_linux-cuberevo', '2.6.17', '2.6.17.14_stm22_0041', '2.6.30', d)}"
#PV_cuberevo = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo', '2.6.17', '20110522', '20090820', d)}"

KV_cuberevo-100hd = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-100hd', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-100hd = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-100hd', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-mini-fta = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini-fta', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-mini-fta = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini-fta', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-250hd = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-250hd', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-250hd = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-250hd', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-2000hd = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-2000hd', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-2000hd = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-2000hd', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-9500hd = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-9500hd', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-9500hd = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-9500hd', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-mini = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-mini = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini', '2.6.23', '20110522', '20090820', d)}"

KV_cuberevo-mini2 = "${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini2', '2.6.23', '2.6.23.17_stm23_0123', '2.6.30', d)}"
PV_cuberevo-mini2 = "${KV}-${@base_contains('PREFERRED_VERSION_linux-cuberevo-mini2', '2.6.23', '20110522', '20090820', d)}"

RDEPENDS = "kernel (${KV}) ffmpeg libass "

#hack for broken busybox depmod (v4l-dvb dvb-core isn't automatically loaded on cpu load)
DEPENDS = " module-init-tools ffmpeg libass "

RDEPENDS_append_cuberevo = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-100hd = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-mini-fta = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-250hd = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-2000hd = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-9500hd = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-mini = " module-init-tools-depmod"
RDEPENDS_append_cuberevo-mini2 = " module-init-tools-depmod"

PR = "r7"
GCC ?= ""

SRC_URI = "http://enigma2.sifteam.eu/tmp/opencuberevo/cuberevo-dvb-tools-${MACHINE}-${PV}${GCC}.tar.bz2 \
			file://showiframe.c \
			file://showiframe.pro"

inherit qmake

UTILS = "showiframe"

S = "${WORKDIR}/showiframe2"

TOOLSBIN = "cubefpctl devinit eplayer3 grab hdmi-control hdmi-info rset shmE2 stfbcontrol stfbset streamproxy ustslave vdstandby"

do_configure_prepend() {
        install -d ${S}/
        install -d ${S}/showiframe/
        cd ${S}/
        echo "TEMPLATE=subdirs" > dmutils.pro
        echo "CONFIG=console" >> dmutils.pro
        echo "SUBDIRS=${UTILS}" >> dmutils.pro
        install -m 0644 ${WORKDIR}/showiframe.c ${S}/showiframe/
        install -m 0644 ${WORKDIR}/showiframe.pro ${S}/showiframe/
}

do_install() {
        install -d ${D}/bin/
        install -d ${D}/lib/
        install -d ${D}/lib/firmware/
        install -d ${D}/usr/lib/
        for i in ${TOOLSBIN}; do
                install -m 0755 ${WORKDIR}/$i ${D}/bin/$i;
        done;
        install -d ${D}/${bindir}/
        for u in ${UTILS}
        do
                install -m 0755 ${S}/${u}/${u} ${D}/${bindir}/
        done
#       install -m 0755 ${WORKDIR}/showiframe ${D}/${bindir}/
        install -m 0755 ${WORKDIR}/libdvbsi++.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/usr/lib/libdvbsi++.so.0.0.0
        install -m 0755 ${WORKDIR}/libdreamdvd.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/usr/lib/libdreamdvd.so.0.0.0
        install -m 0755 ${WORKDIR}/libeplayer3.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libeplayer3.so.0.0.0
        [ ! -f "${STAGING_DIR}/${HOST_SYS}/lib/libeplayer3.so.0" ] && ln -s libeplayer3.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libeplayer3.so.0
        [ ! -f "${STAGING_DIR}/${HOST_SYS}/lib/libeplayer3.so" ] && ln -s libeplayer3.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libeplayer3.so
        install -m 0755 ${WORKDIR}/libmmeimage.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libmmeimage.so.0.0.0
        [ ! -f "${STAGING_DIR}/${HOST_SYS}/lib/libmmeimage.so.0" ] && ln -s libmmeimage.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libmmeimage.so.0
        [ ! -f "${STAGING_DIR}/${HOST_SYS}/lib/libmmeimage.so" ] && ln -s libmmeimage.so.0.0.0 ${STAGING_DIR}/${HOST_SYS}/lib/libmmeimage.so
        install -m 0755 ${WORKDIR}/libeplayer3.so.0.0.0 ${D}/lib/libeplayer3.so.0.0.0
        ln -s libeplayer3.so.0.0.0 ${D}/lib/libeplayer3.so.0
        ln -s libeplayer3.so.0.0.0 ${D}/lib/libeplayer3.so
        install -m 0755 ${WORKDIR}/libmmeimage.so.0.0.0 ${D}/lib/libmmeimage.so.0.0.0
        ln -s libmmeimage.so.0.0.0 ${D}/lib/libmmeimage.so.0
        ln -s libmmeimage.so.0.0.0 ${D}/lib/libmmeimage.so
        install -m 0755 ${WORKDIR}/libdreamdvd.so.0.0.0 ${D}/usr/lib/libdreamdvd.so.0.0.0
        install -m 0755 ${WORKDIR}/libdvbsi++.so.0.0.0 ${D}/usr/lib/libdvbsi++.so.0.0.0
        install -m 0755 ${WORKDIR}/dvb-fe-cx24116.fw ${D}/lib/firmware/dvb-fe-cx24116.fw
        install -m 0755 ${WORKDIR}/audio.elf ${D}/lib/firmware/audio.elf
        install -m 0755 ${WORKDIR}/video.elf ${D}/lib/firmware/video.elf
}

PACKAGE_ARCH := "${MACHINE_ARCH}"
FILES_${PN} = "/"

repository: popazerty/openembedded-cuberevo

repo_name: popazerty/openembedded-cuberevo


text:
DESCRIPTION = "User-level tools for ReiserFS filesystems"
SECTION = "base"
LICENSE = "GPL"
RRECOMMENDS_${PN} = "reiserfsprogs-reiserfsck reiserfsprogs-mkreiserfs"
PR = "r1"

SRC_URI ="ftp://ftp.namesys.com/pub/reiserfsprogs/reiserfsprogs-${PV}.tar.gz \
	  file://header-fix.patch;patch=1 \
	  "

S = "${WORKDIR}/reiserfsprogs-${PV}"

inherit autotools

PACKAGES_prepend = "reiserfsprogs-reiserfsck reiserfsprogs-mkreiserfs "
FILES_reiserfsprogs-reiserfsck = "${sbindir}/reiserfsck"
FILES_reiserfsprogs-mkreiserfs = "${sbindir}/mkreiserfs"

repository: jdegges/gumstix-pip-oe

repo_name: jdegges/gumstix-pip-oe