code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package utils
import (
"encoding/json"
"github.com/crawlab-team/crawlab/core/interfaces"
)
func GetResultHash(value interface{}, keys []string) (res string, err error) {
m := make(map[string]interface{})
for _, k := range keys {
_value, ok := value.(interfaces.Result)
if !ok {
continue
}
v := _value.GetValue(k)
m[k] = v
}
data, err := json.Marshal(m)
if err != nil {
return "", err
}
return EncryptMd5(string(data)), nil
}
|
2302_79757062/crawlab
|
core/utils/result.go
|
Go
|
bsd-3-clause
| 451
|
package utils
import "encoding/json"
// Object 转化为 String
func ObjectToString(params interface{}) string {
bytes, _ := json.Marshal(params)
return BytesToString(bytes)
}
// 获取 RPC 参数
func GetRpcParam(key string, params map[string]string) string {
return params[key]
}
|
2302_79757062/crawlab
|
core/utils/rpc.go
|
Go
|
bsd-3-clause
| 288
|
package utils
func GetSpiderCol(col string, name string) string {
if col == "" {
return "results_" + name
}
return col
}
|
2302_79757062/crawlab
|
core/utils/spider.go
|
Go
|
bsd-3-clause
| 127
|
package utils
import (
"github.com/crawlab-team/crawlab/db/generic"
"github.com/upper/db/v4"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func GetSqlQuery(query generic.ListQuery) (res db.Cond) {
res = db.Cond{}
for _, c := range query {
switch c.Value.(type) {
case primitive.ObjectID:
c.Value = c.Value.(primitive.ObjectID).Hex()
}
switch c.Op {
case generic.OpEqual:
res[c.Key] = c.Value
default:
res[c.Key] = db.Cond{
c.Op: c.Value,
}
}
}
// TODO: sort
return res
}
|
2302_79757062/crawlab
|
core/utils/sql.go
|
Go
|
bsd-3-clause
| 512
|
package utils
import (
"context"
"github.com/crawlab-team/crawlab/core/models/models"
"github.com/upper/db/v4"
"github.com/upper/db/v4/adapter/sqlite"
"time"
)
func GetSqliteSession(ds *models.DataSource) (s db.Session, err error) {
return getSqliteSession(context.Background(), ds)
}
func GetSqliteSessionWithTimeout(ds *models.DataSource, timeout time.Duration) (s db.Session, err error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return getSqliteSession(ctx, ds)
}
func getSqliteSession(ctx context.Context, ds *models.DataSource) (s db.Session, err error) {
// connect settings
settings := sqlite.ConnectionURL{
Database: ds.Database,
Options: nil,
}
// session
done := make(chan struct{})
go func() {
s, err = sqlite.Open(settings)
close(done)
}()
// wait for done
select {
case <-ctx.Done():
if ctx.Err() != nil {
err = ctx.Err()
}
case <-done:
}
return s, err
}
|
2302_79757062/crawlab
|
core/utils/sqlite.go
|
Go
|
bsd-3-clause
| 954
|
package utils
|
2302_79757062/crawlab
|
core/utils/stats.go
|
Go
|
bsd-3-clause
| 14
|
package utils
import "github.com/spf13/viper"
func IsPro() bool {
return viper.GetString("info.edition") == "global.edition.pro"
}
|
2302_79757062/crawlab
|
core/utils/system.go
|
Go
|
bsd-3-clause
| 134
|
package utils
import "github.com/crawlab-team/crawlab/core/constants"
func IsCancellable(status string) bool {
switch status {
case constants.TaskStatusPending,
constants.TaskStatusRunning:
return true
default:
return false
}
}
|
2302_79757062/crawlab
|
core/utils/task.go
|
Go
|
bsd-3-clause
| 240
|
package utils
import (
"time"
)
func GetLocalTime(t time.Time) time.Time {
return t.In(time.Local)
}
func GetTimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
func GetLocalTimeString(t time.Time) string {
t = GetLocalTime(t)
return GetTimeString(t)
}
|
2302_79757062/crawlab
|
core/utils/time.go
|
Go
|
bsd-3-clause
| 284
|
package utils
import "github.com/google/uuid"
func NewUUIDString() (res string) {
id, _ := uuid.NewUUID()
return id.String()
}
|
2302_79757062/crawlab
|
core/utils/uuid.go
|
Go
|
bsd-3-clause
| 131
|
package errors
const (
errorPrefixMongo = "mongo"
errorPrefixRedis = "redis"
)
|
2302_79757062/crawlab
|
db/errors/base.go
|
Go
|
bsd-3-clause
| 82
|
package errors
import "errors"
var (
ErrInvalidType = errors.New("invalid type")
ErrMissingValue = errors.New("missing value")
ErrNoCursor = errors.New("no cursor")
ErrAlreadyLocked = errors.New("already locked")
)
|
2302_79757062/crawlab
|
db/errors/errors.go
|
Go
|
bsd-3-clause
| 229
|
package errors
import (
"errors"
"fmt"
)
var (
ErrorRedisInvalidType = NewRedisError("invalid type")
ErrorRedisLocked = NewRedisError("locked")
)
func NewRedisError(msg string) (err error) {
return errors.New(fmt.Sprintf("%s: %s", errorPrefixRedis, msg))
}
|
2302_79757062/crawlab
|
db/errors/redis.go
|
Go
|
bsd-3-clause
| 270
|
package generic
const (
DataSourceTypeMongo = "mongo"
DataSourceTypeMysql = "mysql"
DataSourceTypePostgres = "postgres"
DataSourceTypeElasticSearch = "postgres"
)
|
2302_79757062/crawlab
|
db/generic/base.go
|
Go
|
bsd-3-clause
| 189
|
package generic
type ListQueryCondition struct {
Key string
Op string
Value interface{}
}
type ListQuery []ListQueryCondition
type ListOptions struct {
Skip int
Limit int
Sort []ListSort
}
|
2302_79757062/crawlab
|
db/generic/list.go
|
Go
|
bsd-3-clause
| 205
|
package generic
type Op string
const (
OpEqual = "eq"
)
|
2302_79757062/crawlab
|
db/generic/op.go
|
Go
|
bsd-3-clause
| 59
|
package generic
type SortDirection string
const (
SortDirectionAsc SortDirection = "asc"
SortDirectionDesc SortDirection = "desc"
)
type ListSort struct {
Key string
Direction SortDirection
}
|
2302_79757062/crawlab
|
db/generic/sort.go
|
Go
|
bsd-3-clause
| 206
|
package db
import "time"
type RedisClient interface {
Ping() (err error)
Keys(pattern string) (values []string, err error)
AllKeys() (values []string, err error)
Get(collection string) (value string, err error)
Set(collection string, value string) (err error)
Del(collection string) (err error)
RPush(collection string, value interface{}) (err error)
LPush(collection string, value interface{}) (err error)
LPop(collection string) (value string, err error)
RPop(collection string) (value string, err error)
LLen(collection string) (count int, err error)
BRPop(collection string, timeout int) (value string, err error)
BLPop(collection string, timeout int) (value string, err error)
HSet(collection string, key string, value string) (err error)
HGet(collection string, key string) (value string, err error)
HDel(collection string, key string) (err error)
HScan(collection string) (results map[string]string, err error)
HKeys(collection string) (results []string, err error)
ZAdd(collection string, score float32, value interface{}) (err error)
ZCount(collection string, min string, max string) (count int, err error)
ZCountAll(collection string) (count int, err error)
ZScan(collection string, pattern string, count int) (results []string, err error)
ZPopMax(collection string, count int) (results []string, err error)
ZPopMin(collection string, count int) (results []string, err error)
ZPopMaxOne(collection string) (value string, err error)
ZPopMinOne(collection string) (value string, err error)
BZPopMax(collection string, timeout int) (value string, err error)
BZPopMin(collection string, timeout int) (value string, err error)
Lock(lockKey string) (value int64, err error)
UnLock(lockKey string, value int64)
MemoryStats() (stats map[string]int64, err error)
SetBackoffMaxInterval(interval time.Duration)
SetTimeout(timeout int)
}
|
2302_79757062/crawlab
|
db/interfaces.go
|
Go
|
bsd-3-clause
| 1,871
|
package mongo
import (
"context"
"encoding/json"
"fmt"
"github.com/apex/log"
"github.com/cenkalti/backoff/v4"
"github.com/crawlab-team/crawlab/trace"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"sync"
)
var AppName = "crawlab-db"
var _clientMap = map[string]*mongo.Client{}
var _mu sync.Mutex
func GetMongoClient(opts ...ClientOption) (c *mongo.Client, err error) {
// client options
_opts := &ClientOptions{}
for _, op := range opts {
op(_opts)
}
if _opts.Uri == "" {
_opts.Uri = viper.GetString("mongo.uri")
}
if _opts.Host == "" {
_opts.Host = viper.GetString("mongo.host")
if _opts.Host == "" {
_opts.Host = "localhost"
}
}
if _opts.Port == "" {
_opts.Port = viper.GetString("mongo.port")
if _opts.Port == "" {
_opts.Port = "27017"
}
}
if _opts.Db == "" {
_opts.Db = viper.GetString("mongo.db")
if _opts.Db == "" {
_opts.Db = "admin"
}
}
if len(_opts.Hosts) == 0 {
_opts.Hosts = viper.GetStringSlice("mongo.hosts")
}
if _opts.Username == "" {
_opts.Username = viper.GetString("mongo.username")
}
if _opts.Password == "" {
_opts.Password = viper.GetString("mongo.password")
}
if _opts.AuthSource == "" {
_opts.AuthSource = viper.GetString("mongo.authSource")
if _opts.AuthSource == "" {
_opts.AuthSource = "admin"
}
}
if _opts.AuthMechanism == "" {
_opts.AuthMechanism = viper.GetString("mongo.authMechanism")
}
if _opts.AuthMechanismProperties == nil {
_opts.AuthMechanismProperties = viper.GetStringMapString("mongo.authMechanismProperties")
}
// client options key json string
_optsKeyBytes, err := json.Marshal(_opts)
if err != nil {
return nil, trace.TraceError(err)
}
_optsKey := string(_optsKeyBytes)
// attempt to get client by client options
c, ok := _clientMap[_optsKey]
if ok {
return c, nil
}
// create new mongo client
c, err = newMongoClient(_opts.Context, _opts)
if err != nil {
return nil, err
}
// add to map
_mu.Lock()
_clientMap[_optsKey] = c
_mu.Unlock()
return c, nil
}
func newMongoClient(ctx context.Context, _opts *ClientOptions) (c *mongo.Client, err error) {
// mongo client options
mongoOpts := &options.ClientOptions{
AppName: &AppName,
}
if _opts.Uri != "" {
// uri is set
mongoOpts.ApplyURI(_opts.Uri)
} else {
// uri is unset
// username and password are set
if _opts.Username != "" && _opts.Password != "" {
mongoOpts.SetAuth(options.Credential{
AuthMechanism: _opts.AuthMechanism,
AuthMechanismProperties: _opts.AuthMechanismProperties,
AuthSource: _opts.AuthSource,
Username: _opts.Username,
Password: _opts.Password,
PasswordSet: true,
})
}
if len(_opts.Hosts) > 0 {
// hosts are set
mongoOpts.SetHosts(_opts.Hosts)
} else {
// hosts are unset
mongoOpts.ApplyURI(fmt.Sprintf("mongodb://%s:%s/%s", _opts.Host, _opts.Port, _opts.Db))
}
}
// attempt to connect with retry
bp := backoff.NewExponentialBackOff()
err = backoff.Retry(func() error {
errMsg := fmt.Sprintf("waiting for connect mongo database, after %f seconds try again.", bp.NextBackOff().Seconds())
c, err = mongo.NewClient(mongoOpts)
if err != nil {
log.WithError(err).Warnf(errMsg)
return err
}
if err := c.Connect(ctx); err != nil {
log.WithError(err).Warnf(errMsg)
return err
}
return nil
}, bp)
return c, nil
}
|
2302_79757062/crawlab
|
db/mongo/client.go
|
Go
|
bsd-3-clause
| 3,462
|
package mongo
import "context"
type ClientOption func(options *ClientOptions)
type ClientOptions struct {
Context context.Context
Uri string
Host string
Port string
Db string
Hosts []string
Username string
Password string
AuthSource string
AuthMechanism string
AuthMechanismProperties map[string]string
}
func WithContext(ctx context.Context) ClientOption {
return func(options *ClientOptions) {
options.Context = ctx
}
}
func WithUri(value string) ClientOption {
return func(options *ClientOptions) {
options.Uri = value
}
}
func WithHost(value string) ClientOption {
return func(options *ClientOptions) {
options.Host = value
}
}
func WithPort(value string) ClientOption {
return func(options *ClientOptions) {
options.Port = value
}
}
func WithDb(value string) ClientOption {
return func(options *ClientOptions) {
options.Db = value
}
}
func WithHosts(value []string) ClientOption {
return func(options *ClientOptions) {
options.Hosts = value
}
}
func WithUsername(value string) ClientOption {
return func(options *ClientOptions) {
options.Username = value
}
}
func WithPassword(value string) ClientOption {
return func(options *ClientOptions) {
options.Password = value
}
}
func WithAuthSource(value string) ClientOption {
return func(options *ClientOptions) {
options.AuthSource = value
}
}
func WithAuthMechanism(value string) ClientOption {
return func(options *ClientOptions) {
options.AuthMechanism = value
}
}
|
2302_79757062/crawlab
|
db/mongo/client_options.go
|
Go
|
bsd-3-clause
| 1,650
|
package mongo
import (
"context"
"github.com/crawlab-team/crawlab/db/errors"
"github.com/crawlab-team/crawlab/trace"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ColInterface interface {
Insert(doc interface{}) (id primitive.ObjectID, err error)
InsertMany(docs []interface{}) (ids []primitive.ObjectID, err error)
UpdateId(id primitive.ObjectID, update interface{}) (err error)
Update(query bson.M, update interface{}) (err error)
UpdateWithOptions(query bson.M, update interface{}, opts *options.UpdateOptions) (err error)
ReplaceId(id primitive.ObjectID, doc interface{}) (err error)
Replace(query bson.M, doc interface{}) (err error)
ReplaceWithOptions(query bson.M, doc interface{}, opts *options.ReplaceOptions) (err error)
DeleteId(id primitive.ObjectID) (err error)
Delete(query bson.M) (err error)
DeleteWithOptions(query bson.M, opts *options.DeleteOptions) (err error)
Find(query bson.M, opts *FindOptions) (fr *FindResult)
FindId(id primitive.ObjectID) (fr *FindResult)
Count(query bson.M) (total int, err error)
Aggregate(pipeline mongo.Pipeline, opts *options.AggregateOptions) (fr *FindResult)
CreateIndex(indexModel mongo.IndexModel) (err error)
CreateIndexes(indexModels []mongo.IndexModel) (err error)
MustCreateIndex(indexModel mongo.IndexModel)
MustCreateIndexes(indexModels []mongo.IndexModel)
DeleteIndex(name string) (err error)
DeleteAllIndexes() (err error)
ListIndexes() (indexes []map[string]interface{}, err error)
GetContext() (ctx context.Context)
GetName() (name string)
GetCollection() (c *mongo.Collection)
}
type FindOptions struct {
Skip int
Limit int
Sort bson.D
}
type Col struct {
ctx context.Context
db *mongo.Database
c *mongo.Collection
}
func (col *Col) Insert(doc interface{}) (id primitive.ObjectID, err error) {
res, err := col.c.InsertOne(col.ctx, doc)
if err != nil {
return primitive.NilObjectID, trace.TraceError(err)
}
if id, ok := res.InsertedID.(primitive.ObjectID); ok {
return id, nil
}
return primitive.NilObjectID, trace.TraceError(errors.ErrInvalidType)
}
func (col *Col) InsertMany(docs []interface{}) (ids []primitive.ObjectID, err error) {
res, err := col.c.InsertMany(col.ctx, docs)
if err != nil {
return nil, trace.TraceError(err)
}
for _, v := range res.InsertedIDs {
switch v.(type) {
case primitive.ObjectID:
id := v.(primitive.ObjectID)
ids = append(ids, id)
default:
return nil, trace.TraceError(errors.ErrInvalidType)
}
}
return ids, nil
}
func (col *Col) UpdateId(id primitive.ObjectID, update interface{}) (err error) {
_, err = col.c.UpdateOne(col.ctx, bson.M{"_id": id}, update)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) Update(query bson.M, update interface{}) (err error) {
return col.UpdateWithOptions(query, update, nil)
}
func (col *Col) UpdateWithOptions(query bson.M, update interface{}, opts *options.UpdateOptions) (err error) {
if opts == nil {
_, err = col.c.UpdateMany(col.ctx, query, update)
} else {
_, err = col.c.UpdateMany(col.ctx, query, update, opts)
}
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) ReplaceId(id primitive.ObjectID, doc interface{}) (err error) {
return col.Replace(bson.M{"_id": id}, doc)
}
func (col *Col) Replace(query bson.M, doc interface{}) (err error) {
return col.ReplaceWithOptions(query, doc, nil)
}
func (col *Col) ReplaceWithOptions(query bson.M, doc interface{}, opts *options.ReplaceOptions) (err error) {
if opts == nil {
_, err = col.c.ReplaceOne(col.ctx, query, doc)
} else {
_, err = col.c.ReplaceOne(col.ctx, query, doc, opts)
}
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) DeleteId(id primitive.ObjectID) (err error) {
_, err = col.c.DeleteOne(col.ctx, bson.M{"_id": id})
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) Delete(query bson.M) (err error) {
return col.DeleteWithOptions(query, nil)
}
func (col *Col) DeleteWithOptions(query bson.M, opts *options.DeleteOptions) (err error) {
if opts == nil {
_, err = col.c.DeleteMany(col.ctx, query)
} else {
_, err = col.c.DeleteMany(col.ctx, query, opts)
}
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) Find(query bson.M, opts *FindOptions) (fr *FindResult) {
_opts := &options.FindOptions{}
if opts != nil {
if opts.Skip != 0 {
skipInt64 := int64(opts.Skip)
_opts.Skip = &skipInt64
}
if opts.Limit != 0 {
limitInt64 := int64(opts.Limit)
_opts.Limit = &limitInt64
}
if opts.Sort != nil {
_opts.Sort = opts.Sort
}
}
cur, err := col.c.Find(col.ctx, query, _opts)
if err != nil {
return &FindResult{
col: col,
err: err,
}
}
fr = &FindResult{
col: col,
cur: cur,
}
return fr
}
func (col *Col) FindId(id primitive.ObjectID) (fr *FindResult) {
res := col.c.FindOne(col.ctx, bson.M{"_id": id})
if res.Err() != nil {
return &FindResult{
col: col,
err: res.Err(),
}
}
fr = &FindResult{
col: col,
res: res,
}
return fr
}
func (col *Col) Count(query bson.M) (total int, err error) {
totalInt64, err := col.c.CountDocuments(col.ctx, query)
if err != nil {
return 0, err
}
total = int(totalInt64)
return total, nil
}
func (col *Col) Aggregate(pipeline mongo.Pipeline, opts *options.AggregateOptions) (fr *FindResult) {
cur, err := col.c.Aggregate(col.ctx, pipeline, opts)
if err != nil {
return &FindResult{
col: col,
err: err,
}
}
if cur.Err() != nil {
return &FindResult{
col: col,
err: cur.Err(),
}
}
fr = &FindResult{
col: col,
cur: cur,
}
return fr
}
func (col *Col) CreateIndex(indexModel mongo.IndexModel) (err error) {
_, err = col.c.Indexes().CreateOne(col.ctx, indexModel)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) CreateIndexes(indexModels []mongo.IndexModel) (err error) {
_, err = col.c.Indexes().CreateMany(col.ctx, indexModels)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) MustCreateIndex(indexModel mongo.IndexModel) {
_, _ = col.c.Indexes().CreateOne(col.ctx, indexModel)
}
func (col *Col) MustCreateIndexes(indexModels []mongo.IndexModel) {
_, _ = col.c.Indexes().CreateMany(col.ctx, indexModels)
}
func (col *Col) DeleteIndex(name string) (err error) {
_, err = col.c.Indexes().DropOne(col.ctx, name)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) DeleteAllIndexes() (err error) {
_, err = col.c.Indexes().DropAll(col.ctx)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (col *Col) ListIndexes() (indexes []map[string]interface{}, err error) {
cur, err := col.c.Indexes().List(col.ctx)
if err != nil {
return nil, err
}
if err := cur.All(col.ctx, &indexes); err != nil {
return nil, err
}
return indexes, nil
}
func (col *Col) GetContext() (ctx context.Context) {
return col.ctx
}
func (col *Col) GetName() (name string) {
return col.c.Name()
}
func (col *Col) GetCollection() (c *mongo.Collection) {
return col.c
}
func GetMongoCol(colName string) (col *Col) {
return GetMongoColWithDb(colName, nil)
}
func GetMongoColWithDb(colName string, db *mongo.Database) (col *Col) {
ctx := context.Background()
if db == nil {
db = GetMongoDb("")
}
c := db.Collection(colName)
col = &Col{
ctx: ctx,
db: db,
c: c,
}
return col
}
|
2302_79757062/crawlab
|
db/mongo/col.go
|
Go
|
bsd-3-clause
| 7,517
|
package mongo
import (
"github.com/crawlab-team/crawlab/trace"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
)
func GetMongoDb(dbName string, opts ...DbOption) (db *mongo.Database) {
if dbName == "" {
dbName = viper.GetString("mongo.db")
}
if dbName == "" {
dbName = "test"
}
_opts := &DbOptions{}
for _, op := range opts {
op(_opts)
}
var c *mongo.Client
if _opts.client == nil {
var err error
c, err = GetMongoClient()
if err != nil {
trace.PrintError(err)
return nil
}
} else {
c = _opts.client
}
return c.Database(dbName, nil)
}
|
2302_79757062/crawlab
|
db/mongo/db.go
|
Go
|
bsd-3-clause
| 590
|
package mongo
import "go.mongodb.org/mongo-driver/mongo"
type DbOption func(options *DbOptions)
type DbOptions struct {
client *mongo.Client
}
func WithDbClient(c *mongo.Client) DbOption {
return func(options *DbOptions) {
options.client = c
}
}
|
2302_79757062/crawlab
|
db/mongo/db_options.go
|
Go
|
bsd-3-clause
| 255
|
package mongo
import (
"context"
"github.com/crawlab-team/crawlab/db/errors"
"go.mongodb.org/mongo-driver/mongo"
)
type FindResultInterface interface {
One(val interface{}) (err error)
All(val interface{}) (err error)
GetCol() (col *Col)
GetSingleResult() (res *mongo.SingleResult)
GetCursor() (cur *mongo.Cursor)
GetError() (err error)
}
func NewFindResult() (fr *FindResult) {
return &FindResult{}
}
func NewFindResultWithError(err error) (fr *FindResult) {
return &FindResult{
err: err,
}
}
type FindResult struct {
col *Col
res *mongo.SingleResult
cur *mongo.Cursor
err error
}
func (fr *FindResult) GetError() (err error) {
//TODO implement me
panic("implement me")
}
func (fr *FindResult) One(val interface{}) (err error) {
if fr.err != nil {
return fr.err
}
if fr.cur != nil {
if !fr.cur.TryNext(fr.col.ctx) {
return mongo.ErrNoDocuments
}
return fr.cur.Decode(val)
}
return fr.res.Decode(val)
}
func (fr *FindResult) All(val interface{}) (err error) {
if fr.err != nil {
return fr.err
}
var ctx context.Context
if fr.col == nil {
ctx = context.Background()
} else {
ctx = fr.col.ctx
}
if fr.cur == nil {
return errors.ErrNoCursor
}
if !fr.cur.TryNext(ctx) {
return ctx.Err()
}
return fr.cur.All(ctx, val)
}
func (fr *FindResult) GetCol() (col *Col) {
return fr.col
}
func (fr *FindResult) GetSingleResult() (res *mongo.SingleResult) {
return fr.res
}
func (fr *FindResult) GetCursor() (cur *mongo.Cursor) {
return fr.cur
}
|
2302_79757062/crawlab
|
db/mongo/result.go
|
Go
|
bsd-3-clause
| 1,502
|
package mongo
import (
"context"
"github.com/crawlab-team/crawlab/trace"
"go.mongodb.org/mongo-driver/mongo"
)
func RunTransaction(fn func(mongo.SessionContext) error) (err error) {
return RunTransactionWithContext(context.Background(), fn)
}
func RunTransactionWithContext(ctx context.Context, fn func(mongo.SessionContext) error) (err error) {
// default client
c, err := GetMongoClient()
if err != nil {
return err
}
// start session
s, err := c.StartSession()
if err != nil {
return trace.TraceError(err)
}
// start transaction
if err := s.StartTransaction(); err != nil {
return trace.TraceError(err)
}
// perform operation
if err := mongo.WithSession(ctx, s, func(sc mongo.SessionContext) error {
if err := fn(sc); err != nil {
return trace.TraceError(err)
}
if err = s.CommitTransaction(sc); err != nil {
return trace.TraceError(err)
}
return nil
}); err != nil {
return trace.TraceError(err)
}
return nil
}
|
2302_79757062/crawlab
|
db/mongo/transaction.go
|
Go
|
bsd-3-clause
| 966
|
package redis
import (
"github.com/apex/log"
"github.com/crawlab-team/crawlab/db"
"github.com/crawlab-team/crawlab/db/errors"
"github.com/crawlab-team/crawlab/db/utils"
"github.com/crawlab-team/crawlab/trace"
"github.com/gomodule/redigo/redis"
"reflect"
"strings"
"time"
)
type Client struct {
// settings
backoffMaxInterval time.Duration
timeout int
// internals
pool *redis.Pool
}
func (client *Client) Ping() error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := redis.String(c.Do("PING")); err != nil {
if err != redis.ErrNil {
return trace.TraceError(err)
}
return err
}
return nil
}
func (client *Client) Keys(pattern string) (values []string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err = redis.Strings(c.Do("KEYS", pattern))
if err != nil {
return nil, trace.TraceError(err)
}
return values, nil
}
func (client *Client) AllKeys() (values []string, err error) {
return client.Keys("*")
}
func (client *Client) Get(collection string) (value string, err error) {
c := client.pool.Get()
defer utils.Close(c)
value, err = redis.String(c.Do("GET", collection))
if err != nil {
return "", trace.TraceError(err)
}
return value, nil
}
func (client *Client) Set(collection string, value string) (err error) {
c := client.pool.Get()
defer utils.Close(c)
value, err = redis.String(c.Do("SET", collection, value))
if err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) Del(collection string) error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("DEL", collection); err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) RPush(collection string, value interface{}) error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("RPUSH", collection, value); err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) LPush(collection string, value interface{}) error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("LPUSH", collection, value); err != nil {
if err != redis.ErrNil {
return trace.TraceError(err)
}
return err
}
return nil
}
func (client *Client) LPop(collection string) (string, error) {
c := client.pool.Get()
defer utils.Close(c)
value, err := redis.String(c.Do("LPOP", collection))
if err != nil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
return value, nil
}
func (client *Client) RPop(collection string) (string, error) {
c := client.pool.Get()
defer utils.Close(c)
value, err := redis.String(c.Do("RPOP", collection))
if err != nil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
return value, nil
}
func (client *Client) LLen(collection string) (int, error) {
c := client.pool.Get()
defer utils.Close(c)
value, err := redis.Int(c.Do("LLEN", collection))
if err != nil {
return 0, trace.TraceError(err)
}
return value, nil
}
func (client *Client) BRPop(collection string, timeout int) (value string, err error) {
if timeout <= 0 {
timeout = 60
}
c := client.pool.Get()
defer utils.Close(c)
values, err := redis.Strings(c.Do("BRPOP", collection, timeout))
if err != nil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
return values[1], nil
}
func (client *Client) BLPop(collection string, timeout int) (value string, err error) {
if timeout <= 0 {
timeout = 60
}
c := client.pool.Get()
defer utils.Close(c)
values, err := redis.Strings(c.Do("BLPOP", collection, timeout))
if err != nil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
return values[1], nil
}
func (client *Client) HSet(collection string, key string, value string) error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("HSET", collection, key, value); err != nil {
if err != redis.ErrNil {
return trace.TraceError(err)
}
return err
}
return nil
}
func (client *Client) HGet(collection string, key string) (string, error) {
c := client.pool.Get()
defer utils.Close(c)
value, err := redis.String(c.Do("HGET", collection, key))
if err != nil && err != redis.ErrNil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
return value, nil
}
func (client *Client) HDel(collection string, key string) error {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("HDEL", collection, key); err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) HScan(collection string) (results map[string]string, err error) {
c := client.pool.Get()
defer utils.Close(c)
var (
cursor int64
items []string
)
results = map[string]string{}
for {
values, err := redis.Values(c.Do("HSCAN", collection, cursor))
if err != nil {
if err != redis.ErrNil {
return nil, trace.TraceError(err)
}
return nil, err
}
values, err = redis.Scan(values, &cursor, &items)
if err != nil {
if err != redis.ErrNil {
return nil, trace.TraceError(err)
}
return nil, err
}
for i := 0; i < len(items); i += 2 {
key := items[i]
value := items[i+1]
results[key] = value
}
if cursor == 0 {
break
}
}
return results, nil
}
func (client *Client) HKeys(collection string) (results []string, err error) {
c := client.pool.Get()
defer utils.Close(c)
results, err = redis.Strings(c.Do("HKEYS", collection))
if err != nil {
if err != redis.ErrNil {
return results, trace.TraceError(err)
}
return results, err
}
return results, nil
}
func (client *Client) ZAdd(collection string, score float32, value interface{}) (err error) {
c := client.pool.Get()
defer utils.Close(c)
if _, err := c.Do("ZADD", collection, score, value); err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) ZCount(collection string, min string, max string) (count int, err error) {
c := client.pool.Get()
defer utils.Close(c)
count, err = redis.Int(c.Do("ZCOUNT", collection, min, max))
if err != nil {
return 0, trace.TraceError(err)
}
return count, nil
}
func (client *Client) ZCountAll(collection string) (count int, err error) {
return client.ZCount(collection, "-inf", "+inf")
}
func (client *Client) ZScan(collection string, pattern string, count int) (values []string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err = redis.Strings(c.Do("ZSCAN", collection, 0, pattern, count))
if err != nil {
if err != redis.ErrNil {
return nil, trace.TraceError(err)
}
return nil, err
}
return values, nil
}
func (client *Client) ZPopMax(collection string, count int) (results []string, err error) {
c := client.pool.Get()
defer utils.Close(c)
results = []string{}
values, err := redis.Strings(c.Do("ZPOPMAX", collection, count))
if err != nil {
if err != redis.ErrNil {
return nil, trace.TraceError(err)
}
return nil, err
}
for i := 0; i < len(values); i += 2 {
v := values[i]
results = append(results, v)
}
return results, nil
}
func (client *Client) ZPopMin(collection string, count int) (results []string, err error) {
c := client.pool.Get()
defer utils.Close(c)
results = []string{}
values, err := redis.Strings(c.Do("ZPOPMIN", collection, count))
if err != nil {
if err != redis.ErrNil {
return nil, trace.TraceError(err)
}
return nil, err
}
for i := 0; i < len(values); i += 2 {
v := values[i]
results = append(results, v)
}
return results, nil
}
func (client *Client) ZPopMaxOne(collection string) (value string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err := client.ZPopMax(collection, 1)
if err != nil {
return "", err
}
if values == nil || len(values) == 0 {
return "", nil
}
return values[0], nil
}
func (client *Client) ZPopMinOne(collection string) (value string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err := client.ZPopMin(collection, 1)
if err != nil {
return "", err
}
if values == nil || len(values) == 0 {
return "", nil
}
return values[0], nil
}
func (client *Client) BZPopMax(collection string, timeout int) (value string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err := redis.Strings(c.Do("BZPOPMAX", collection, timeout))
if err != nil {
if err != redis.ErrNil {
return "", trace.TraceError(err)
}
return "", err
}
if len(values) < 3 {
return "", trace.TraceError(errors.ErrorRedisInvalidType)
}
return values[1], nil
}
func (client *Client) BZPopMin(collection string, timeout int) (value string, err error) {
c := client.pool.Get()
defer utils.Close(c)
values, err := redis.Strings(c.Do("BZPOPMIN", collection, timeout))
if err != nil {
if err != redis.ErrNil {
return "", trace.TraceError(err)
}
return "", err
}
if len(values) < 3 {
return "", trace.TraceError(errors.ErrorRedisInvalidType)
}
return values[1], nil
}
func (client *Client) Lock(lockKey string) (value int64, err error) {
c := client.pool.Get()
defer utils.Close(c)
lockKey = client.getLockKey(lockKey)
ts := time.Now().Unix()
ok, err := c.Do("SET", lockKey, ts, "NX", "PX", 30000)
if err != nil {
if err != redis.ErrNil {
return value, trace.TraceError(err)
}
return value, err
}
if ok == nil {
return 0, trace.TraceError(errors.ErrorRedisLocked)
}
return ts, nil
}
func (client *Client) UnLock(lockKey string, value int64) {
c := client.pool.Get()
defer utils.Close(c)
lockKey = client.getLockKey(lockKey)
getValue, err := redis.Int64(c.Do("GET", lockKey))
if err != nil {
log.Errorf("get lockKey error: %s", err.Error())
return
}
if getValue != value {
log.Errorf("the lockKey value diff: %d, %d", value, getValue)
return
}
v, err := redis.Int64(c.Do("DEL", lockKey))
if err != nil {
log.Errorf("unlock failed, error: %s", err.Error())
return
}
if v == 0 {
log.Errorf("unlock failed: key=%s", lockKey)
return
}
}
func (client *Client) MemoryStats() (stats map[string]int64, err error) {
stats = map[string]int64{}
c := client.pool.Get()
defer utils.Close(c)
values, err := redis.Values(c.Do("MEMORY", "STATS"))
for i, v := range values {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Slice {
vc, _ := redis.String(v, err)
if utils.ContainsString(MemoryStatsMetrics, vc) {
stats[vc], _ = redis.Int64(values[i+1], err)
}
}
}
if err != nil {
if err != redis.ErrNil {
return stats, trace.TraceError(err)
}
return stats, err
}
return stats, nil
}
func (client *Client) SetBackoffMaxInterval(interval time.Duration) {
client.backoffMaxInterval = interval
}
func (client *Client) SetTimeout(timeout int) {
client.timeout = timeout
}
func (client *Client) init() (err error) {
b := backoff.NewExponentialBackOff()
b.MaxInterval = client.backoffMaxInterval
if err := backoff.Retry(func() error {
err := client.Ping()
if err != nil {
log.WithError(err).Warnf("waiting for redis pool active connection. will after %f seconds try again.", b.NextBackOff().Seconds())
}
return nil
}, b); err != nil {
return trace.TraceError(err)
}
return nil
}
func (client *Client) getLockKey(lockKey string) string {
lockKey = strings.ReplaceAll(lockKey, ":", "-")
return "nodes:lock:" + lockKey
}
func (client *Client) getTimeout(timeout int) (res int) {
if timeout == 0 {
return client.timeout
}
return timeout
}
var client db.RedisClient
func NewRedisClient(opts ...Option) (client *Client, err error) {
// client
client = &Client{
backoffMaxInterval: 20 * time.Second,
pool: NewRedisPool(),
}
// apply options
for _, opt := range opts {
opt(client)
}
// init
if err := client.init(); err != nil {
return nil, err
}
return client, nil
}
func GetRedisClient() (c db.RedisClient, err error) {
if client != nil {
return client, nil
}
c, err = NewRedisClient()
if err != nil {
return nil, err
}
return c, nil
}
|
2302_79757062/crawlab
|
db/redis/client.go
|
Go
|
bsd-3-clause
| 12,026
|
package redis
var MemoryStatsMetrics = []string{
"peak.allocated",
"total.allocated",
"startup.allocated",
"overhead.total",
"keys.count",
"dataset.bytes",
}
|
2302_79757062/crawlab
|
db/redis/constants.go
|
Go
|
bsd-3-clause
| 165
|
package redis
import (
"github.com/crawlab-team/crawlab/db"
"time"
)
type Option func(c db.RedisClient)
func WithBackoffMaxInterval(interval time.Duration) Option {
return func(c db.RedisClient) {
c.SetBackoffMaxInterval(interval)
}
}
func WithTimeout(timeout int) Option {
return func(c db.RedisClient) {
c.SetTimeout(timeout)
}
}
|
2302_79757062/crawlab
|
db/redis/options.go
|
Go
|
bsd-3-clause
| 346
|
package redis
import (
"github.com/crawlab-team/crawlab/trace"
"github.com/gomodule/redigo/redis"
"github.com/spf13/viper"
"time"
)
func NewRedisPool() *redis.Pool {
var address = viper.GetString("redis.address")
var port = viper.GetString("redis.port")
var database = viper.GetString("redis.database")
var password = viper.GetString("redis.password")
// normalize params
if address == "" {
address = "localhost"
}
if port == "" {
port = "6379"
}
if database == "" {
database = "1"
}
var url string
if password == "" {
url = "redis://" + address + ":" + port + "/" + database
} else {
url = "redis://x:" + password + "@" + address + ":" + port + "/" + database
}
return &redis.Pool{
Dial: func() (conn redis.Conn, e error) {
return redis.DialURL(url,
redis.DialConnectTimeout(time.Second*10),
redis.DialReadTimeout(time.Second*600),
redis.DialWriteTimeout(time.Second*10),
)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return trace.TraceError(err)
},
MaxIdle: 10,
MaxActive: 0,
IdleTimeout: 300 * time.Second,
Wait: false,
MaxConnLifetime: 0,
}
}
|
2302_79757062/crawlab
|
db/redis/pool.go
|
Go
|
bsd-3-clause
| 1,245
|
package test
import (
"github.com/crawlab-team/crawlab/db"
"github.com/crawlab-team/crawlab/db/redis"
"testing"
)
func init() {
var err error
T, err = NewTest()
if err != nil {
panic(err)
}
}
type Test struct {
client db.RedisClient
TestCollection string
TestMessage string
TestMessages []string
TestMessagesMap map[string]string
TestKeysAlpha []string
TestKeysBeta []string
TestLockKey string
}
func (t *Test) Setup(t2 *testing.T) {
t2.Cleanup(t.Cleanup)
}
func (t *Test) Cleanup() {
keys, _ := t.client.AllKeys()
for _, key := range keys {
_ = t.client.Del(key)
}
}
var T *Test
func NewTest() (t *Test, err error) {
// test
t = &Test{}
// client
t.client, err = redis.GetRedisClient()
if err != nil {
return nil, err
}
// test collection
t.TestCollection = "test_collection"
// test message
t.TestMessage = "this is a test message"
// test messages
t.TestMessages = []string{
"test message 1",
"test message 2",
"test message 3",
}
// test messages map
t.TestMessagesMap = map[string]string{
"test key 1": "test value 1",
"test key 2": "test value 2",
"test key 3": "test value 3",
}
// test keys alpha
t.TestKeysAlpha = []string{
"test key alpha 1",
"test key alpha 2",
"test key alpha 3",
}
// test keys beta
t.TestKeysBeta = []string{
"test key beta 1",
"test key beta 2",
"test key beta 3",
"test key beta 4",
"test key beta 5",
}
// test lock key
t.TestLockKey = "test lock key"
return t, nil
}
|
2302_79757062/crawlab
|
db/redis/test/base.go
|
Go
|
bsd-3-clause
| 1,522
|
package sql
import (
"errors"
"fmt"
"github.com/crawlab-team/crawlab/trace"
"github.com/jmoiron/sqlx"
)
func GetSqlDatabaseConnectionString(dataSourceType string, host string, port string, username string, password string, database string) (connStr string, err error) {
if dataSourceType == "mysql" {
connStr = fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, database)
} else if dataSourceType == "postgres" {
connStr = fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s", host, port, username, database, password, "disable")
} else {
err = errors.New(dataSourceType + " is not implemented")
return connStr, trace.TraceError(err)
}
return connStr, nil
}
func GetSqlConn(dataSourceType string, host string, port string, username string, password string, database string) (db *sqlx.DB, err error) {
// get database connection string
connStr, err := GetSqlDatabaseConnectionString(dataSourceType, host, port, username, password, database)
if err != nil {
return db, trace.TraceError(err)
}
// get database instance
db, err = sqlx.Open(dataSourceType, connStr)
if err != nil {
return db, trace.TraceError(err)
}
return db, nil
}
|
2302_79757062/crawlab
|
db/sql/sql.go
|
Go
|
bsd-3-clause
| 1,233
|
package utils
import "io"
func Close(c io.Closer) {
err := c.Close()
if err != nil {
//log.WithError(err).Error("关闭资源文件失败。")
}
}
func ContainsString(list []string, item string) bool {
for _, d := range list {
if d == item {
return true
}
}
return false
}
|
2302_79757062/crawlab
|
db/utils/utils.go
|
Go
|
bsd-3-clause
| 291
|
FROM node:14 AS build
ADD . /app
WORKDIR /app
RUN rm /app/.npmrc
# install frontend
RUN npm i -g pnpm@7
RUN pnpm install
RUN pnpm run build
FROM alpine:3.14
# copy files
COPY --from=build /app/dist /app/dist
|
2302_79757062/crawlab
|
frontend/Dockerfile
|
Dockerfile
|
bsd-3-clause
| 212
|
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
'@babel/preset-typescript'
]
}
|
2302_79757062/crawlab
|
frontend/babel.config.js
|
JavaScript
|
bsd-3-clause
| 105
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="width=device-width,initial-scale=1.0" name="viewport">
<link href="favicon.ico" rel="icon">
<title>Crawlab</title>
<!--externals-->
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.css" rel="stylesheet">
<script src="js/vue3-sfc-loader.js"></script>
<script src="js/login-canvas.js"></script>
<script src="simplemde/simplemde.js"></script>
<style>
#loading-placeholder {
position: fixed;
background: white;
z-index: -1;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
#loading-placeholder .title-wrapper {
height: 54px;
}
#loading-placeholder .title {
font-family: "Verdana", serif;
font-weight: 600;
font-size: 48px;
color: #409EFF;
text-align: center;
cursor: default;
letter-spacing: -5px;
margin: 0;
}
#loading-placeholder .title > span {
display: inline-block;
animation: change-shape 1s infinite;
}
#loading-placeholder .title > span:nth-child(1) {
animation-delay: calc(1s / 7 * 0 / 2);
}
#loading-placeholder .title > span:nth-child(2) {
animation-delay: calc(1s / 7 * 1 / 2);
}
#loading-placeholder .title > span:nth-child(3) {
animation-delay: calc(1s / 7 * 2 / 2);
}
#loading-placeholder .title > span:nth-child(4) {
animation-delay: calc(1s / 7 * 3 / 2);
}
#loading-placeholder .title > span:nth-child(5) {
animation-delay: calc(1s / 7 * 4 / 2);
}
#loading-placeholder .title > span:nth-child(6) {
animation-delay: calc(1s / 7 * 5 / 2);
}
#loading-placeholder .title > span:nth-child(7) {
animation-delay: calc(1s / 7 * 6 / 2);
}
#loading-placeholder .sub-title-wrapper {
position: relative;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 10px;
height: 28px;
}
#loading-placeholder .sub-title-wrapper .sub-title {
position: absolute;
font-size: 18px;
font-weight: 300;
font-family: "Verdana", serif;
font-style: italic;
color: #67C23A;
transform: rotate3d(1, 0, 0, 90deg);
animation: flip 20s infinite;
/*color: #E6A23C;*/
/*color: #F56C6C;*/
}
#loading-placeholder .sub-title-wrapper > .sub-title:nth-child(1) {
animation-delay: calc(20s / 4 * 0);
}
#loading-placeholder .sub-title-wrapper > .sub-title:nth-child(2) {
animation-delay: calc(20s / 4 * 1);
}
#loading-placeholder .sub-title-wrapper > .sub-title:nth-child(3) {
animation-delay: calc(20s / 4 * 2);
}
#loading-placeholder .sub-title-wrapper > .sub-title:nth-child(4) {
animation-delay: calc(20s / 4 * 3);
}
#loading-placeholder .loading-text {
text-align: center;
font-weight: bolder;
font-family: "Verdana", serif;
font-style: italic;
color: #889aa4;
font-size: 14px;
animation: blink-loading 2s ease-in infinite;
}
@keyframes blink-loading {
0% {
opacity: 100%;
}
50% {
opacity: 50%;
}
100% {
opacity: 100%;
}
}
@keyframes change-shape {
0% {
transform: scale(1);
}
25% {
transform: scale(1.2);
}
50% {
transform: scale(1);
}
100% {
transform: scale(1);
}
}
@keyframes flip {
0% {
transform: rotate3d(1, 0, 0, 90deg);
}
2% {
transform: rotate3d(1, 0, 0, 90deg);
}
7% {
transform: rotate3d(1, 0, 0, 0);
}
23% {
transform: rotate3d(1, 0, 0, 0);
}
27% {
transform: rotate3d(1, 0, 0, 90deg);
}
50% {
transform: rotate3d(1, 0, 0, 90deg);
}
100% {
transform: rotate3d(1, 0, 0, 90deg);
}
}
</style>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="loading-placeholder">
<div style="margin-bottom: 150px">
<div class="title-wrapper">
<h3 class="title">
<span>C</span>
<span>R</span>
<span>A</span>
<span>W</span>
<span>L</span>
<span>A</span>
<span>B</span>
</h3>
</div>
<div class="sub-title-wrapper">
<span class="sub-title"><i class="fa fa-cloud-download"></i> Easy Crawling</span>
<span class="sub-title"><i class="fa fa-diamond"></i> Better Management</span>
<span class="sub-title"><i class="fa fa-dollar"></i> Gain Data Value</span>
<span class="sub-title"><i class="fa fa-server"></i> Good Scalability</span>
</div>
<div class="loading-text">
Loading...
</div>
</div>
</div>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<!-- built files will be auto injected -->
</body>
</html>
|
2302_79757062/crawlab
|
frontend/index.html
|
HTML
|
bsd-3-clause
| 6,183
|
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/en/configuration.html
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/r0/jl9gx1m97tb2qpggj961z3n40000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: 'node',
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
|
2302_79757062/crawlab
|
frontend/jest.config.ts
|
TypeScript
|
bsd-3-clause
| 6,592
|
function initCanvas() {
let canvas, ctx, circ, nodes, mouse, SENSITIVITY, SIBLINGS_LIMIT, DENSITY, NODES_QTY, ANCHOR_LENGTH, MOUSE_RADIUS,
TURBULENCE, MOUSE_MOVING_TURBULENCE, MOUSE_ANGLE_TURBULENCE, MOUSE_MOVING_RADIUS, BASE_BRIGHTNESS, RADIUS_DEGRADE,
SAMPLE_SIZE
let handle
// how close next node must be to activate connection (in px)
// shorter distance == better connection (line width)
SENSITIVITY = 200
// note that siblings limit is not 'accurate' as the node can actually have more connections than this value that's because the node accepts sibling nodes with no regard to their current connections this is acceptable because potential fix would not result in significant visual difference
// more siblings == bigger node
SIBLINGS_LIMIT = 10
// default node margin
DENSITY = 100
// total number of nodes used (incremented after creation)
NODES_QTY = 0
// avoid nodes spreading
ANCHOR_LENGTH = 100
// highlight radius
MOUSE_RADIUS = 200
// turbulence of randomness
TURBULENCE = 3
// turbulence of mouse moving
MOUSE_MOVING_TURBULENCE = 50
// turbulence of mouse moving angle
MOUSE_ANGLE_TURBULENCE = 0.002
// moving radius of mouse
MOUSE_MOVING_RADIUS = 600
// base brightness
BASE_BRIGHTNESS = 0.12
// radius degrade
RADIUS_DEGRADE = 0.4
// sample size
SAMPLE_SIZE = 0.5
circ = 2 * Math.PI
nodes = []
canvas = document.querySelector('#canvas')
if (!canvas) return;
resizeWindow()
ctx = canvas.getContext('2d')
if (!ctx) {
alert('Ooops! Your browser does not support canvas :\'(')
}
function Mouse(x, y) {
this.anchorX = x
this.anchorY = y
this.x = x
this.y = y - MOUSE_RADIUS / 2
this.angle = 0
}
Mouse.prototype.computePosition = function () {
// this.x = this.anchorX + MOUSE_MOVING_RADIUS / 2 * Math.sin(this.angle)
// this.y = this.anchorY - MOUSE_MOVING_RADIUS / 2 * Math.cos(this.angle)
}
Mouse.prototype.move = function () {
let vx = Math.random() * MOUSE_MOVING_TURBULENCE
let vy = Math.random() * MOUSE_MOVING_TURBULENCE
if (this.x + vx + MOUSE_RADIUS / 2 > window.innerWidth || this.x + vx - MOUSE_RADIUS / 2 < 0) {
vx = -vx
}
if (this.y + vy + MOUSE_RADIUS / 2 > window.innerHeight || this.y + vy - MOUSE_RADIUS / 2 < 0) {
vy = -vy
}
this.x += vx
this.y += vy
// this.angle += Math.random() * MOUSE_ANGLE_TURBULENCE * 2 * Math.PI
// this.angle -= Math.floor(this.angle / (2 * Math.PI)) * 2 * Math.PI
// this.computePosition()
}
function Node(x, y) {
this.anchorX = x
this.anchorY = y
this.x = Math.random() * (x - (x - ANCHOR_LENGTH)) + (x - ANCHOR_LENGTH)
this.y = Math.random() * (y - (y - ANCHOR_LENGTH)) + (y - ANCHOR_LENGTH)
this.vx = Math.random() * TURBULENCE - 1
this.vy = Math.random() * TURBULENCE - 1
this.energy = Math.random() * 100
this.radius = Math.random()
this.siblings = []
this.brightness = 0
}
Node.prototype.drawNode = function () {
let color = 'rgba(64, 156, 255, ' + this.brightness + ')'
ctx.beginPath()
ctx.arc(this.x, this.y, 2 * this.radius + 2 * this.siblings.length / SIBLINGS_LIMIT / 1.5, 0, circ)
ctx.fillStyle = color
ctx.fill()
}
Node.prototype.drawConnections = function () {
for (let i = 0; i < this.siblings.length; i++) {
let color = 'rgba(64, 156, 255, ' + this.brightness + ')'
ctx.beginPath()
ctx.moveTo(this.x, this.y)
ctx.lineTo(this.siblings[i].x, this.siblings[i].y)
ctx.lineWidth = 1 - calcDistance(this, this.siblings[i]) / SENSITIVITY
ctx.strokeStyle = color
ctx.stroke()
}
}
Node.prototype.moveNode = function () {
this.energy -= 2
if (this.energy < 1) {
this.energy = Math.random() * 100
if (this.x - this.anchorX < -ANCHOR_LENGTH) {
this.vx = Math.random() * TURBULENCE
} else if (this.x - this.anchorX > ANCHOR_LENGTH) {
this.vx = Math.random() * -TURBULENCE
} else {
this.vx = Math.random() * 2 * TURBULENCE - TURBULENCE
}
if (this.y - this.anchorY < -ANCHOR_LENGTH) {
this.vy = Math.random() * TURBULENCE
} else if (this.y - this.anchorY > ANCHOR_LENGTH) {
this.vy = Math.random() * -TURBULENCE
} else {
this.vy = Math.random() * 2 * TURBULENCE - TURBULENCE
}
}
this.x += this.vx * this.energy / 100
this.y += this.vy * this.energy / 100
}
function Handle() {
this.isStopped = false
}
Handle.prototype.stop = function () {
this.isStopped = true
}
function initNodes() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
nodes = []
for (let i = DENSITY; i < canvas.width; i += DENSITY) {
for (let j = DENSITY; j < canvas.height; j += DENSITY) {
nodes.push(new Node(i, j))
NODES_QTY++
}
}
}
function initMouse() {
mouse = new Mouse(canvas.width / 2, canvas.height / 2)
}
function initHandle() {
handle = new Handle()
}
function calcDistance(node1, node2) {
return Math.sqrt(Math.pow(node1.x - node2.x, 2) + (Math.pow(node1.y - node2.y, 2)))
}
function findSiblings() {
let node1, node2, distance
for (let i = 0; i < NODES_QTY; i++) {
node1 = nodes[i]
node1.siblings = []
for (let j = 0; j < NODES_QTY; j++) {
node2 = nodes[j]
if (node1 !== node2) {
distance = calcDistance(node1, node2)
if (distance < SENSITIVITY) {
if (node1.siblings.length < SIBLINGS_LIMIT) {
node1.siblings.push(node2)
} else {
let node_sibling_distance = 0
let max_distance = 0
let s
for (let k = 0; k < SIBLINGS_LIMIT; k++) {
node_sibling_distance = calcDistance(node1, node1.siblings[k])
if (node_sibling_distance > max_distance) {
max_distance = node_sibling_distance
s = k
}
}
if (distance < max_distance) {
node1.siblings.splice(s, 1)
node1.siblings.push(node2)
}
}
}
}
}
}
}
function redrawScene() {
if (handle && handle.isStopped) {
return
}
resizeWindow()
ctx.clearRect(0, 0, canvas.width, canvas.height)
findSiblings()
let i, node, distance
for (i = 0; i < NODES_QTY; i++) {
node = nodes[i]
distance = calcDistance({
x: mouse.x,
y: mouse.y
}, node)
node.brightness = (1 - Math.log(distance / MOUSE_RADIUS * RADIUS_DEGRADE)) * BASE_BRIGHTNESS
}
for (i = 0; i < NODES_QTY; i++) {
node = nodes[i]
if (node.brightness) {
node.drawNode()
node.drawConnections()
}
node.moveNode()
}
// mouse.move()
setTimeout(() => {
requestAnimationFrame(redrawScene)
}, 50)
}
function initHandlers() {
document.addEventListener('resize', resizeWindow, {passive: true})
// canvas.addEventListener('mousemove', mousemoveHandler, false)
}
function resizeWindow() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}
function mousemoveHandler(e) {
mouse.x = e.clientX
mouse.y = e.clientY
}
function init() {
initHandlers()
initNodes()
initMouse()
initHandle()
redrawScene()
}
function reset() {
handle.isStopped = true
}
init()
window.resetCanvas = reset
}
|
2302_79757062/crawlab
|
frontend/public/js/login-canvas.js
|
JavaScript
|
bsd-3-clause
| 7,529
|
import 'crawlab-ui/dist/style.css';
import 'vue';
import {createApp} from 'crawlab-ui';
(async function () {
await createApp();
})();
|
2302_79757062/crawlab
|
frontend/src/main.ts
|
TypeScript
|
bsd-3-clause
| 137
|
import {resolve} from 'path';
import {defineConfig, splitVendorChunkPlugin} from 'vite';
import vue from '@vitejs/plugin-vue';
import dynamicImport from 'vite-plugin-dynamic-import';
import {visualizer} from 'rollup-plugin-visualizer';
import externalGlobals from 'rollup-plugin-external-globals';
import {externalizeDeps} from 'vite-plugin-externalize-deps';
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: (id) => {
if (id.includes('node_modules')) {
if (id.includes('@fortawesome')) return '@fortawesome';
if (id.includes('element-plus')) return 'element-plus';
if (id.includes('zrender')) return 'zrender';
if (id.includes('echarts')) return 'echarts';
if (id.includes('codemirror')) return 'codemirror';
if (id.includes('atom-material-icons')) return 'atom-material-icons';
if (id.includes('crawlab-ui')) return 'crawlab-ui';;
return 'vendor.[hash]';
}
}
},
external: [
// 'codemirror',
// 'echarts',
],
plugins: [
// @ts-ignore
// externalGlobals({
// // codemirror: 'CodeMirror',
// echarts: 'echarts',
// })
],
}
},
resolve: {
dedupe: ['vue', 'element-plus', 'codemirror'],
alias: [
{find: '@', replacement: resolve(__dirname, 'src')},
],
extensions: [
'.js',
'.ts',
'.jsx',
'.tsx',
'.json',
'.vue',
'.scss',
]
},
plugins: [
vue(),
dynamicImport(),
// splitVendorChunkPlugin(),
// externalizeDeps(),
// @ts-ignore
visualizer({
open: true,
// open: false,
}),
],
server: {
cors: true,
},
});
|
2302_79757062/crawlab
|
frontend/vite.config.ts
|
TypeScript
|
bsd-3-clause
| 1,796
|
const path = require("path")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const alias = {
'crawlab-ui$': 'crawlab-ui/dist/crawlab-ui.umd.min.js',
'element-plus$': 'element-plus/dist/index.full.min.js',
'echarts$': 'echarts/dist/echarts.min.js',
'codemirror$': 'codemirror/lib/codemirror.js',
}
const optimization = {
splitChunks: {
chunks: 'initial',
minSize: 20000,
minChunks: 1,
maxAsyncRequests: 3,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
}
const config = {
pages: {
index: {
entry: 'src/main.ts',
template: 'public/index.html',
filename: 'index.html',
title: 'Crawlab | Distributed Web Crawler Platform'
}
},
outputDir: './dist',
configureWebpack: {
optimization,
resolve: {
alias,
},
plugins: []
}
}
if (['development', 'local'].includes(process.env.NODE_ENV)) {
// do nothing
} else if (['production', 'docker'].includes(process.env.NODE_ENV)) {
config.configureWebpack.plugins.push(new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'public/js'),
}
]
}))
} else if (['analyze'].includes(process.env.NODE_ENV)) {
config.configureWebpack.plugins.push(new BundleAnalyzerPlugin({
analyzePort: 8890,
}))
}
module.exports = config
|
2302_79757062/crawlab
|
frontend/vue.config.js
|
JavaScript
|
bsd-3-clause
| 1,609
|
FROM golang:1.15
WORKDIR /app
ADD ./go.mod /app
ADD ./go.sum /app
RUN go mod download
CMD ["sh", "./bin/test.sh"]
|
2302_79757062/crawlab
|
fs/Dockerfile
|
Dockerfile
|
bsd-3-clause
| 116
|
package fs
import "os"
const (
FilerResponseNotFoundErrorMessage = "response status code: 404"
FilerStatusNotFoundErrorMessage = "Status:404 Not Found"
)
const (
DefaultDirMode = os.FileMode(0766)
DefaultFileMode = os.FileMode(0666)
)
const (
MethodUpdateFile = "update-file"
MethodUploadFile = "upload-file"
MethodUploadDir = "upload-dir"
)
|
2302_79757062/crawlab
|
fs/constants.go
|
Go
|
bsd-3-clause
| 357
|
package fs
import "errors"
var ErrorFsNotExists = errors.New("not exists")
|
2302_79757062/crawlab
|
fs/errors.go
|
Go
|
bsd-3-clause
| 77
|
package fs
import (
"github.com/crawlab-team/goseaweedfs"
"time"
)
type Manager interface {
Init() (err error)
Close() (err error)
ListDir(remotePath string, isRecursive bool) (files []goseaweedfs.FilerFileInfo, err error)
UploadFile(localPath, remotePath string, args ...interface{}) (err error)
UploadDir(localPath, remotePath string, args ...interface{}) (err error)
DownloadFile(remotePath, localPath string, args ...interface{}) (err error)
DownloadDir(remotePath, localPath string, args ...interface{}) (err error)
DeleteFile(remotePath string) (err error)
DeleteDir(remotePath string) (err error)
SyncLocalToRemote(localPath, remotePath string, args ...interface{}) (err error)
SyncRemoteToLocal(remotePath, localPath string, args ...interface{}) (err error)
GetFile(remotePath string, args ...interface{}) (data []byte, err error)
GetFileInfo(remotePath string) (file *goseaweedfs.FilerFileInfo, err error)
UpdateFile(remotePath string, data []byte, args ...interface{}) (err error)
Exists(remotePath string, args ...interface{}) (ok bool, err error)
SetFilerUrl(url string)
SetFilerAuthKey(authKey string)
SetTimeout(timeout time.Duration)
SetWorkerNum(num int)
SetRetryInterval(interval time.Duration)
SetRetryNum(num int)
SetMaxQps(qps int)
}
|
2302_79757062/crawlab
|
fs/interface.go
|
Go
|
bsd-3-clause
| 1,280
|
package copy
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"syscall"
)
func CopyDirectory(scrDir, dest string) error {
entries, err := ioutil.ReadDir(scrDir)
if err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(scrDir, entry.Name())
destPath := filepath.Join(dest, entry.Name())
fileInfo, err := os.Stat(sourcePath)
if err != nil {
return err
}
stat, ok := fileInfo.Sys().(*syscall.Stat_t)
if !ok {
return fmt.Errorf("failed to get raw syscall.Stat_t data for '%s'", sourcePath)
}
switch fileInfo.Mode() & os.ModeType {
case os.ModeDir:
if err := CreateIfNotExists(destPath, 0755); err != nil {
return err
}
if err := CopyDirectory(sourcePath, destPath); err != nil {
return err
}
case os.ModeSymlink:
if err := CopySymLink(sourcePath, destPath); err != nil {
return err
}
default:
if err := Copy(sourcePath, destPath); err != nil {
return err
}
}
if err := os.Lchown(destPath, int(stat.Uid), int(stat.Gid)); err != nil {
return err
}
isSymlink := entry.Mode()&os.ModeSymlink != 0
if !isSymlink {
if err := os.Chmod(destPath, entry.Mode()); err != nil {
return err
}
}
}
return nil
}
func Copy(srcFile, dstFile string) error {
out, err := os.Create(dstFile)
if err != nil {
return err
}
defer out.Close()
in, err := os.Open(srcFile)
defer in.Close()
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err != nil {
return err
}
return nil
}
func Exists(filePath string) bool {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return false
}
return true
}
func CreateIfNotExists(dir string, perm os.FileMode) error {
if Exists(dir) {
return nil
}
if err := os.MkdirAll(dir, perm); err != nil {
return fmt.Errorf("failed to create directory: '%s', error: '%s'", dir, err.Error())
}
return nil
}
func CopySymLink(source, dest string) error {
link, err := os.Readlink(source)
if err != nil {
return err
}
return os.Symlink(link, dest)
}
|
2302_79757062/crawlab
|
fs/lib/copy/copy.go
|
Go
|
bsd-3-clause
| 2,051
|
package fs
import "time"
type Option func(m Manager)
func WithFilerUrl(url string) Option {
return func(m Manager) {
m.SetFilerUrl(url)
}
}
func WithFilerAuthKey(authKey string) Option {
return func(m Manager) {
m.SetFilerAuthKey(authKey)
}
}
func WithTimeout(timeout time.Duration) Option {
return func(m Manager) {
m.SetTimeout(timeout)
}
}
func WithWorkerNum(num int) Option {
return func(m Manager) {
m.SetWorkerNum(num)
}
}
func WithRetryInterval(interval time.Duration) Option {
return func(m Manager) {
m.SetRetryInterval(interval)
}
}
func WithRetryNum(num int) Option {
return func(m Manager) {
m.SetRetryNum(num)
}
}
func WithMaxQps(qps int) Option {
return func(m Manager) {
m.SetMaxQps(qps)
}
}
|
2302_79757062/crawlab
|
fs/options.go
|
Go
|
bsd-3-clause
| 744
|
package fs
import (
"bytes"
"errors"
"fmt"
"github.com/cenkalti/backoff/v4"
"github.com/crawlab-team/crawlab/trace"
"github.com/crawlab-team/goseaweedfs"
"github.com/emirpasic/gods/queues/linkedlistqueue"
"github.com/google/uuid"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
)
type seaweedFsManagerFn func(params seaweedFsManagerParams) (res seaweedFsManagerResults)
type seaweedFsManagerHandle struct {
params seaweedFsManagerParams
fn seaweedFsManagerFn
resChan chan seaweedFsManagerResults
}
type seaweedFsManagerParams struct {
localPath string
remotePath string
isRecursive bool
collection string
ttl string
urlValues url.Values
data []byte
}
type seaweedFsManagerResults struct {
files []goseaweedfs.FilerFileInfo
file *goseaweedfs.FilerFileInfo
data []byte
ok bool
err error
}
type SeaweedFsManager struct {
// settings variables
filerUrl string
timeout time.Duration
authKey string
workerNum int
retryNum uint64
retryInterval time.Duration
maxQps int
// internals
f *goseaweedfs.Filer
q *linkedlistqueue.Queue
cr int
ch chan seaweedFsManagerHandle
closed bool
}
func (m *SeaweedFsManager) Init() (err error) {
// filer options
var filerOpts []goseaweedfs.FilerOption
// auth key
if m.authKey != "" {
filerOpts = append(filerOpts, goseaweedfs.WithFilerAuthKey(m.authKey))
}
// handle channel
m.ch = make(chan seaweedFsManagerHandle, m.workerNum)
// filer instance
m.f, err = goseaweedfs.NewFiler(m.filerUrl, &http.Client{Timeout: m.timeout}, filerOpts...)
if err != nil {
return trace.TraceError(err)
}
// start async
go m.start()
return nil
}
func (m *SeaweedFsManager) Close() (err error) {
m.closed = true
if err := m.f.Close(); err != nil {
return trace.TraceError(err)
}
return nil
}
func (m *SeaweedFsManager) ListDir(remotePath string, isRecursive bool) (files []goseaweedfs.FilerFileInfo, err error) {
params := seaweedFsManagerParams{
remotePath: remotePath,
isRecursive: isRecursive,
}
res := m.process(params, m.listDir)
return res.files, res.err
}
func (m *SeaweedFsManager) ListDirRecursive(remotePath string) (files []goseaweedfs.FilerFileInfo, err error) {
params := seaweedFsManagerParams{
remotePath: remotePath,
}
res := m.process(params, m.listDirRecursive)
return res.files, res.err
}
func (m *SeaweedFsManager) UploadFile(localPath, remotePath string, args ...interface{}) (err error) {
localPath, err = filepath.Abs(localPath)
if err != nil {
return trace.TraceError(err)
}
collection, ttl := getCollectionAndTtlFromArgs(args...)
params := seaweedFsManagerParams{
localPath: localPath,
remotePath: remotePath,
collection: collection,
ttl: ttl,
}
res := m.process(params, m.uploadFile)
return res.err
}
func (m *SeaweedFsManager) UploadDir(localPath, remotePath string, args ...interface{}) (err error) {
localPath, err = filepath.Abs(localPath)
if err != nil {
return trace.TraceError(err)
}
collection, ttl := getCollectionAndTtlFromArgs(args...)
params := seaweedFsManagerParams{
localPath: localPath,
remotePath: remotePath,
collection: collection,
ttl: ttl,
}
res := m.process(params, m.uploadDir)
return res.err
}
func (m *SeaweedFsManager) DownloadFile(remotePath, localPath string, args ...interface{}) (err error) {
localPath, err = filepath.Abs(localPath)
if err != nil {
return trace.TraceError(err)
}
collection, ttl := getCollectionAndTtlFromArgs(args...)
urlValues := getUrlValuesFromArgs(args...)
params := seaweedFsManagerParams{
localPath: localPath,
remotePath: remotePath,
collection: collection,
ttl: ttl,
urlValues: urlValues,
}
res := m.process(params, m.downloadFile)
return res.err
}
func (m *SeaweedFsManager) DownloadDir(remotePath, localPath string, args ...interface{}) (err error) {
localPath, err = filepath.Abs(localPath)
if err != nil {
return trace.TraceError(err)
}
params := seaweedFsManagerParams{
remotePath: remotePath,
}
res := m.process(params, m.downloadDir)
return res.err
}
func (m *SeaweedFsManager) DeleteFile(remotePath string) (err error) {
params := seaweedFsManagerParams{
remotePath: remotePath,
}
res := m.process(params, m.deleteFile)
return res.err
}
func (m *SeaweedFsManager) DeleteDir(remotePath string) (err error) {
params := seaweedFsManagerParams{
remotePath: remotePath,
}
res := m.process(params, m.deleteDir)
return res.err
}
func (m *SeaweedFsManager) SyncLocalToRemote(localPath, remotePath string, args ...interface{}) (err error) {
localPath, err = filepath.Abs(localPath)
if err != nil {
return trace.TraceError(err)
}
collection, ttl := getCollectionAndTtlFromArgs(args...)
params := seaweedFsManagerParams{
localPath: localPath,
remotePath: remotePath,
collection: collection,
ttl: ttl,
}
res := m.process(params, m.syncLocalToRemote)
return res.err
}
func (m *SeaweedFsManager) SyncRemoteToLocal(remotePath, localPath string, args ...interface{}) (err error) {
collection, ttl := getCollectionAndTtlFromArgs(args...)
params := seaweedFsManagerParams{
localPath: localPath,
remotePath: remotePath,
collection: collection,
ttl: ttl,
}
res := m.process(params, m.syncRemoteToLocal)
return res.err
}
func (m *SeaweedFsManager) GetFile(remotePath string, args ...interface{}) (data []byte, err error) {
urlValues := getUrlValuesFromArgs(args...)
params := seaweedFsManagerParams{
remotePath: remotePath,
urlValues: urlValues,
}
res := m.process(params, m.getFile)
return res.data, res.err
}
func (m *SeaweedFsManager) GetFileInfo(remotePath string) (file *goseaweedfs.FilerFileInfo, err error) {
params := seaweedFsManagerParams{
remotePath: remotePath,
}
res := m.process(params, m.getFileInfo)
return res.file, res.err
}
func (m *SeaweedFsManager) UpdateFile(remotePath string, data []byte, args ...interface{}) (err error) {
collection, ttl := getCollectionAndTtlFromArgs(args...)
params := seaweedFsManagerParams{
remotePath: remotePath,
collection: collection,
ttl: ttl,
data: data,
}
res := m.process(params, m.updateFile)
return res.err
}
func (m *SeaweedFsManager) Exists(remotePath string, args ...interface{}) (ok bool, err error) {
_, err = m.GetFile(remotePath, args...)
if err == nil {
// exists
return true, nil
}
if strings.Contains(err.Error(), FilerStatusNotFoundErrorMessage) {
// not exists
return false, nil
}
return ok, trace.TraceError(err)
}
func (m *SeaweedFsManager) SetFilerUrl(url string) {
m.filerUrl = url
}
func (m *SeaweedFsManager) SetFilerAuthKey(authKey string) {
m.authKey = authKey
}
func (m *SeaweedFsManager) SetTimeout(timeout time.Duration) {
m.timeout = timeout
}
func (m *SeaweedFsManager) SetWorkerNum(num int) {
m.workerNum = num
}
func (m *SeaweedFsManager) SetRetryInterval(interval time.Duration) {
m.retryInterval = interval
}
func (m *SeaweedFsManager) SetRetryNum(num int) {
m.retryNum = uint64(num)
}
func (m *SeaweedFsManager) SetMaxQps(qps int) {
m.maxQps = qps
}
func (m *SeaweedFsManager) newHandle(params seaweedFsManagerParams, fn seaweedFsManagerFn) (handle seaweedFsManagerHandle) {
return seaweedFsManagerHandle{
params: params,
fn: fn,
resChan: make(chan seaweedFsManagerResults),
}
}
func (m *SeaweedFsManager) start() {
for {
if m.closed {
return
}
handle := <-m.ch
go func() {
if err := backoff.Retry(func() error {
res := handle.fn(handle.params)
if res.err != nil {
return res.err
}
handle.resChan <- res
return nil
}, backoff.WithMaxRetries(
backoff.NewConstantBackOff(m.retryInterval), m.retryNum),
); err != nil {
handle.resChan <- m.error(err)
}
m.wait()
}()
}
}
func (m *SeaweedFsManager) process(params seaweedFsManagerParams, fn seaweedFsManagerFn) (res seaweedFsManagerResults) {
handle := m.newHandle(params, fn)
//log.Infof("handle: %v", handle)
m.ch <- handle
res = <-handle.resChan
return
}
func (m *SeaweedFsManager) error(err error) (res seaweedFsManagerResults) {
if err != nil {
trace.PrintError(err)
}
return seaweedFsManagerResults{err: err}
}
func (m *SeaweedFsManager) wait() {
ms := float32(1) / float32(m.maxQps) * 1e3
d := time.Duration(ms) * time.Millisecond
time.Sleep(d)
}
func (m *SeaweedFsManager) getCollectionAndTtlArgsFromParams(params seaweedFsManagerParams) (args []interface{}) {
if params.collection != "" {
args = append(args, params.collection)
}
if params.ttl != "" {
args = append(args, params.ttl)
}
return args
}
func (m *SeaweedFsManager) listDir(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
var err error
if params.isRecursive {
res.files, err = m.ListDirRecursive(params.remotePath)
} else {
res.files, err = m.f.ListDir(params.remotePath)
}
if err != nil {
return m.error(err)
}
return
}
func (m *SeaweedFsManager) listDirRecursive(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
entries, err := m.f.ListDir(params.remotePath)
if err != nil {
return m.error(err)
}
for _, file := range entries {
file = goseaweedfs.GetFileWithExtendedFields(file)
if file.IsDir {
file.Children, err = m.ListDirRecursive(file.FullPath)
if err != nil {
return m.error(err)
}
}
res.files = append(res.files, file)
}
return
}
func (m *SeaweedFsManager) uploadFile(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
r, err := m.f.UploadFile(params.localPath, params.remotePath, params.collection, params.ttl)
if err != nil {
return m.error(err)
}
if r.Error != "" {
err = errors.New(r.Error)
return m.error(err)
}
return
}
func (m *SeaweedFsManager) uploadDir(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
args := m.getCollectionAndTtlArgsFromParams(params)
if strings.HasSuffix(params.localPath, "/") {
params.localPath = params.localPath[:(len(params.localPath) - 1)]
}
if !strings.HasPrefix(params.remotePath, "/") {
params.remotePath = "/" + params.remotePath
}
files, err := goseaweedfs.ListFilesRecursive(params.localPath)
if err != nil {
return m.error(err)
}
for _, info := range files {
newFilePath := params.remotePath + strings.Replace(info.Path, params.localPath, "", -1)
if err := m.UploadFile(info.Path, newFilePath, args...); err != nil {
return m.error(err)
}
}
return
}
func (m *SeaweedFsManager) downloadFile(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
err := m.f.Download(params.remotePath, params.urlValues, func(reader io.Reader) error {
data, err := ioutil.ReadAll(reader)
if err != nil {
return trace.TraceError(err)
}
dirPath := filepath.Dir(params.localPath)
_, err = os.Stat(dirPath)
if err != nil {
// if not exists, create a new directory
if err := os.MkdirAll(dirPath, DefaultDirMode); err != nil {
return trace.TraceError(err)
}
}
fileMode := DefaultFileMode
fileInfo, err := os.Stat(params.localPath)
if err == nil {
// if file already exists, save file mode and remove it
fileMode = fileInfo.Mode()
if err := os.Remove(params.localPath); err != nil {
return trace.TraceError(err)
}
}
if err := ioutil.WriteFile(params.localPath, data, fileMode); err != nil {
return trace.TraceError(err)
}
return nil
})
if err != nil {
return m.error(err)
}
return
}
func (m *SeaweedFsManager) downloadDir(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
args := m.getCollectionAndTtlArgsFromParams(params)
var files []goseaweedfs.FilerFileInfo
files, res.err = m.ListDir(params.remotePath, true)
for _, file := range files {
if file.IsDir {
if err := m.DownloadDir(file.FullPath, path.Join(params.localPath, file.Name), args...); err != nil {
return m.error(err)
}
} else {
if err := m.DownloadFile(file.FullPath, path.Join(params.localPath, file.Name), args...); err != nil {
return m.error(err)
}
}
}
return
}
func (m *SeaweedFsManager) deleteFile(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
if err := m.f.DeleteFile(params.remotePath); err != nil {
return m.error(err)
}
return
}
func (m *SeaweedFsManager) deleteDir(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
if err := m.f.DeleteDir(params.remotePath); err != nil {
return m.error(err)
}
return
}
func (m *SeaweedFsManager) syncLocalToRemote(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
// args
args := m.getCollectionAndTtlArgsFromParams(params)
// raise error if local path does not exist
if _, err := os.Stat(params.localPath); err != nil {
return m.error(err)
}
// get files and maps
localFiles, remoteFiles, localFilesMap, remoteFilesMap, err := getFilesAndFilesMaps(m.f, params.localPath, params.remotePath)
if err != nil {
return m.error(err)
}
// compare remote files with local files and delete files absent in local files
for _, remoteFile := range remoteFiles {
// attempt to get corresponding local file
_, ok := localFilesMap[remoteFile.FullPath]
if !ok {
// file does not exist on local, delete
if remoteFile.IsDir {
if err := m.DeleteDir(remoteFile.FullPath); err != nil {
return m.error(err)
}
} else {
if err := m.DeleteFile(remoteFile.FullPath); err != nil {
return m.error(err)
}
}
}
}
// compare local files with remote files and upload files with difference
for _, localFile := range localFiles {
// skip .git
if IsGitFile(localFile) {
continue
}
// corresponding remote file path
fileRemotePath := fmt.Sprintf("%s%s", params.remotePath, strings.Replace(localFile.Path, params.localPath, "", -1))
// attempt to get corresponding remote file
remoteFile, ok := remoteFilesMap[fileRemotePath]
if !ok {
// file does not exist on remote, upload
if err := m.UploadFile(localFile.Path, fileRemotePath, args...); err != nil {
return m.error(err)
}
} else {
// file exists on remote, upload if md5sum values are different
if remoteFile.Md5 != localFile.Md5 {
if err := m.UploadFile(localFile.Path, fileRemotePath, args...); err != nil {
return m.error(err)
}
}
}
}
return
}
func (m *SeaweedFsManager) syncRemoteToLocal(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
// args
args := m.getCollectionAndTtlArgsFromParams(params)
// create directory if local path does not exist
if _, err := os.Stat(params.localPath); err != nil {
if err := os.MkdirAll(params.localPath, os.ModePerm); err != nil {
return m.error(err)
}
}
// get files and maps
localFiles, remoteFiles, localFilesMap, remoteFilesMap, err := getFilesAndFilesMaps(m.f, params.localPath, params.remotePath)
if err != nil {
return m.error(err)
}
// compare local files with remote files and delete files absent on remote
for _, localFile := range localFiles {
// skip .git
if IsGitFile(localFile) {
continue
}
// corresponding remote file path
fileRemotePath := fmt.Sprintf("%s%s", params.remotePath, strings.Replace(localFile.Path, params.localPath, "", -1))
// attempt to get corresponding remote file
_, ok := remoteFilesMap[fileRemotePath]
if !ok {
// file does not exist on remote, upload
if err := os.Remove(localFile.Path); err != nil {
return m.error(err)
}
}
}
// compare remote files with local files and download if files with difference
for _, remoteFile := range remoteFiles {
// directory
if remoteFile.IsDir {
localDirRelativePath := strings.Replace(remoteFile.FullPath, params.remotePath, "", 1)
localDirPath := fmt.Sprintf("%s%s", params.localPath, localDirRelativePath)
if err := m.SyncRemoteToLocal(remoteFile.FullPath, localDirPath); err != nil {
return m.error(err)
}
continue
}
// local file path
localFileRelativePath := strings.Replace(remoteFile.FullPath, params.remotePath, "", 1)
localFilePath := fmt.Sprintf("%s%s", params.localPath, localFileRelativePath)
// attempt to get corresponding local file
localFile, ok := localFilesMap[remoteFile.FullPath]
if !ok {
// file does not exist on local, download
if err := m.DownloadFile(remoteFile.FullPath, localFilePath); err != nil {
return m.error(err)
}
} else {
// file exists on remote, download if md5sum values are different
if remoteFile.Md5 != localFile.Md5 {
if err := m.DownloadFile(remoteFile.FullPath, localFilePath, args...); err != nil {
return m.error(err)
}
}
}
}
return
}
func (m *SeaweedFsManager) getFile(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
var buf bytes.Buffer
res.err = m.f.Download(params.remotePath, params.urlValues, func(reader io.Reader) error {
_, err := io.Copy(&buf, reader)
if err != nil {
return trace.TraceError(err)
}
return nil
})
res.data = buf.Bytes()
return
}
func (m *SeaweedFsManager) getFileInfo(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
arr := strings.Split(params.remotePath, "/")
dirName := strings.Join(arr[:(len(arr)-1)], "/")
files, err := m.f.ListDir(dirName)
if err != nil {
return m.error(err)
}
for _, f := range files {
if f.FullPath == params.remotePath {
res.file = &f
return
}
}
return m.error(ErrorFsNotExists)
}
func (m *SeaweedFsManager) updateFile(params seaweedFsManagerParams) (res seaweedFsManagerResults) {
tmpRootDir := os.TempDir()
tmpDirPath := path.Join(tmpRootDir, ".seaweedfs")
if _, err := os.Stat(tmpDirPath); err != nil {
if err := os.MkdirAll(tmpDirPath, os.ModePerm); err != nil {
return m.error(err)
}
}
tmpFilePath := path.Join(tmpDirPath, fmt.Sprintf(".%s", uuid.New().String()))
if _, err := os.Stat(tmpFilePath); err == nil {
if err := os.Remove(tmpFilePath); err != nil {
return m.error(err)
}
}
if err := ioutil.WriteFile(tmpFilePath, params.data, os.ModePerm); err != nil {
return m.error(err)
}
params2 := seaweedFsManagerParams{
localPath: tmpFilePath,
remotePath: params.remotePath,
collection: params.collection,
ttl: params.ttl,
}
if res := m.uploadFile(params2); res.err != nil {
return m.error(res.err)
}
if err := os.Remove(tmpFilePath); err != nil {
return m.error(err)
}
return
}
func NewSeaweedFsManager(opts ...Option) (m2 Manager, err error) {
// manager
m := &SeaweedFsManager{
filerUrl: "http://localhost:8888",
timeout: 5 * time.Minute,
workerNum: 1,
retryInterval: 500 * time.Millisecond,
retryNum: 3,
maxQps: 5,
q: linkedlistqueue.New(),
}
// apply options
for _, opt := range opts {
opt(m)
}
// initialize
if err := m.Init(); err != nil {
return nil, err
}
return m, nil
}
var _seaweedFsManager Manager
func GetSeaweedFsManager(opts ...Option) (m2 Manager, err error) {
if _seaweedFsManager == nil {
_seaweedFsManager, err = NewSeaweedFsManager(opts...)
if err != nil {
return nil, err
}
}
return _seaweedFsManager, nil
}
|
2302_79757062/crawlab
|
fs/seaweedfs_manager.go
|
Go
|
bsd-3-clause
| 19,055
|
package test
import (
fs "github.com/crawlab-team/crawlab/fs"
"os"
"testing"
"time"
)
func init() {
var err error
T, err = NewTest()
if err != nil {
panic(err)
}
}
var T *Test
type Test struct {
m fs.Manager
}
func (t *Test) Setup(t2 *testing.T) {
t.Cleanup()
t2.Cleanup(t.Cleanup)
}
func (t *Test) Cleanup() {
_ = T.m.DeleteDir("/test")
// wait to avoid caching
time.Sleep(200 * time.Millisecond)
}
func NewTest() (res *Test, err error) {
// test
t := &Test{}
// filer url
filerUrl := os.Getenv("CRAWLAB_FILER_URL")
if filerUrl == "" {
filerUrl = "http://localhost:8888"
}
// manager
t.m, err = fs.NewSeaweedFsManager(
fs.WithFilerUrl(filerUrl),
fs.WithTimeout(10*time.Second),
)
if err != nil {
return nil, err
}
return t, nil
}
|
2302_79757062/crawlab
|
fs/test/base.go
|
Go
|
bsd-3-clause
| 778
|
package test
import (
"github.com/apex/log"
"github.com/cenkalti/backoff/v4"
"github.com/crawlab-team/crawlab/trace"
"github.com/google/uuid"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"time"
)
func init() {
var err error
TmpDir, err = filepath.Abs("tmp")
if err != nil {
panic(err)
}
if _, err := os.Stat(TmpDir); err != nil {
if err := os.MkdirAll(TmpDir, os.ModePerm); err != nil {
panic(err)
}
}
//TmpDir = getTmpDir()
}
var TmpDir string
func StartTestSeaweedFs() (err error) {
// skip if CRAWLAB_IGNORE_WEED is set true
if os.Getenv("CRAWLAB_IGNORE_WEED") != "" {
return nil
}
// write to start.sh and stop.sh
if err := writeShFiles(TmpDir); err != nil {
return trace.TraceError(err)
}
// run weed
go runCmd(exec.Command("sh", "./start.sh"), TmpDir)
// wait for containers to be ready
time.Sleep(5 * time.Second)
f := func() error {
_, err := T.m.ListDir("/", true)
if err != nil {
return err
}
return nil
}
b := backoff.WithMaxRetries(backoff.NewConstantBackOff(5*time.Second), 5)
nt := func(err error, duration time.Duration) {
log.Infof("seaweedfs services not ready, re-attempt in %.1f seconds", duration.Seconds())
}
err = backoff.RetryNotify(f, b, nt)
if err != nil {
return trace.TraceError(err)
}
return nil
}
func StopTestSeaweedFs() (err error) {
// skip if CRAWLAB_IGNORE_WEED is set true
if os.Getenv("CRAWLAB_IGNORE_WEED") != "" {
return nil
}
// stop seaweedfs
if err := runCmd(exec.Command("sh", "./stop.sh"), TmpDir); err != nil {
return trace.TraceError(err)
}
time.Sleep(5 * time.Second)
// remove tmp folder
if err := os.RemoveAll(TmpDir); err != nil {
return trace.TraceError(err)
}
return nil
}
func writeShFiles(dirPath string) (err error) {
fileNames := []string{
"start.sh",
"stop.sh",
}
for _, fileName := range fileNames {
data, err := Asset("bin/" + fileName)
if err != nil {
return trace.TraceError(err)
}
filePath := path.Join(dirPath, fileName)
if err := ioutil.WriteFile(filePath, data, os.FileMode(0766)); err != nil {
return trace.TraceError(err)
}
}
return nil
}
func runCmd(cmd *exec.Cmd, dirPath string) (err error) {
log.Infof("running cmd: %v", cmd)
cmd.Dir = dirPath
//cmd.Stdout = os.Stdout
//cmd.Stderr = os.Stdout
return cmd.Run()
}
func getTmpDir() string {
id, _ := uuid.NewUUID()
tmpDir := path.Join(os.TempDir(), id.String())
if _, err := os.Stat(tmpDir); err != nil {
if err := os.MkdirAll(tmpDir, os.FileMode(0766)); err != nil {
panic(err)
}
}
return tmpDir
}
|
2302_79757062/crawlab
|
fs/test/utils.go
|
Go
|
bsd-3-clause
| 2,564
|
package fs
import (
"fmt"
"github.com/crawlab-team/goseaweedfs"
"net/url"
"path/filepath"
"regexp"
"strings"
)
func IsGitFile(file goseaweedfs.FileInfo) (res bool) {
// skip .git
res, err := regexp.MatchString("/?\\.git/", file.Path)
if err != nil {
return false
}
return res
}
func getCollectionAndTtlFromArgs(args ...interface{}) (collection, ttl string) {
if len(args) > 0 {
collection = args[0].(string)
}
if len(args) > 1 {
ttl = args[1].(string)
}
return
}
func getUrlValuesFromArgs(args ...interface{}) (values url.Values) {
if len(args) > 0 {
values = args[0].(url.Values)
}
return values
}
func getFilesAndFilesMaps(f *goseaweedfs.Filer, localPath, remotePath string) (localFiles []goseaweedfs.FileInfo, remoteFiles []goseaweedfs.FilerFileInfo, localFilesMap map[string]goseaweedfs.FileInfo, remoteFilesMap map[string]goseaweedfs.FilerFileInfo, err error) {
// declare maps
localFilesMap = map[string]goseaweedfs.FileInfo{}
remoteFilesMap = map[string]goseaweedfs.FilerFileInfo{}
// cache local files info
localFiles, err = goseaweedfs.ListLocalFilesRecursive(localPath)
if err != nil {
return localFiles, remoteFiles, localFilesMap, remoteFilesMap, err
}
for _, file := range localFiles {
fileRemotePath := fmt.Sprintf("%s%s", remotePath, strings.Replace(file.Path, localPath, "", -1))
localFilesMap[fileRemotePath] = file
// directory
dirRemotePath := filepath.Dir(fileRemotePath)
_, ok := localFilesMap[dirRemotePath]
if !ok {
localFilesMap[dirRemotePath] = goseaweedfs.FileInfo{
Name: filepath.Base(dirRemotePath),
Path: dirRemotePath,
}
}
}
// cache remote files info
remoteFiles, err = f.ListDirRecursive(remotePath)
if err != nil {
if err.Error() != FilerResponseNotFoundErrorMessage {
return localFiles, remoteFiles, localFilesMap, remoteFilesMap, err
}
err = nil
}
remoteFiles = getFlattenRemoteFiles(remoteFiles)
for _, file := range remoteFiles {
remoteFilesMap[file.FullPath] = file
}
return
}
func getFlattenRemoteFiles(files []goseaweedfs.FilerFileInfo) (flattenFiles []goseaweedfs.FilerFileInfo) {
flattenFiles = []goseaweedfs.FilerFileInfo{}
for _, file := range files {
flattenFiles = append(flattenFiles, file)
if file.IsDir {
flattenFiles = append(flattenFiles, getFlattenRemoteFiles(file.Children)...)
}
}
return
}
|
2302_79757062/crawlab
|
fs/utils.go
|
Go
|
bsd-3-clause
| 2,353
|
#!/bin/sh
IFS=$'\n'
pattern=^replace
content=$(cat ./backend/go.mod)
for line in $content
do
if [[ $line =~ $pattern ]]; then
echo "Invalid ./backend/go.mod, which should not contain \"^replace\""
exit 1
fi
done
|
2302_79757062/crawlab
|
scripts/validate-backend.sh
|
Shell
|
bsd-3-clause
| 219
|
package parser
// type: model / attribute
// {{task.spider.name}}
// =>
|
2302_79757062/crawlab
|
template-parser/entity.go
|
Go
|
bsd-3-clause
| 74
|
package parser
func Parse(template string, args ...interface{}) (content string, err error) {
return ParseGeneral(template, args...)
}
func ParseGeneral(template string, args ...interface{}) (content string, err error) {
p, _ := NewGeneralParser()
if err := p.Parse(template); err != nil {
return "", err
}
return p.Render(args...)
}
|
2302_79757062/crawlab
|
template-parser/func.go
|
Go
|
bsd-3-clause
| 343
|
package parser
import (
"encoding/json"
"errors"
"fmt"
"github.com/robertkrimen/otto"
"regexp"
"strings"
)
type GeneralParser struct {
tagPattern string
tagRegexp *regexp.Regexp
mathPattern string
mathRegexp *regexp.Regexp
template string
indexes [][]int
matches [][]string
placeholders []string
variables []Variable
vm *otto.Otto
}
const VariableNameResult = "result"
const ValueNameNA = "N/A"
func (p *GeneralParser) Parse(template string) (err error) {
p.template = template
p.indexes = p.tagRegexp.FindAllStringIndex(template, -1)
p.matches = p.tagRegexp.FindAllStringSubmatch(template, -1)
for _, arr := range p.matches {
p.placeholders = append(p.placeholders, arr[1])
}
return nil
}
func (p *GeneralParser) Render(args ...interface{}) (content string, err error) {
// render tag content
content, err = p.renderTagContent(args...)
if err != nil {
return content, err
}
// render math content
content, err = p.renderMathContent(content)
if err != nil {
return content, err
}
return content, nil
}
func (p *GeneralParser) renderTagContent(args ...interface{}) (content string, err error) {
// validate
if len(args) == 0 {
return "", errors.New("no arguments")
}
// first argument
arg := args[0]
// content
content = p.template
// old strings
var oldStrList []string
for _, index := range p.indexes {
// old string
oldStr := content[index[0]:index[1]]
oldStrList = append(oldStrList, oldStr)
}
// iterate placeholders
for i, placeholder := range p.placeholders {
// variable
v, err := NewVariable(arg, placeholder)
if err != nil {
return "", err
}
// value
value, err := v.GetValue()
if err != nil || value == nil {
value = ValueNameNA
}
// old string
oldStr := oldStrList[i]
// new string
var newStr string
switch value.(type) {
case string:
newStr = value.(string)
default:
newStrBytes, err := json.Marshal(value)
if err != nil {
return "", err
}
newStr = string(newStrBytes)
}
// replace old string with new string
content = strings.Replace(content, oldStr, newStr, 1)
}
return content, nil
}
func (p *GeneralParser) renderMathContent(inputContent string) (content string, err error) {
content = inputContent
indexes := p.mathRegexp.FindAllStringIndex(inputContent, -1)
matches := p.mathRegexp.FindAllStringSubmatch(inputContent, -1)
// old strings
var oldStrList []string
for _, index := range indexes {
// old string
oldStr := content[index[0]:index[1]]
oldStrList = append(oldStrList, oldStr)
}
// iterate matches
for i, m := range matches {
// js script to run to get evaluate result
script := fmt.Sprintf("%s = %s; %s", VariableNameResult, m[1], VariableNameResult)
// replace NA
script = strings.ReplaceAll(script, ValueNameNA, "NaN")
// value
value, err := p.vm.Run(script)
if err != nil {
return "", err
}
// old string
oldStr := oldStrList[i]
// new string
newStr := value.String()
// replace old string with new string
content = strings.Replace(content, oldStr, newStr, 1)
}
return content, nil
}
func (p *GeneralParser) GetPlaceholders() (placeholders []string) {
return p.placeholders
}
func NewGeneralParser() (p Parser, err error) {
// tag regexp
tagPrefix := "\\{\\{"
tagSuffix := "\\}\\}"
tagBasicChars := "\\$\\.\\w_"
tagAssociateChars := "\\[\\]:"
tagPattern := fmt.Sprintf(
"%s *([%s%s]+) *%s",
tagPrefix,
tagBasicChars,
tagAssociateChars,
tagSuffix,
)
tagRegexp, err := regexp.Compile(tagPattern)
if err != nil {
return nil, err
}
// math regexp
mathPrefix := "\\{#"
mathSuffix := "#\\}"
mathBasicChars := " \\(\\)"
mathOpChars := "\\+\\-\\*/%"
mathNumChars := "\\d\\."
mathSpecialChars := "(?:NaN|null)"
mathPattern := fmt.Sprintf(
"%s *([%s%s%s%s]+) *%s",
mathPrefix,
mathBasicChars,
mathOpChars,
mathNumChars,
mathSpecialChars,
mathSuffix,
)
mathRegexp, err := regexp.Compile(mathPattern)
if err != nil {
return nil, err
}
// math vm
vm := otto.New()
// parser
p = &GeneralParser{
tagPattern: tagPattern,
tagRegexp: tagRegexp,
mathPattern: mathPattern,
mathRegexp: mathRegexp,
vm: vm,
}
return p, nil
}
|
2302_79757062/crawlab
|
template-parser/general_parser.go
|
Go
|
bsd-3-clause
| 4,249
|
package parser
type Entity interface {
GetType() string
SetType(string)
GetName() string
SetName(string)
}
|
2302_79757062/crawlab
|
template-parser/interfaces.go
|
Go
|
bsd-3-clause
| 112
|
package parser
type Parser interface {
Parse(template string) (err error)
Render(args ...interface{}) (content string, err error)
}
|
2302_79757062/crawlab
|
template-parser/parser.go
|
Go
|
bsd-3-clause
| 135
|
package parser
import (
"encoding/json"
"errors"
"fmt"
"github.com/crawlab-team/crawlab/db/mongo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"regexp"
"strings"
)
var userRegexp, _ = regexp.Compile("^user(?:\\[(\\w+)\\])?$")
var extRegexp, _ = regexp.Compile("^(\\w+)?:(\\w+)")
type Variable struct {
root interface{}
tokens []string
doc bson.M
}
func (v *Variable) GetValue() (value interface{}, err error) {
return v.getNodeByIndex(len(v.tokens) - 1)
}
func (v *Variable) getNodeByIndex(index int) (result interface{}, err error) {
node := v.doc
for i := 0; i < index && i < len(v.tokens); i++ {
nextIndex := i + 1
if nextIndex < len(v.tokens)-1 {
// root or intermediate node
} else {
// value
return v.getNextValue(node, i), nil
}
// next node
node, err = v.getNextNode(node, i)
if err != nil {
return nil, err
}
if node == nil {
return nil, nil
}
}
return node, nil
}
func (v *Variable) getNextNode(currentNode bson.M, currentIndex int) (nextNode bson.M, err error) {
// next index and token
nextIndex := currentIndex + 1
nextToken := v.tokens[nextIndex]
// attempt to get attribute in current node
nextNodeRes, ok := currentNode[nextToken]
if ok {
nextNode, ok = nextNodeRes.(bson.M)
if ok {
return nextNode, nil
}
}
// if next token is user or user[<action>]
if userRegexp.MatchString(nextToken) {
return v.getNextNodeUserAction(currentNode, nextIndex, nextToken)
}
// if next token is <model>:<ext>
if extRegexp.MatchString(nextToken) {
return v.getNextNodeExt(currentNode, nextIndex, nextToken)
}
// model
model := nextToken
// next id
nextId, err := v._getNodeModelId(currentNode, model, nextIndex)
if err != nil {
return nil, err
}
// mongo collection name
colName := fmt.Sprintf("%ss", model)
// get next node from mongo collection
if err := mongo.GetMongoCol(colName).FindId(nextId).One(&nextNode); err != nil {
return nil, err
}
return nextNode, nil
}
func (v *Variable) getNextNodeUserAction(currentNode bson.M, nextIndex int, nextToken string) (nextNode bson.M, err error) {
// action
matches := userRegexp.FindStringSubmatch(nextToken)
action := "create"
if len(matches) > 1 && matches[1] != "" {
action = matches[1]
}
// id
id, err := v._getCurrentNodeId(currentNode, nextIndex)
if err != nil {
return nil, err
}
// artifact
var artifact bson.M
if err := mongo.GetMongoCol("artifacts").FindId(id).One(&artifact); err != nil {
return nil, err
}
// artifact._sys
sysRes, ok := artifact["_sys"]
if !ok {
return nil, errors.New(fmt.Sprintf("_sys not exists in artifact of %s", strings.Join(v.tokens[:nextIndex], ".")))
}
sys, ok := sysRes.(bson.M)
if !ok {
return nil, errors.New(fmt.Sprintf("_sys is invalid in artifact of %s", strings.Join(v.tokens[:nextIndex], ".")))
}
// <action>_uid
uidRes, _ := sys[action+"_uid"]
uid, _ := uidRes.(primitive.ObjectID)
if err := mongo.GetMongoCol("users").FindId(uid).One(&nextNode); err != nil {
return nil, err
}
return nextNode, nil
}
func (v *Variable) getNextNodeExt(currentNode bson.M, nextIndex int, nextToken string) (nextNode bson.M, err error) {
matches := extRegexp.FindStringSubmatch(nextToken)
var model, ext string
var mode int
if matches[1] == "" {
// :<model>_<ext>
mode = 0
arr := strings.Split(matches[2], "_")
model = arr[0]
ext = arr[1]
} else {
// <model>:<ext>
mode = 1
model = matches[1]
ext = matches[2]
}
// id
var id primitive.ObjectID
switch mode {
case 0:
// id = currentNode._id
id, err = v._getCurrentNodeId(currentNode, nextIndex)
if err != nil {
return nil, err
}
case 1:
// id = currentNode.<model>_id
id, err = v._getNodeModelId(currentNode, model, nextIndex)
if err != nil {
return nil, err
}
default:
return nil, errors.New(fmt.Sprintf("invalid mode: %d", mode))
}
// ext
colName := fmt.Sprintf("%s_%ss", model, ext)
if err := mongo.GetMongoCol(colName).FindId(id).One(&nextNode); err != nil {
return nil, err
}
return nextNode, nil
}
func (v *Variable) getNextValue(currentNode bson.M, currentIndex int) (nextValue interface{}) {
// next index and token
nextIndex := currentIndex + 1
nextToken := v.tokens[nextIndex]
// next value
nextValue, _ = currentNode[nextToken]
return nextValue
}
func (v *Variable) _getCurrentNodeId(currentNode bson.M, nextIndex int) (id primitive.ObjectID, err error) {
idRes, ok := currentNode["_id"]
if !ok {
return id, errors.New(fmt.Sprintf("%s is not available in %s", "_id", strings.Join(v.tokens[:nextIndex], ".")))
}
switch idRes.(type) {
case string:
idStr, ok := idRes.(string)
if !ok {
return id, errors.New(fmt.Sprintf("%s is not ObjectId in %s", "_id", strings.Join(v.tokens[:nextIndex], ".")))
}
id, err = primitive.ObjectIDFromHex(idStr)
if err != nil {
return id, errors.New(fmt.Sprintf("%s is not ObjectId in %s", "_id", strings.Join(v.tokens[:nextIndex], ".")))
}
return id, nil
case primitive.ObjectID:
return idRes.(primitive.ObjectID), nil
default:
return id, errors.New(fmt.Sprintf("%s is not ObjectId in %s", "_id", strings.Join(v.tokens[:nextIndex], ".")))
}
}
func (v *Variable) _getNodeModelId(currentNode bson.M, model string, nextIndex int) (id primitive.ObjectID, err error) {
nextIdKey := fmt.Sprintf("%s_id", model)
nextIdRes, ok := currentNode[nextIdKey]
if !ok {
return id, errors.New(fmt.Sprintf("%s is not available in %s", nextIdKey, strings.Join(v.tokens[:nextIndex], ".")))
}
nextId, ok := nextIdRes.(primitive.ObjectID)
if !ok {
nextIdStr, ok := nextIdRes.(string)
if !ok {
return id, errors.New(fmt.Sprintf("%s is not ObjectId in %s", nextIdKey, strings.Join(v.tokens[:nextIndex], ".")))
}
nextId, err = primitive.ObjectIDFromHex(nextIdStr)
if err != nil {
return id, err
}
}
if nextId.IsZero() {
return id, nil
}
return nextId, nil
}
func NewVariable(root interface{}, placeholder string) (v *Variable, err error) {
// validate
if placeholder == "" {
return nil, errors.New("empty placeholder")
}
if !strings.HasPrefix(placeholder, "$") {
return nil, errors.New("not start with $")
}
// tokens
tokens := strings.Split(placeholder, ".")
// document
data, err := json.Marshal(root)
if err != nil {
return nil, err
}
var doc bson.M
if err := json.Unmarshal(data, &doc); err != nil {
return nil, err
}
v = &Variable{
root: root,
tokens: tokens,
doc: doc,
}
return v, nil
}
|
2302_79757062/crawlab
|
template-parser/variable.go
|
Go
|
bsd-3-clause
| 6,506
|
package vcs
const (
GitRemoteNameOrigin = "origin"
GitRemoteNameUpstream = "upstream"
GitRemoteNameCrawlab = "crawlab"
)
const GitDefaultRemoteName = GitRemoteNameOrigin
const (
GitBranchNameMaster = "master"
GitBranchNameMain = "main"
GitBranchNameRelease = "release"
GitBranchNameTest = "test"
GitBranchNameDevelop = "develop"
)
const GitDefaultBranchName = GitBranchNameMaster
type GitAuthType int
const (
GitAuthTypeNone GitAuthType = iota
GitAuthTypeHTTP
GitAuthTypeSSH
)
type GitInitType int
const (
GitInitTypeFs GitInitType = iota
GitInitTypeMem
)
const (
GitRefTypeBranch = "branch"
GitRefTypeTag = "tag"
)
|
2302_79757062/crawlab
|
vcs/constants.go
|
Go
|
bsd-3-clause
| 651
|
package vcs
import (
"time"
)
type GitOptions struct {
checkout []GitCheckoutOption
}
type GitRef struct {
Type string `json:"type"`
Name string `json:"name"`
FullName string `json:"full_name"`
Hash string `json:"hash"`
Timestamp time.Time `json:"timestamp"`
}
type GitLog struct {
Hash string `json:"hash"`
Msg string `json:"msg"`
AuthorName string `json:"author_name"`
AuthorEmail string `json:"author_email"`
Timestamp time.Time `json:"timestamp"`
Refs []GitRef `json:"refs"`
}
type GitFileStatus struct {
Path string `json:"path"`
Name string `json:"name"`
IsDir bool `json:"is_dir"`
Staging string `json:"staging"`
Worktree string `json:"worktree"`
Extra string `json:"extra"`
Children []GitFileStatus `json:"children"`
}
|
2302_79757062/crawlab
|
vcs/entity.go
|
Go
|
bsd-3-clause
| 889
|
package vcs
import "errors"
var (
ErrInvalidArgsLength = errors.New("invalid arguments length")
ErrUnsupportedType = errors.New("unsupported type")
ErrInvalidAuthType = errors.New("invalid auth type")
ErrInvalidOptions = errors.New("invalid options")
ErrRepoAlreadyExists = errors.New("repo already exists")
ErrInvalidRepoPath = errors.New("invalid repo path")
ErrUnableToGetCurrentBranch = errors.New("unable to get current branch")
ErrUnableToCloneWithEmptyRemoteUrl = errors.New("unable to clone with empty remote url")
ErrInvalidHeadRef = errors.New("invalid head ref")
ErrNoMatchedRemoteBranch = errors.New("no matched remote branch")
)
|
2302_79757062/crawlab
|
vcs/errors.go
|
Go
|
bsd-3-clause
| 781
|
package vcs
import (
"github.com/apex/log"
"github.com/crawlab-team/crawlab/trace"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/go-git/go-git/v5/storage/memory"
"golang.org/x/crypto/ssh"
"io/ioutil"
"os"
"path"
"regexp"
"sort"
"strings"
)
var headRefRegexp, _ = regexp.Compile("^ref: (.*)")
type GitClient struct {
// settings
path string
remoteUrl string
isMem bool
authType GitAuthType
username string
password string
privateKey string
privateKeyPath string
defaultBranch string
// internals
r *git.Repository
}
func (c *GitClient) Init() (err error) {
initType := c.getInitType()
switch initType {
case GitInitTypeFs:
err = c.initFs()
case GitInitTypeMem:
err = c.initMem()
}
if err != nil {
return err
}
// if remote url is not empty and no remote exists
// create default remote and pull from remote url
remotes, err := c.r.Remotes()
if err != nil {
return err
}
if c.remoteUrl != "" && len(remotes) == 0 {
// attempt to get default remote
if _, err := c.r.Remote(GitRemoteNameOrigin); err != nil {
if err != git.ErrRemoteNotFound {
return trace.TraceError(err)
}
err = nil
// create default remote
if err := c.createRemote(GitRemoteNameOrigin, c.remoteUrl); err != nil {
return err
}
//// pull
//opts := []GitPullOption{
// WithRemoteNamePull(GitRemoteNameOrigin),
//}
//if err := c.Pull(opts...); err != nil {
// return err
//}
}
}
return nil
}
func (c *GitClient) Dispose() (err error) {
switch c.getInitType() {
case GitInitTypeFs:
if err := os.RemoveAll(c.path); err != nil {
return trace.TraceError(err)
}
case GitInitTypeMem:
GitMemStorages.Delete(c.path)
GitMemFileSystem.Delete(c.path)
}
return nil
}
func (c *GitClient) Checkout(opts ...GitCheckoutOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// apply options
o := &git.CheckoutOptions{}
for _, opt := range opts {
opt(o)
}
// checkout to the branch
if err := wt.Checkout(o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Commit(msg string, opts ...GitCommitOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// apply options
o := &git.CommitOptions{}
for _, opt := range opts {
opt(o)
}
// commit
if _, err := wt.Commit(msg, o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Pull(opts ...GitPullOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
if auth != nil {
opts = append(opts, WithAuthPull(auth))
}
// apply options
o := &git.PullOptions{}
for _, opt := range opts {
opt(o)
}
// pull
if err := wt.Pull(o); err != nil {
if err == transport.ErrEmptyRemoteRepository {
return nil
}
if err == transport.ErrEmptyUploadPackRequest {
return nil
}
if err == git.NoErrAlreadyUpToDate {
return nil
}
if err == git.ErrNonFastForwardUpdate {
return nil
}
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Push(opts ...GitPushOption) (err error) {
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
if auth != nil {
opts = append(opts, WithAuthPush(auth))
}
// apply options
o := &git.PushOptions{}
for _, opt := range opts {
opt(o)
}
// push
if err := c.r.Push(o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Reset(opts ...GitResetOption) (err error) {
// apply options
o := &git.ResetOptions{
Mode: git.HardReset,
}
for _, opt := range opts {
opt(o)
}
// worktree
wt, err := c.r.Worktree()
if err != nil {
return err
}
// reset
if err := wt.Reset(o); err != nil {
return err
}
// clean
if err := wt.Clean(&git.CleanOptions{Dir: true}); err != nil {
return err
}
return nil
}
func (c *GitClient) CreateBranch(branch, remote string, ref *plumbing.Reference) (err error) {
return c.createBranch(branch, remote, ref)
}
func (c *GitClient) CheckoutBranchFromRef(branch string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, "", ref, opts...)
}
func (c *GitClient) CheckoutBranchWithRemoteFromRef(branch, remote string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, remote, ref, opts...)
}
func (c *GitClient) CheckoutBranch(branch string, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, "", nil, opts...)
}
func (c *GitClient) CheckoutBranchWithRemote(branch, remote string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
if remote == "" {
remote = GitRemoteNameOrigin
}
// remote
if _, err := c.r.Remote(remote); err != nil {
return trace.TraceError(err)
}
// check if the branch exists
b, err := c.r.Branch(branch)
if err != nil {
if err == git.ErrBranchNotFound {
// create a new branch if it does not exist
if err := c.createBranch(branch, remote, ref); err != nil {
return err
}
b, err = c.r.Branch(branch)
if err != nil {
return trace.TraceError(err)
}
} else {
return trace.TraceError(err)
}
}
// set branch remote
if remote != "" {
b.Remote = remote
}
// add to options
opts = append(opts, WithBranch(branch))
return c.Checkout(opts...)
}
func (c *GitClient) CheckoutHash(hash string, opts ...GitCheckoutOption) (err error) {
// add to options
opts = append(opts, WithHash(hash))
return c.Checkout(opts...)
}
func (c *GitClient) MoveBranch(from, to string) (err error) {
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
if err := wt.Checkout(&git.CheckoutOptions{
Create: true,
Branch: plumbing.NewBranchReferenceName(to),
}); err != nil {
return trace.TraceError(err)
}
fromRef, err := c.r.Reference(plumbing.NewBranchReferenceName(from), false)
if err != nil {
return trace.TraceError(err)
}
if err := c.r.Storer.RemoveReference(fromRef.Name()); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) CommitAll(msg string, opts ...GitCommitOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// add all files
if _, err := wt.Add("."); err != nil {
return trace.TraceError(err)
}
return c.Commit(msg, opts...)
}
func (c *GitClient) GetLogs() (logs []GitLog, err error) {
iter, err := c.r.Log(&git.LogOptions{
All: true,
})
if err != nil {
return nil, trace.TraceError(err)
}
if err := iter.ForEach(func(commit *object.Commit) error {
log := GitLog{
Hash: commit.Hash.String(),
Msg: commit.Message,
AuthorName: commit.Author.Name,
AuthorEmail: commit.Author.Email,
Timestamp: commit.Author.When,
}
logs = append(logs, log)
return nil
}); err != nil {
return nil, trace.TraceError(err)
}
return
}
func (c *GitClient) GetLogsWithRefs() (logs []GitLog, err error) {
// logs without tags
logs, err = c.GetLogs()
if err != nil {
return nil, err
}
// branches
branches, err := c.GetBranches()
if err != nil {
return nil, err
}
// tags
tags, err := c.GetTags()
if err != nil {
return nil, err
}
// refs
refs := append(branches, tags...)
// refs map
refsMap := map[string][]GitRef{}
for _, ref := range refs {
_, ok := refsMap[ref.Hash]
if !ok {
refsMap[ref.Hash] = []GitRef{}
}
refsMap[ref.Hash] = append(refsMap[ref.Hash], ref)
}
// iterate logs
for i, l := range logs {
refs, ok := refsMap[l.Hash]
if ok {
logs[i].Refs = refs
}
}
return logs, nil
}
func (c *GitClient) GetRepository() (r *git.Repository) {
return c.r
}
func (c *GitClient) GetPath() (path string) {
return c.path
}
func (c *GitClient) SetPath(path string) {
c.path = path
}
func (c *GitClient) GetRemoteUrl() (path string) {
return c.remoteUrl
}
func (c *GitClient) SetRemoteUrl(url string) {
c.remoteUrl = url
}
func (c *GitClient) GetIsMem() (isMem bool) {
return c.isMem
}
func (c *GitClient) SetIsMem(isMem bool) {
c.isMem = isMem
}
func (c *GitClient) GetAuthType() (authType GitAuthType) {
return c.authType
}
func (c *GitClient) SetAuthType(authType GitAuthType) {
c.authType = authType
}
func (c *GitClient) GetUsername() (username string) {
return c.username
}
func (c *GitClient) SetUsername(username string) {
c.username = username
}
func (c *GitClient) GetPassword() (password string) {
return c.password
}
func (c *GitClient) SetPassword(password string) {
c.password = password
}
func (c *GitClient) GetPrivateKey() (key string) {
return c.privateKey
}
func (c *GitClient) SetPrivateKey(key string) {
c.privateKey = key
}
func (c *GitClient) GetPrivateKeyPath() (path string) {
return c.privateKeyPath
}
func (c *GitClient) SetPrivateKeyPath(path string) {
c.privateKeyPath = path
}
func (c *GitClient) GetCurrentBranch() (branch string, err error) {
// attempt to get branch from .git/HEAD
headRefStr, err := c.getHeadRef()
if err != nil {
return "", err
}
// if .git/HEAD points to refs/heads/master, return branch as master
if headRefStr == plumbing.Master.String() {
return GitBranchNameMaster, nil
}
// attempt to get head ref
headRef, err := c.r.Head()
if err != nil {
return "", trace.TraceError(err)
}
if !headRef.Name().IsBranch() {
return "", trace.TraceError(ErrUnableToGetCurrentBranch)
}
return headRef.Name().Short(), nil
}
func (c *GitClient) GetCurrentBranchRef() (ref *GitRef, err error) {
currentBranch, err := c.GetCurrentBranch()
if err != nil {
return nil, err
}
branches, err := c.GetBranches()
if err != nil {
return nil, err
}
for _, branch := range branches {
if branch.Name == currentBranch {
return &branch, nil
}
}
return nil, trace.TraceError(ErrUnableToGetCurrentBranch)
}
func (c *GitClient) GetBranches() (branches []GitRef, err error) {
iter, err := c.r.Branches()
if err != nil {
return nil, trace.TraceError(err)
}
_ = iter.ForEach(func(r *plumbing.Reference) error {
branches = append(branches, GitRef{
Type: GitRefTypeBranch,
Name: r.Name().Short(),
Hash: r.Hash().String(),
})
return nil
})
return branches, nil
}
func (c *GitClient) GetRemoteRefs(remoteName string) (gitRefs []GitRef, err error) {
// remote
r, err := c.r.Remote(remoteName)
if err != nil {
if err == git.ErrRemoteNotFound {
return nil, nil
}
return nil, trace.TraceError(err)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return nil, err
}
// refs
refs, err := r.List(&git.ListOptions{Auth: auth})
if err != nil {
if err != transport.ErrEmptyRemoteRepository {
return nil, trace.TraceError(err)
}
return nil, nil
}
// iterate refs
for _, ref := range refs {
// ref type
var refType string
if strings.HasPrefix(ref.Name().String(), "refs/heads") {
refType = GitRefTypeBranch
} else if strings.HasPrefix(ref.Name().String(), "refs/tags") {
refType = GitRefTypeTag
} else {
continue
}
// add to branches
gitRefs = append(gitRefs, GitRef{
Type: refType,
Name: ref.Name().Short(),
FullName: ref.Name().String(),
Hash: ref.Hash().String(),
})
}
// logs without tags
logs, err := c.GetLogs()
if err != nil {
return nil, err
}
// logs map
logsMap := map[string]GitLog{}
for _, l := range logs {
logsMap[l.Hash] = l
}
// iterate git refs
for i, gitRef := range gitRefs {
l, ok := logsMap[gitRef.Hash]
if !ok {
continue
}
gitRefs[i].Timestamp = l.Timestamp
}
// sort git refs
sort.Slice(gitRefs, func(i, j int) bool {
return gitRefs[i].Timestamp.Unix() > gitRefs[j].Timestamp.Unix()
})
return gitRefs, nil
}
func (c *GitClient) GetTags() (tags []GitRef, err error) {
iter, err := c.r.Tags()
if err != nil {
return nil, trace.TraceError(err)
}
_ = iter.ForEach(func(r *plumbing.Reference) error {
tags = append(tags, GitRef{
Type: GitRefTypeTag,
Name: r.Name().Short(),
Hash: r.Hash().String(),
})
return nil
})
return tags, nil
}
func (c *GitClient) GetStatus() (statusList []GitFileStatus, err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return nil, trace.TraceError(err)
}
// status
status, err := wt.Status()
if err != nil {
log.Warnf("failed to get worktree status: %v", err)
}
// file status list
var list []GitFileStatus
for filePath, fileStatus := range status {
// file name
fileName := path.Base(filePath)
// file status
s := GitFileStatus{
Path: filePath,
Name: fileName,
IsDir: false,
Staging: c.getStatusString(fileStatus.Staging),
Worktree: c.getStatusString(fileStatus.Worktree),
Extra: fileStatus.Extra,
}
// add to list
list = append(list, s)
}
// sort list ascending
sort.Slice(list, func(i, j int) bool {
return list[i].Path < list[j].Path
})
return list, nil
}
func (c *GitClient) Add(filePath string) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
if _, err := wt.Add(filePath); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) GetRemote(name string) (r *git.Remote, err error) {
return c.r.Remote(name)
}
func (c *GitClient) CreateRemote(cfg *config.RemoteConfig) (r *git.Remote, err error) {
return c.r.CreateRemote(cfg)
}
func (c *GitClient) DeleteRemote(name string) (err error) {
return c.r.DeleteRemote(name)
}
func (c *GitClient) IsRemoteChanged() (ok bool, err error) {
return c.isRemoteChanged()
}
func (c *GitClient) initMem() (err error) {
// validate options
if !c.isMem || c.path == "" {
return trace.TraceError(ErrInvalidOptions)
}
// get storage and worktree
storage, wt := c.getMemStorageAndMemFs(c.path)
// attempt to init
c.r, err = git.Init(storage, wt)
if err != nil {
if err == git.ErrRepositoryAlreadyExists {
// if already exists, attempt to open
c.r, err = git.Open(storage, wt)
if err != nil {
return trace.TraceError(err)
}
} else {
return trace.TraceError(err)
}
}
return nil
}
func (c *GitClient) initFs() (err error) {
// validate options
if c.path == "" {
return trace.TraceError(ErrInvalidOptions)
}
// create directory if not exists
_, err = os.Stat(c.path)
if err != nil {
if err := os.MkdirAll(c.path, os.ModePerm); err != nil {
return trace.TraceError(err)
}
err = nil
}
// try to open repo
c.r, err = git.PlainOpen(c.path)
if err == git.ErrRepositoryNotExists {
// repo not exists, init
c.r, err = git.PlainInit(c.path, false)
if err != nil {
return trace.TraceError(err)
}
} else if err != nil {
// error
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) clone() (err error) {
// validate
if c.remoteUrl == "" {
return trace.TraceError(ErrUnableToCloneWithEmptyRemoteUrl)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
// options
o := &git.CloneOptions{
URL: c.remoteUrl,
Auth: auth,
}
// clone
if _, err := git.PlainClone(c.path, false, o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) getInitType() (res GitInitType) {
if c.isMem {
return GitInitTypeMem
} else {
return GitInitTypeFs
}
}
func (c *GitClient) createRemote(remoteName string, url string) (err error) {
_, err = c.r.CreateRemote(&config.RemoteConfig{
Name: remoteName,
URLs: []string{url},
})
if err != nil {
return trace.TraceError(err)
}
return
}
func (c *GitClient) getMemStorageAndMemFs(key string) (storage *memory.Storage, fs billy.Filesystem) {
// storage
storageItem, ok := GitMemStorages.Load(key)
if !ok {
storage = memory.NewStorage()
GitMemStorages.Store(key, storage)
} else {
switch storageItem.(type) {
case *memory.Storage:
storage = storageItem.(*memory.Storage)
default:
storage = memory.NewStorage()
GitMemStorages.Store(key, storage)
}
}
// file system
fsItem, ok := GitMemFileSystem.Load(key)
if !ok {
fs = memfs.New()
GitMemFileSystem.Store(key, fs)
} else {
switch fsItem.(type) {
case billy.Filesystem:
fs = fsItem.(billy.Filesystem)
default:
fs = memfs.New()
GitMemFileSystem.Store(key, fs)
}
}
return storage, fs
}
func (c *GitClient) getGitAuth() (auth transport.AuthMethod, err error) {
switch c.authType {
case GitAuthTypeNone:
return nil, nil
case GitAuthTypeHTTP:
if c.username == "" && c.password == "" {
return nil, nil
}
auth = &http.BasicAuth{
Username: c.username,
Password: c.password,
}
return auth, nil
case GitAuthTypeSSH:
var privateKeyData []byte
if c.privateKey != "" {
// private key content
privateKeyData = []byte(c.privateKey)
} else if c.privateKeyPath != "" {
// read from private key file
privateKeyData, err = ioutil.ReadFile(c.privateKeyPath)
if err != nil {
return nil, trace.TraceError(err)
}
} else {
// no private key
return nil, nil
}
signer, err := ssh.ParsePrivateKey(privateKeyData)
if err != nil {
return nil, trace.TraceError(err)
}
auth = &gitssh.PublicKeys{
User: c.username,
Signer: signer,
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
},
}
return auth, nil
default:
return nil, trace.TraceError(ErrInvalidAuthType)
}
}
func (c *GitClient) getHeadRef() (ref string, err error) {
wt, err := c.r.Worktree()
if err != nil {
return "", trace.TraceError(err)
}
fh, err := wt.Filesystem.Open(path.Join(".git", "HEAD"))
if err != nil {
return "", trace.TraceError(err)
}
data, err := ioutil.ReadAll(fh)
if err != nil {
return "", trace.TraceError(err)
}
m := headRefRegexp.FindStringSubmatch(string(data))
if len(m) < 2 {
return "", trace.TraceError(ErrInvalidHeadRef)
}
return m[1], nil
}
func (c *GitClient) getStatusString(statusCode git.StatusCode) (code string) {
return string(statusCode)
//switch statusCode {
//}
//Unmodified StatusCode = ' '
//Untracked StatusCode = '?'
//Modified StatusCode = 'M'
//Added StatusCode = 'A'
//Deleted StatusCode = 'D'
//Renamed StatusCode = 'R'
//Copied StatusCode = 'C'
//UpdatedButUnmerged StatusCode = 'U'
}
func (c *GitClient) getDirPaths(filePath string) (paths []string) {
pathItems := strings.Split(filePath, "/")
var items []string
for i, pathItem := range pathItems {
if i == len(pathItems)-1 {
continue
}
items = append(items, pathItem)
dirPath := strings.Join(items, "/")
paths = append(paths, dirPath)
}
return paths
}
func (c *GitClient) createBranch(branch, remote string, ref *plumbing.Reference) (err error) {
// create a new branch if it does not exist
cfg := config.Branch{
Name: branch,
Remote: remote,
}
if err := c.r.CreateBranch(&cfg); err != nil {
return err
}
// if ref is nil
if ref == nil {
// try to set to remote ref of branch first
ref, err = c.getBranchHashRef(branch, remote)
// if no matched remote branch, set to HEAD
if err == ErrNoMatchedRemoteBranch {
ref, err = c.r.Head()
if err != nil {
return trace.TraceError(err)
}
}
// error
if err != nil {
return trace.TraceError(err)
}
}
// branch reference name
branchRefName := plumbing.NewBranchReferenceName(branch)
// branch reference
branchRef := plumbing.NewHashReference(branchRefName, ref.Hash())
// set HEAD to branch reference
if err := c.r.Storer.SetReference(branchRef); err != nil {
return err
}
return nil
}
func (c *GitClient) getBranchHashRef(branch, remote string) (hashRef *plumbing.Reference, err error) {
refs, err := c.GetRemoteRefs(remote)
if err != nil {
return nil, err
}
var branchRef *GitRef
for _, r := range refs {
if r.Name == branch {
branchRef = &r
break
}
}
if branchRef == nil {
return nil, ErrNoMatchedRemoteBranch
}
branchHashRef := plumbing.NewHashReference(plumbing.NewBranchReferenceName(branch), plumbing.NewHash(branchRef.Hash))
return branchHashRef, nil
}
func (c *GitClient) isRemoteChanged() (ok bool, err error) {
b, err := c.GetCurrentBranchRef()
if err != nil {
return false, err
}
refs, err := c.GetRemoteRefs(GitRemoteNameOrigin)
if err != nil {
return false, err
}
for _, r := range refs {
if r.Name == b.Name {
return r.Hash != b.Hash, nil
}
}
return false, nil
}
func NewGitClient(opts ...GitOption) (c *GitClient, err error) {
// client
c = &GitClient{
isMem: false,
authType: GitAuthTypeNone,
username: "git",
privateKeyPath: getDefaultPublicKeyPath(),
}
// apply options
for _, opt := range opts {
opt(c)
}
// init
if err := c.Init(); err != nil {
return c, err
}
return
}
|
2302_79757062/crawlab
|
vcs/git.go
|
Go
|
bsd-3-clause
| 21,289
|
package vcs
import (
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"strings"
)
type GitOption func(c *GitClient)
func WithPath(path string) GitOption {
return func(c *GitClient) {
c.path = path
}
}
func WithRemoteUrl(url string) GitOption {
return func(c *GitClient) {
c.remoteUrl = url
}
}
func WithIsMem() GitOption {
return func(c *GitClient) {
c.isMem = true
}
}
func WithAuthType(authType GitAuthType) GitOption {
return func(c *GitClient) {
c.authType = authType
}
}
func WithUsername(username string) GitOption {
return func(c *GitClient) {
c.username = username
}
}
func WithPassword(password string) GitOption {
return func(c *GitClient) {
c.password = password
}
}
func WithPrivateKey(key string) GitOption {
return func(c *GitClient) {
c.privateKey = key
}
}
func WithDefaultBranch(branch string) GitOption {
return func(c *GitClient) {
c.defaultBranch = branch
}
}
func WithPrivateKeyPath(path string) GitOption {
return func(c *GitClient) {
c.privateKeyPath = path
}
}
type GitCloneOption func(o *git.CloneOptions)
func WithURL(url string) GitCloneOption {
return func(o *git.CloneOptions) {
o.URL = url
}
}
func WithAuthClone(auth transport.AuthMethod) GitCloneOption {
return func(o *git.CloneOptions) {
o.Auth = auth
}
}
func WithRemoteName(name string) GitCloneOption {
return func(o *git.CloneOptions) {
o.RemoteName = name
}
}
func WithSingleBranch(singleBranch bool) GitCloneOption {
return func(o *git.CloneOptions) {
o.SingleBranch = singleBranch
}
}
func WithNoCheckout(noCheckout bool) GitCloneOption {
return func(o *git.CloneOptions) {
o.NoCheckout = noCheckout
}
}
func WithDepthClone(depth int) GitCloneOption {
return func(o *git.CloneOptions) {
o.Depth = depth
}
}
func WithRecurseSubmodules(recurseSubmodules git.SubmoduleRescursivity) GitCloneOption {
return func(o *git.CloneOptions) {
o.RecurseSubmodules = recurseSubmodules
}
}
func WithTags(tags git.TagMode) GitCloneOption {
return func(o *git.CloneOptions) {
o.Tags = tags
}
}
type GitCheckoutOption func(o *git.CheckoutOptions)
func WithBranch(branch string) GitCheckoutOption {
return func(o *git.CheckoutOptions) {
if strings.HasPrefix(branch, "refs/heads") {
o.Branch = plumbing.ReferenceName(branch)
} else {
o.Branch = plumbing.NewBranchReferenceName(branch)
}
}
}
func WithHash(hash string) GitCheckoutOption {
return func(o *git.CheckoutOptions) {
h := plumbing.NewHash(hash)
if h.IsZero() {
return
}
o.Hash = h
}
}
type GitCommitOption func(o *git.CommitOptions)
func WithAll(all bool) GitCommitOption {
return func(o *git.CommitOptions) {
o.All = all
}
}
func WithAuthor(author *object.Signature) GitCommitOption {
return func(o *git.CommitOptions) {
o.Author = author
}
}
func WithCommitter(committer *object.Signature) GitCommitOption {
return func(o *git.CommitOptions) {
o.Committer = committer
}
}
func WithParents(parents []plumbing.Hash) GitCommitOption {
return func(o *git.CommitOptions) {
o.Parents = parents
}
}
type GitPullOption func(o *git.PullOptions)
func WithRemoteNamePull(name string) GitPullOption {
return func(o *git.PullOptions) {
o.RemoteName = name
}
}
func WithBranchNamePull(branch string) GitPullOption {
return func(o *git.PullOptions) {
o.ReferenceName = plumbing.NewBranchReferenceName(branch)
}
}
func WithDepthPull(depth int) GitPullOption {
return func(o *git.PullOptions) {
o.Depth = depth
}
}
func WithAuthPull(auth transport.AuthMethod) GitPullOption {
return func(o *git.PullOptions) {
if auth != nil {
o.Auth = auth
}
}
}
func WithRecurseSubmodulesPull(recurseSubmodules git.SubmoduleRescursivity) GitPullOption {
return func(o *git.PullOptions) {
o.RecurseSubmodules = recurseSubmodules
}
}
func WithForcePull(force bool) GitPullOption {
return func(o *git.PullOptions) {
o.Force = force
}
}
type GitPushOption func(o *git.PushOptions)
func WithRemoteNamePush(name string) GitPushOption {
return func(o *git.PushOptions) {
o.RemoteName = name
}
}
func WithRefSpecs(specs []config.RefSpec) GitPushOption {
return func(o *git.PushOptions) {
o.RefSpecs = specs
}
}
func WithAuthPush(auth transport.AuthMethod) GitPushOption {
return func(o *git.PushOptions) {
o.Auth = auth
}
}
func WithPrune(prune bool) GitPushOption {
return func(o *git.PushOptions) {
o.Prune = prune
}
}
func WithForcePush(force bool) GitPushOption {
return func(o *git.PushOptions) {
o.Force = force
}
}
type GitResetOption func(o *git.ResetOptions)
func WithCommit(commit plumbing.Hash) GitResetOption {
return func(o *git.ResetOptions) {
o.Commit = commit
}
}
func WithMode(mode git.ResetMode) GitResetOption {
return func(o *git.ResetOptions) {
o.Mode = mode
}
}
|
2302_79757062/crawlab
|
vcs/git_options.go
|
Go
|
bsd-3-clause
| 4,946
|
package vcs
import "sync"
var GitMemStorages = sync.Map{}
var GitMemFileSystem = sync.Map{}
|
2302_79757062/crawlab
|
vcs/git_store.go
|
Go
|
bsd-3-clause
| 94
|
package vcs
import (
"github.com/go-git/go-git/v5"
"os"
"path"
)
func CreateBareGitRepo(path string) (err error) {
// validate options
if path == "" {
return ErrInvalidRepoPath
}
// validate if exists
if IsGitRepoExists(path) {
return ErrRepoAlreadyExists
}
// create directory if not exists
_, err = os.Stat(path)
if err != nil {
if err := os.MkdirAll(path, os.FileMode(0766)); err != nil {
return err
}
err = nil
}
// init
if _, err := git.PlainInit(path, true); err != nil {
return err
}
return nil
}
func CloneGitRepo(path, url string, opts ...GitCloneOption) (c *GitClient, err error) {
// url
opts = append(opts, WithURL(url))
// apply options
o := &git.CloneOptions{}
for _, opt := range opts {
opt(o)
}
// clone
if _, err := git.PlainClone(path, false, o); err != nil {
return nil, err
}
return NewGitClient(WithPath(path))
}
func IsGitRepoExists(repoPath string) (ok bool) {
dotGitPath := path.Join(repoPath, git.GitDirName)
if _, err := os.Stat(dotGitPath); err == nil {
return true
}
headPath := path.Join(repoPath, "HEAD")
if _, err := os.Stat(headPath); err == nil {
return true
}
return false
}
|
2302_79757062/crawlab
|
vcs/git_utils.go
|
Go
|
bsd-3-clause
| 1,179
|
package vcs
type Client interface {
Init() (err error)
Dispose() (err error)
Clone(opts ...GitCloneOption) (err error)
Checkout(opts ...GitCheckoutOption) (err error)
Commit(msg string, opts ...GitCommitOption) (err error)
Pull(opts ...GitPullOption) (err error)
Push(opts ...GitPushOption) (err error)
Reset(opts ...GitResetOption) (err error)
}
|
2302_79757062/crawlab
|
vcs/interface.go
|
Go
|
bsd-3-clause
| 356
|
package test
import (
vcs "github.com/crawlab-team/crawlab/vcs"
"io/ioutil"
"os"
"path"
"sync"
"testing"
"time"
)
func init() {
var err error
T, err = NewTest()
if err != nil {
panic(err)
}
}
var T *Test
type Test struct {
RemoteRepoPath string
LocalRepoPath string
LocalRepo *vcs.GitClient
FsRepoPath string
MemRepoPath string
AuthRepoPath string
AuthRepoPath1 string
AuthRepoPath2 string
AuthRepoPath3 string
TestFileName string
TestFileContent string
TestBranchName string
TestCommitMessage string
InitialCommitMessage string
InitialReadmeFileName string
InitialReadmeFileContent string
}
func (t *Test) Setup(t2 *testing.T) {
var err error
t2.Cleanup(t.Cleanup)
// remote repo
if err := vcs.CreateBareGitRepo(t.RemoteRepoPath); err != nil {
panic(err)
}
// local repo (fs)
t.LocalRepo, err = vcs.NewGitClient(
vcs.WithPath(t.LocalRepoPath),
vcs.WithRemoteUrl(t.RemoteRepoPath),
)
if err != nil {
panic(err)
}
// initial commit
filePath := path.Join(t.LocalRepoPath, t.InitialReadmeFileContent)
if err := ioutil.WriteFile(filePath, []byte(t.InitialReadmeFileContent), os.FileMode(0766)); err != nil {
panic(err)
}
if err := t.LocalRepo.CommitAll(t.InitialCommitMessage); err != nil {
panic(err)
}
}
func (t *Test) Cleanup() {
if err := T.LocalRepo.Dispose(); err != nil {
panic(err)
}
if err := os.RemoveAll(T.RemoteRepoPath); err != nil {
panic(err)
}
vcs.GitMemStorages = sync.Map{}
vcs.GitMemFileSystem = sync.Map{}
// wait to avoid caching
time.Sleep(500 * time.Millisecond)
}
func NewTest() (t *Test, err error) {
t = &Test{}
// clear tmp directory
_ = os.RemoveAll("./tmp")
_ = os.MkdirAll("./tmp", os.FileMode(0766))
// remote repo path
t.RemoteRepoPath = "./tmp/test_remote_repo"
// local repo path
t.LocalRepoPath = "./tmp/test_local_repo"
// fs repo path
t.FsRepoPath = "./tmp/test_fs_repo"
// mem repo path
t.MemRepoPath = "./tmp/test_mem_repo"
// auth repo path
t.AuthRepoPath = "./tmp/test_auth_repo"
// auth repo path 1
t.AuthRepoPath1 = "./tmp/test_auth_repo1"
// auth repo path 2
t.AuthRepoPath2 = "./tmp/test_auth_repo2"
// auth repo path 3
t.AuthRepoPath3 = "./tmp/test_auth_repo3"
// test file name
t.TestFileName = "test_file.txt"
// test file content
t.TestFileContent = "it works"
// test branch name
t.TestBranchName = "develop"
// test commit message
t.InitialCommitMessage = "test commit"
// initial commit message
t.InitialCommitMessage = "initial commit"
// initial readme file name
t.InitialReadmeFileName = "README.md"
// initial readme file content
t.InitialReadmeFileContent = "README"
return t, nil
}
|
2302_79757062/crawlab
|
vcs/test/base.go
|
Go
|
bsd-3-clause
| 2,822
|
package test
type Credential struct {
Username string `json:"username"`
Password string `json:"password"`
TestRepoHttpUrl string `json:"test_repo_http_url"`
TestRepoMultiBranchUrl string `json:"test_repo_multi_branch_url"`
SshUsername string `json:"ssh_username"`
SshPassword string `json:"ssh_password"`
TestRepoSshUrl string `json:"test_repo_ssh_url"`
PrivateKey string `json:"private_key"`
PrivateKeyPath string `json:"private_key_path"`
}
|
2302_79757062/crawlab
|
vcs/test/credential.go
|
Go
|
bsd-3-clause
| 538
|
package vcs
import (
"os/user"
"path/filepath"
)
func getDefaultPublicKeyPath() (path string) {
u, err := user.Current()
if err != nil {
return path
}
path = filepath.Join(u.HomeDir, ".ssh", "id_rsa")
return
}
|
2302_79757062/crawlab
|
vcs/utils.go
|
Go
|
bsd-3-clause
| 221
|
FROM golang:1.16
RUN go env -w GOPROXY=https://goproxy.io,https://goproxy.cn && \
go env -w GO111MODULE="on"
WORKDIR /tools
RUN go get github.com/cosmtrek/air
WORKDIR /backend
RUN rm -rf /tools
# set as non-interactive
ENV DEBIAN_FRONTEND noninteractive
# install packages
RUN chmod 777 /tmp \
&& apt-get update \
&& apt-get install -y curl git net-tools iputils-ping ntp ntpdate nginx wget dumb-init cloc
# install python
RUN apt-get install -y python3 python3-pip \
&& ln -s /usr/bin/pip3 /usr/local/bin/pip \
&& ln -s /usr/bin/python3 /usr/local/bin/python
# install golang
RUN curl -OL https://storage.googleapis.com/golang/go1.16.7.linux-amd64.tar.gz \
&& tar -C /usr/local -xvf go1.16.7.linux-amd64.tar.gz \
&& ln -s /usr/local/go/bin/go /usr/local/bin/go \
&& rm go1.16.7.linux-amd64.tar.gz
# install seaweedfs
RUN wget https://github.com/chrislusf/seaweedfs/releases/download/2.76/linux_amd64.tar.gz \
&& tar -zxf linux_amd64.tar.gz \
&& cp weed /usr/local/bin \
&& rm linux_amd64.tar.gz
# install backend
RUN pip install scrapy pymongo bs4 requests -i https://mirrors.aliyun.com/pypi/simple
RUN pip install crawlab-sdk==0.6.b20211024-1207
VOLUME /backend
EXPOSE 8080
|
2302_79757062/crawlab
|
workspace/dockerfiles/golang/Dockerfile
|
Dockerfile
|
bsd-3-clause
| 1,203
|
FROM node:12
WORKDIR frontend
ENV SASS_BINARY_SITE=https://npm.taobao.org/mirrors/node-sass/
RUN npm config set registry "http://registry.npm.taobao.org"
|
2302_79757062/crawlab
|
workspace/dockerfiles/node/Dockerfile
|
Dockerfile
|
bsd-3-clause
| 154
|
package com.example.demo5
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.demo5", appContext.packageName)
}
}
|
2302_80106977/demo4
|
demo5/app/src/androidTest/java/com/example/demo5/ExampleInstrumentedTest.kt
|
Kotlin
|
unknown
| 661
|
package com.example.demo5
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.demo5.data.DataSource
import com.example.demo5.model.Topic
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
Surface(
modifier = Modifier
.fillMaxSize()
.statusBarsPadding(),
color = MaterialTheme.colorScheme.background
) {
TopicGrid(
modifier = Modifier.padding(
start = 8.dp,
top = 8.dp,
end = 8.dp,
)
)
}
}
}
}
@Composable
fun TopicGrid(modifier: Modifier = Modifier) {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier
) {
items(DataSource.topics) { topic ->
TopicCard(topic)
}
}
}
@Composable
fun TopicCard(topic: Topic, modifier: Modifier = Modifier) {
Card(modifier = modifier) {
Row(
// modifier = Modifier.padding(8.dp)
) {
// 左边:图片(保持原有格式)
Box(
modifier = Modifier.size(68.dp)
) {
Image(
painter = painterResource(id = topic.imageRes),
contentDescription = null,
modifier = Modifier.size(68.dp),
contentScale = ContentScale.Crop
)
}
// 右边:垂直排列的两个部分
Column(
modifier = Modifier
.padding(start = 16.dp, 16.dp)
.weight(1f),
verticalArrangement = Arrangement.SpaceBetween
) {
// div2:主题名称
Text(
text = stringResource(id = topic.name),
modifier = Modifier.padding(bottom = 8.dp)
)
// div1:图标和数字的水平排列
Row(
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(R.drawable.ic_grain),
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Text(
text = topic.availableCourses.toString(),
modifier = Modifier.padding(start = 8.dp)
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun TopicPreview() {
val topic = Topic(R.string.photography, 321, R.drawable.ic_grain)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
TopicCard(topic = topic)
}
}
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/MainActivity.kt
|
Kotlin
|
unknown
| 4,533
|
package com.example.demo5.data
import com.example.demo5.R
import com.example.demo5.model.Topic
object DataSource {
val topics = listOf(
Topic(R.string.architecture, 58, R.drawable.img1),
Topic(R.string.automotive, 30, R.drawable.img2),
Topic(R.string.biology, 90, R.drawable.img3),
Topic(R.string.crafts, 121, R.drawable.img4),
Topic(R.string.business, 78, R.drawable.img5),
Topic(R.string.culinary, 118, R.drawable.img6),
Topic(R.string.design, 423, R.drawable.img7),
Topic(R.string.ecology, 28, R.drawable.img8),
Topic(R.string.engineering, 67, R.drawable.img9),
Topic(R.string.fashion, 92, R.drawable.img10),
Topic(R.string.finance, 100, R.drawable.img11),
Topic(R.string.film, 165, R.drawable.img12),
Topic(R.string.gaming, 37, R.drawable.img13),
Topic(R.string.geology, 290, R.drawable.img14),
Topic(R.string.drawing, 326, R.drawable.img15),
Topic(R.string.history, 189, R.drawable.img16),
Topic(R.string.journalism, 96, R.drawable.img17),
Topic(R.string.law, 58, R.drawable.img18),
Topic(R.string.lifestyle, 305, R.drawable.img19),
Topic(R.string.music, 212, R.drawable.img20),
Topic(R.string.painting, 172, R.drawable.img21),
Topic(R.string.photography, 321, R.drawable.img22),
Topic(R.string.physics, 41, R.drawable.img23),
Topic(R.string.tech, 118, R.drawable.img24)
)
}
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/data/DataSource.kt
|
Kotlin
|
unknown
| 1,481
|
package com.example.demo5.model
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
data class Topic(
@StringRes val name: Int,
val availableCourses: Int,
@DrawableRes val imageRes: Int
)
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/model/Topic.kt
|
Kotlin
|
unknown
| 225
|
package com.example.demo5.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/ui/theme/Color.kt
|
Kotlin
|
unknown
| 281
|
package com.example.demo5.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun Demo5Theme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/ui/theme/Theme.kt
|
Kotlin
|
unknown
| 1,690
|
package com.example.demo5.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
2302_80106977/demo4
|
demo5/app/src/main/java/com/example/demo5/ui/theme/Type.kt
|
Kotlin
|
unknown
| 986
|
package com.example.demo5
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
2302_80106977/demo4
|
demo5/app/src/test/java/com/example/demo5/ExampleUnitTest.kt
|
Kotlin
|
unknown
| 341
|
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
}
|
2302_80106977/zxy
|
MyApplication/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
|
Kotlin
|
unknown
| 677
|
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MyApplicationTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Surface(color = Color.Red) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
Greeting("zxy")
}
}
|
2302_80106977/zxy
|
MyApplication/app/src/main/java/com/example/myapplication/MainActivity.kt
|
Kotlin
|
unknown
| 1,493
|
package com.example.myapplication.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
2302_80106977/zxy
|
MyApplication/app/src/main/java/com/example/myapplication/ui/theme/Color.kt
|
Kotlin
|
unknown
| 289
|
package com.example.myapplication.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MyApplicationTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
|
2302_80106977/zxy
|
MyApplication/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt
|
Kotlin
|
unknown
| 1,706
|
package com.example.myapplication.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
2302_80106977/zxy
|
MyApplication/app/src/main/java/com/example/myapplication/ui/theme/Type.kt
|
Kotlin
|
unknown
| 994
|
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
2302_80106977/zxy
|
MyApplication/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
|
Kotlin
|
unknown
| 349
|
package com.example.myui
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myui", appContext.packageName)
}
}
|
2302_80106977/demo2
|
MyUI/app/src/androidTest/java/com/example/myui/ExampleInstrumentedTest.kt
|
Kotlin
|
unknown
| 659
|
package com.example.myui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("zxy")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
// 1. 所有图片资源(再次确认:文件名与 res/drawable 目录下完全一致,无大写/特殊符号)
val backgroundImg = painterResource(R.drawable.erciyuan)
val phoneImg = painterResource(R.drawable.dianhua) // 电话图标
val atImg = painterResource(R.drawable.img2) // @图标
val emailImg = painterResource(R.drawable.img3) // 邮箱图标
val catImg = painterResource(R.drawable.cat) // 主内容猫图
// 时间状态
var currentTime by remember { mutableStateOf(getBeijingTime()) }
androidx.compose.runtime.LaunchedEffect(Unit) {
while (true) {
delay(1000)
currentTime = getBeijingTime()
}
}
// 层叠布局:背景 + 内容
Box(modifier = modifier.fillMaxSize()) {
// 背景图
Image(
painter = backgroundImg,
contentDescription = "页面背景",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
alpha = 0.3f
)
// 上层内容
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
// 时间框
Box(
modifier = Modifier
.fillMaxWidth(0.7f)
.padding(vertical = 16.dp)
.clip(RoundedCornerShape(24.dp))
.background(Color(0xFFADD8E6).copy(alpha = 0.8f))
.padding(vertical = 12.dp, horizontal = 24.dp),
contentAlignment = Alignment.Center
) {
Text(
text = currentTime,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF1E3A5F)
)
}
Spacer(modifier = Modifier.height(32.dp))
// 主内容区域(猫图能显示,说明这里的Image逻辑没问题)
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
Image(
painter = catImg,
contentDescription = "猫图标",
modifier = Modifier
.size(120.dp)
.padding(vertical = 16.dp),
contentScale = ContentScale.Fit // 确保图片完整显示
)
Text(
text = "Hello $name!",
textAlign = TextAlign.Center,
fontSize = 42.sp,
lineHeight = 48.sp,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(vertical = 8.dp)
)
Text(
text = "Welcome to My App",
fontSize = 24.sp,
lineHeight = 28.sp,
fontWeight = FontWeight.Normal,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier.padding(vertical = 8.dp)
)
}
Spacer(modifier = Modifier.height(32.dp))
// 联系信息区域
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 32.dp, vertical = 16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f))
.padding(vertical = 16.dp)
) {
// 用 Image 替代 Icon,逻辑和“猫图”完全一致(猫图能显示,这里也该显示)
ContactRow(img = phoneImg, text = "+86 123 4567 8910")
Spacer(modifier = Modifier.height(12.dp))
ContactRow(img = atImg, text = "@zxy")
Spacer(modifier = Modifier.height(12.dp))
ContactRow(img = emailImg, text = "zxyqq@qq.com")
}
Spacer(modifier = Modifier.height(32.dp))
}
}
}
// 关键修改:用 Image 替代 Icon,添加红色背景测试(能看到红色块说明布局在,只是图没显示)
@Composable
fun ContactRow(
img: androidx.compose.ui.graphics.painter.Painter,
text: String
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 60.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
// 用 Image 替代 Icon,添加红色背景(测试用)
Image(
painter = img,
contentDescription = "联系图标",
modifier = Modifier
.size(28.dp)
.alpha(1f) // 完全不透明,排除透明问题
.background(Color.Red.copy(alpha = 0.3f)), // 红色背景:若看到红色块,说明布局在
contentScale = ContentScale.Fit, // 确保图片完整显示(避免被裁剪)
alpha = 1f // 图片本身完全不透明
)
Spacer(modifier = Modifier.width(30.dp))
Text(
text = text,
fontSize = 18.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.Medium,
color = Color.Black // 固定黑色,确保文本清晰
)
}
}
// 获取北京时间
fun getBeijingTime(): String {
val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
sdf.timeZone = TimeZone.getTimeZone("Asia/Shanghai")
return sdf.format(Date())
}
|
2302_80106977/demo2
|
MyUI/app/src/main/java/com/example/myui/MainActivity.kt
|
Kotlin
|
unknown
| 8,308
|
package com.example.myui.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
2302_80106977/demo2
|
MyUI/app/src/main/java/com/example/myui/ui/theme/Color.kt
|
Kotlin
|
unknown
| 280
|
package com.example.myui.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MyUITheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
|
2302_80106977/demo2
|
MyUI/app/src/main/java/com/example/myui/ui/theme/Theme.kt
|
Kotlin
|
unknown
| 1,688
|
package com.example.myui.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
2302_80106977/demo2
|
MyUI/app/src/main/java/com/example/myui/ui/theme/Type.kt
|
Kotlin
|
unknown
| 985
|
package com.example.myui
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
2302_80106977/demo2
|
MyUI/app/src/test/java/com/example/myui/ExampleUnitTest.kt
|
Kotlin
|
unknown
| 340
|
<!DOCTYPE html>
<html lang="en" ng-app="portainer">
<head>
<meta charset="utf-8">
<title>Portainer面板</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Portainer.io">
<link rel="stylesheet" href="css/app.069dd38e.css">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/app.261b69fc.js"></script>
<!-- Fav and touch icons -->
<link rel="apple-touch-icon" sizes="180x180" href="ico/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="ico/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="ico/favicon-16x16.png">
<link rel="manifest" href="ico/manifest.json">
<link rel="mask-icon" href="ico/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="ico/favicon.ico">
<meta name="msapplication-config" content="ico/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
</head>
<body ng-controller="MainController">
<div id="page-wrapper" ng-class="{
open: toggle && ['portainer.auth', 'portainer.updatePassword', 'portainer.init.admin', 'portainer.init.endpoint'].indexOf($state.current.name) === -1,
nopadding: ['portainer.auth', 'portainer.updatePassword', 'portainer.init.admin', 'portainer.init.endpoint'].indexOf($state.current.name) > -1 || applicationState.loading
}"
ng-cloak>
<div id="sideview" ui-view="sidebar" ng-if="!applicationState.loading"></div>
<div id="content-wrapper">
<div class="page-content">
<div class="page-wrapper" ng-if="applicationState.loading">
<!-- loading box -->
<div class="container simple-box">
<div class="col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3">
<!-- loading box logo -->
<div class="row">
<img ng-if="logo" ng-src="{{ logo }}" class="simple-box-logo">
<img ng-if="!logo" src="images/logo_alt.png" class="simple-box-logo" alt="Portainer">
</div>
<!-- !loading box logo -->
<!-- panel -->
<div class="row" style="text-align: center">
Connecting to the Docker endpoint...
<i class="fa fa-cog fa-spin" style="margin-left: 5px"></i>
</div>
<!-- !panel -->
</div>
</div>
<!-- !loading box -->
</div>
<!-- Main Content -->
<div id="view" ui-view="content" ng-if="!applicationState.loading"></div>
</div><!-- End Page Content -->
</div><!-- End Content Wrapper -->
</div><!-- End Page Wrapper -->
</body>
</html>
|
2302_77879529/lottery
|
doc/assets/Portainer-CN/index.html
|
HTML
|
apache-2.0
| 2,810
|
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50639
Source Host : localhost:3306
Source Schema : lottery
Target Server Type : MySQL
Target Server Version : 50639
File Encoding : 65001
Date: 04/12/2021 12:36:39
*/
create database lottery;
USE lottery;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for activity
-- ----------------------------
DROP TABLE IF EXISTS `activity`;
CREATE TABLE `activity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`activity_id` bigint(20) NOT NULL COMMENT '活动ID',
`activity_name` varchar(64) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '活动名称',
`activity_desc` varchar(128) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '活动描述',
`begin_date_time` datetime(3) DEFAULT NULL COMMENT '开始时间',
`end_date_time` datetime(3) DEFAULT NULL COMMENT '结束时间',
`stock_count` int(11) DEFAULT NULL COMMENT '库存',
`stock_surplus_count` int(11) DEFAULT NULL COMMENT '库存剩余',
`take_count` int(11) DEFAULT NULL COMMENT '每人可参与次数',
`strategy_id` bigint(11) DEFAULT NULL COMMENT '抽奖策略ID',
`state` tinyint(2) DEFAULT NULL COMMENT '活动状态:1编辑、2提审、3撤审、4通过、5运行(审核通过后worker扫描状态)、6拒绝、7关闭、8开启',
`creator` varchar(64) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '创建人',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_activity_id` (`activity_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='活动配置';
-- ----------------------------
-- Records of activity
-- ----------------------------
BEGIN;
INSERT INTO `activity` VALUES (1, 100001, '活动名', '测试活动', '2021-10-01 00:00:00', '2021-12-30 23:59:59', 100, 94, 10, 10001, 5, 'xiaofuge', '2021-08-08 20:14:50', '2021-08-08 20:14:50');
INSERT INTO `activity` VALUES (3, 100002, '活动名02', '测试活动', '2021-10-01 00:00:00', '2021-12-30 23:59:59', 100, 100, 10, 10001, 5, 'xiaofuge', '2021-10-05 15:49:21', '2021-10-05 15:49:21');
COMMIT;
-- ----------------------------
-- Table structure for award
-- ----------------------------
DROP TABLE IF EXISTS `award`;
CREATE TABLE `award` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`award_id` varchar(64) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '奖品ID',
`award_type` tinyint(4) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_award_id` (`award_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='奖品配置';
-- ----------------------------
-- Records of award
-- ----------------------------
BEGIN;
INSERT INTO `award` VALUES (1, '1', 1, 'IMac', 'Code', '2021-08-15 15:38:05', '2021-08-15 15:38:05');
INSERT INTO `award` VALUES (2, '2', 1, 'iphone', 'Code', '2021-08-15 15:38:05', '2021-08-15 15:38:05');
INSERT INTO `award` VALUES (3, '3', 1, 'ipad', 'Code', '2021-08-15 15:38:05', '2021-08-15 15:38:05');
INSERT INTO `award` VALUES (4, '4', 1, 'AirPods', 'Code', '2021-08-15 15:38:05', '2021-08-15 15:38:05');
INSERT INTO `award` VALUES (5, '5', 1, 'Book', 'Code', '2021-08-15 15:38:05', '2021-08-15 15:38:05');
COMMIT;
-- ----------------------------
-- Table structure for rule_tree
-- ----------------------------
DROP TABLE IF EXISTS `rule_tree`;
CREATE TABLE `rule_tree` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tree_name` varchar(64) DEFAULT NULL COMMENT '规则树Id',
`tree_desc` varchar(128) DEFAULT NULL COMMENT '规则树描述',
`tree_root_node_id` bigint(20) DEFAULT NULL COMMENT '规则树根ID',
`create_time` datetime(3) DEFAULT NULL COMMENT '创建时间',
`update_time` datetime(3) DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2110081903 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of rule_tree
-- ----------------------------
BEGIN;
INSERT INTO `rule_tree` VALUES (2110081902, '抽奖活动规则树', '用于决策不同用户可参与的活动', 1, '2021-10-08 15:38:05', '2021-10-08 15:38:05');
COMMIT;
-- ----------------------------
-- Table structure for rule_tree_node
-- ----------------------------
DROP TABLE IF EXISTS `rule_tree_node`;
CREATE TABLE `rule_tree_node` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tree_id` int(2) DEFAULT NULL COMMENT '规则树ID',
`node_type` int(2) DEFAULT NULL COMMENT '节点类型;1子叶、2果实',
`node_value` varchar(32) DEFAULT NULL COMMENT '节点值[nodeType=2];果实值',
`rule_key` varchar(16) DEFAULT NULL COMMENT '规则Key',
`rule_desc` varchar(32) DEFAULT NULL COMMENT '规则描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of rule_tree_node
-- ----------------------------
BEGIN;
INSERT INTO `rule_tree_node` VALUES (1, 2110081902, 1, NULL, 'userGender', '用户性别[男/女]');
INSERT INTO `rule_tree_node` VALUES (11, 2110081902, 1, NULL, 'userAge', '用户年龄');
INSERT INTO `rule_tree_node` VALUES (12, 2110081902, 1, NULL, 'userAge', '用户年龄');
INSERT INTO `rule_tree_node` VALUES (111, 2110081902, 2, '100001', NULL, NULL);
INSERT INTO `rule_tree_node` VALUES (112, 2110081902, 2, '100002', NULL, NULL);
INSERT INTO `rule_tree_node` VALUES (121, 2110081902, 2, '100003', NULL, NULL);
INSERT INTO `rule_tree_node` VALUES (122, 2110081902, 2, '100004', NULL, NULL);
COMMIT;
-- ----------------------------
-- Table structure for rule_tree_node_line
-- ----------------------------
DROP TABLE IF EXISTS `rule_tree_node_line`;
CREATE TABLE `rule_tree_node_line` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tree_id` bigint(20) DEFAULT NULL COMMENT '规则树ID',
`node_id_from` bigint(20) DEFAULT NULL COMMENT '节点From',
`node_id_to` bigint(20) DEFAULT NULL COMMENT '节点To',
`rule_limit_type` int(2) DEFAULT NULL COMMENT '限定类型;1:=;2:>;3:<;4:>=;5<=;6:enum[枚举范围];7:果实',
`rule_limit_value` varchar(32) DEFAULT NULL COMMENT '限定值',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of rule_tree_node_line
-- ----------------------------
BEGIN;
INSERT INTO `rule_tree_node_line` VALUES (1, 2110081902, 1, 11, 1, 'man');
INSERT INTO `rule_tree_node_line` VALUES (2, 2110081902, 1, 12, 1, 'woman');
INSERT INTO `rule_tree_node_line` VALUES (3, 2110081902, 11, 111, 3, '25');
INSERT INTO `rule_tree_node_line` VALUES (4, 2110081902, 11, 112, 4, '25');
INSERT INTO `rule_tree_node_line` VALUES (5, 2110081902, 12, 121, 3, '25');
INSERT INTO `rule_tree_node_line` VALUES (6, 2110081902, 12, 122, 4, '25');
COMMIT;
-- ----------------------------
-- Table structure for strategy
-- ----------------------------
DROP TABLE IF EXISTS `strategy`;
CREATE TABLE `strategy` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`strategy_id` bigint(11) NOT NULL COMMENT '策略ID',
`strategy_desc` varchar(128) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '策略描述',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发放奖品时间',
`ext_info` varchar(128) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展信息',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `strategy_strategyId_uindex` (`strategy_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='策略配置';
-- ----------------------------
-- Records of strategy
-- ----------------------------
BEGIN;
INSERT INTO `strategy` VALUES (1, 10001, 'test', 2, 1, NULL, '', '2021-09-25 08:15:52', '2021-09-25 08:15:52');
COMMIT;
# 转储表 strategy_detail
# ------------------------------------------------------------
DROP TABLE IF EXISTS `strategy_detail`;
CREATE TABLE `strategy_detail` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`strategy_id` bigint NOT NULL COMMENT '策略ID',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '奖品ID',
`award_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '奖品描述',
`award_count` int DEFAULT NULL COMMENT '奖品库存',
`award_surplus_count` int DEFAULT '0' COMMENT '奖品剩余库存',
`award_rate` decimal(5,2) DEFAULT NULL COMMENT '中奖概率',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`),
KEY `idx_strategy_award` (`strategy_id`,`award_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='策略明细';
LOCK TABLES `strategy_detail` WRITE;
/*!40000 ALTER TABLE `strategy_detail` DISABLE KEYS */;
INSERT INTO `strategy_detail` (`id`, `strategy_id`, `award_id`, `award_name`, `award_count`, `award_surplus_count`, `award_rate`, `create_time`, `update_time`)
VALUES
(1,10001,'1','IMac',10,0,0.05,'2021-08-15 15:38:05','2021-08-15 15:38:05'),
(2,10001,'2','iphone',20,19,0.15,'2021-08-15 15:38:05','2021-08-15 15:38:05'),
(3,10001,'3','ipad',50,43,0.20,'2021-08-15 15:38:05','2021-08-15 15:38:05'),
(4,10001,'4','AirPods',100,70,0.25,'2021-08-15 15:38:05','2021-08-15 15:38:05'),
(5,10001,'5','Book',500,389,0.35,'2021-08-15 15:38:05','2021-08-15 15:38:05');
SET FOREIGN_KEY_CHECKS = 1;
|
2302_77879529/lottery
|
doc/assets/sql/lottery.sql
|
PLpgSQL
|
apache-2.0
| 10,499
|
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50639
Source Host : localhost:3306
Source Schema : lottery_01
Target Server Type : MySQL
Target Server Version : 50639
File Encoding : 65001
Date: 11/12/2021 21:31:19
*/
create database lottery_01;
USE lottery_01;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_strategy_export_000
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_000`;
CREATE TABLE `user_strategy_export_000` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_000
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_001
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_001`;
CREATE TABLE `user_strategy_export_001` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_001
-- ----------------------------
BEGIN;
INSERT INTO `user_strategy_export_001` VALUES (1, 'xiaofuge', 100001, 1454347265400504320, 10001, 2, 1, '2021-11-13 13:47:25', 1, '3', 1, 'ipad', 'Code', '1454347264666501120', 1, '2021-10-30 15:19:43', '2021-11-13 13:47:25');
INSERT INTO `user_strategy_export_001` VALUES (2, 'xiaofuge', 100001, 1454351703703945216, 10001, 2, 1, '2021-10-30 15:37:21', 1, '3', 1, 'ipad', 'Code', '1454351703137714176', 1, '2021-10-30 15:37:21', '2021-10-30 15:37:21');
INSERT INTO `user_strategy_export_001` VALUES (3, 'xiaofuge', 100001, 1454355276684722176, 10001, 2, 1, '2021-10-30 15:51:33', 1, '3', 1, 'ipad', 'Code', '1454355275833278464', 1, '2021-10-30 15:51:33', '2021-10-30 15:51:33');
INSERT INTO `user_strategy_export_001` VALUES (4, 'xiaofuge', 100001, 1461956681062809600, 10001, 2, 1, '2021-11-20 15:16:49', 1, '3', 1, 'ipad', 'Code', '1461956679624163328', 1, '2021-11-20 15:16:49', '2021-11-20 15:16:49');
INSERT INTO `user_strategy_export_001` VALUES (5, 'xiaofuge', 100001, 1461957264951869440, 10001, 2, 1, '2021-11-20 15:19:10', 1, '4', 1, 'AirPods', 'Code', '1461957196525993984', 1, '2021-11-20 15:19:08', '2021-11-20 15:19:10');
INSERT INTO `user_strategy_export_001` VALUES (6, 'xiaofuge', 100001, 1461960297911812096, 10001, 2, 1, '2021-11-20 15:31:11', 1, '4', 1, 'AirPods', 'Code', '1461960297228140544', 1, '2021-11-20 15:31:11', '2021-11-20 15:31:11');
INSERT INTO `user_strategy_export_001` VALUES (7, 'xiaofuge', 100001, 1462024810287726592, 10001, 2, 1, '2021-11-20 19:47:32', 1, '4', 1, 'AirPods', 'Code', '1462024809482420224', 1, '2021-11-20 19:47:32', '2021-11-20 19:47:32');
INSERT INTO `user_strategy_export_001` VALUES (8, 'xiaofuge', 100001, 1467000348286812160, 10001, 2, 1, NULL, 0, '5', 1, 'Book', 'Code', '1467000346705559552', 0, '2021-12-04 13:18:33', '2021-12-04 13:18:33');
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_002
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_002`;
CREATE TABLE `user_strategy_export_002` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_002
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_003
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_003`;
CREATE TABLE `user_strategy_export_003` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_003
-- ----------------------------
BEGIN;
INSERT INTO `user_strategy_export_003` VALUES (1, 'Uhdgkw766120d', 120405215, 1443558966104850432, 42480428672, 1, 1, '2021-09-30 20:50:52', 1, '1', 1, 'IMac', '????', '1443558966104850432', NULL, '2021-09-30 20:50:52', '2021-09-30 20:50:52');
INSERT INTO `user_strategy_export_003` VALUES (2, 'fuzhengwei', 100001, 1469660505059753984, 10001, 2, 1, '2021-12-11 21:29:04', 1, '5', 1, 'Book', 'Code', '1469660503969234944', 1, '2021-12-11 21:29:04', '2021-12-11 21:29:04');
INSERT INTO `user_strategy_export_003` VALUES (3, 'fuzhengwei', 100001, 1469660784207462400, 10001, 2, 1, '2021-12-11 21:30:10', 1, '5', 1, 'Book', 'Code', '1469660783494430720', 1, '2021-12-11 21:30:10', '2021-12-11 21:30:10');
COMMIT;
-- ----------------------------
-- Table structure for user_take_activity
-- ----------------------------
DROP TABLE IF EXISTS `user_take_activity`;
CREATE TABLE `user_take_activity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`take_id` bigint(20) DEFAULT NULL COMMENT '活动领取ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`activity_name` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '活动名称',
`take_date` datetime(3) DEFAULT NULL COMMENT '活动领取时间',
`take_count` int(11) DEFAULT NULL COMMENT '领取次数',
`strategy_id` int(11) DEFAULT NULL COMMENT '抽奖策略ID',
`state` tinyint(2) DEFAULT NULL COMMENT '活动单使用状态 0未使用、1已使用',
`uuid` varchar(128) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE COMMENT '防重ID'
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户参与活动记录表';
-- ----------------------------
-- Records of user_take_activity
-- ----------------------------
BEGIN;
INSERT INTO `user_take_activity` VALUES (16, 'Uhdgkw766120d', 1443899607431151616, 100001, 'test', '2021-10-01 19:24:27', 2, NULL, NULL, 'Uhdgkw766120d_100001_2', '2021-10-01 19:24:27', '2021-10-01 19:24:27');
INSERT INTO `user_take_activity` VALUES (17, 'Uhdgkw766120d', 1443900230654394368, 100001, 'test', '2021-10-01 19:26:56', 3, NULL, NULL, 'Uhdgkw766120d_100001_3', '2021-10-01 19:26:56', '2021-10-01 19:26:56');
INSERT INTO `user_take_activity` VALUES (18, 'xiaofuge', 1454347264666501120, 100001, '活动名', '2021-10-30 15:19:43', 1, 10001, 1, 'xiaofuge_100001_1', '2021-10-30 15:19:43', '2021-10-30 15:19:43');
INSERT INTO `user_take_activity` VALUES (19, 'xiaofuge', 1454351703137714176, 100001, '活动名', '2021-10-30 15:37:21', 2, 10001, 1, 'xiaofuge_100001_2', '2021-10-30 15:37:21', '2021-10-30 15:37:21');
INSERT INTO `user_take_activity` VALUES (20, 'xiaofuge', 1454355275833278464, 100001, '活动名', '2021-10-30 15:51:32', 3, 10001, 1, 'xiaofuge_100001_3', '2021-10-30 15:51:33', '2021-10-30 15:51:33');
INSERT INTO `user_take_activity` VALUES (21, 'xiaofuge', 1461956679624163328, 100001, '活动名', '2021-11-20 15:16:13', 4, 10001, 1, 'xiaofuge_100001_4', '2021-11-20 15:16:48', '2021-11-20 15:16:48');
INSERT INTO `user_take_activity` VALUES (22, 'xiaofuge', 1461957196525993984, 100001, '活动名', '2021-11-20 15:18:49', 5, 10001, 1, 'xiaofuge_100001_5', '2021-11-20 15:18:52', '2021-11-20 15:18:52');
INSERT INTO `user_take_activity` VALUES (23, 'xiaofuge', 1461960297228140544, 100001, '活动名', '2021-11-20 15:31:10', 6, 10001, 1, 'xiaofuge_100001_6', '2021-11-20 15:31:11', '2021-11-20 15:31:11');
INSERT INTO `user_take_activity` VALUES (24, 'xiaofuge', 1462024809482420224, 100001, '活动名', '2021-11-20 19:47:31', 7, 10001, 1, 'xiaofuge_100001_7', '2021-11-20 19:47:32', '2021-11-20 19:47:32');
INSERT INTO `user_take_activity` VALUES (25, 'xiaofuge', 1467000346705559552, 100001, '活动名', '2021-12-04 13:18:31', 8, 10001, 1, 'xiaofuge_100001_8', '2021-12-04 13:18:32', '2021-12-04 13:18:32');
INSERT INTO `user_take_activity` VALUES (26, 'fuzhengwei', 1469660503969234944, 100001, '活动名', '2021-12-11 21:29:03', 1, 10001, 1, 'fuzhengwei_100001_1', '2021-12-11 21:29:03', '2021-12-11 21:29:03');
INSERT INTO `user_take_activity` VALUES (27, 'fuzhengwei', 1469660783494430720, 100001, '活动名', '2021-12-11 21:30:08', 2, 10001, 1, 'fuzhengwei_100001_2', '2021-12-11 21:30:10', '2021-12-11 21:30:10');
COMMIT;
-- ----------------------------
-- Table structure for user_take_activity_count
-- ----------------------------
DROP TABLE IF EXISTS `user_take_activity_count`;
CREATE TABLE `user_take_activity_count` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`total_count` int(11) DEFAULT NULL COMMENT '总计可领次数',
`left_count` int(11) DEFAULT NULL COMMENT '剩余领取次数',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uId_activityId` (`u_id`,`activity_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='用户活动参与次数表';
-- ----------------------------
-- Records of user_take_activity_count
-- ----------------------------
BEGIN;
INSERT INTO `user_take_activity_count` VALUES (1, 'Uhdgkw766120d', 100001, 10, 6, '2021-10-01 15:29:27', '2021-10-01 15:29:27');
INSERT INTO `user_take_activity_count` VALUES (2, 'xiaofuge', 100001, 10, 2, '2021-10-30 15:19:43', '2021-10-30 15:19:43');
INSERT INTO `user_take_activity_count` VALUES (3, 'fuzhengwei', 100001, 10, 8, '2021-12-11 21:29:03', '2021-12-11 21:29:03');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
|
2302_77879529/lottery
|
doc/assets/sql/lottery_01.sql
|
PLpgSQL
|
apache-2.0
| 16,211
|
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50639
Source Host : localhost:3306
Source Schema : lottery_02
Target Server Type : MySQL
Target Server Version : 50639
File Encoding : 65001
Date: 11/12/2021 21:31:25
*/
create database lottery_02;
USE lottery_02;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_strategy_export_000
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_000`;
CREATE TABLE `user_strategy_export_000` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_000
-- ----------------------------
BEGIN;
INSERT INTO `user_strategy_export_000` VALUES (1, 'fustack', 100001, 1444540456057864192, 10001, 2, 1, '2021-12-04 14:06:28', 1, '3', 1, 'ipad', 'Code', '1444540456057864192', 0, '2021-10-03 13:50:57', '2021-12-04 14:06:28');
INSERT INTO `user_strategy_export_000` VALUES (2, 'fustack', 100001, 1444541565086367744, 10001, 2, 1, NULL, 0, '5', 1, 'Book', 'Code', '1444541565086367744', 0, '2021-10-03 13:55:22', '2021-10-03 13:55:22');
INSERT INTO `user_strategy_export_000` VALUES (3, 'fustack', 100001, 1444810184030633984, 10001, 2, 1, NULL, 0, '4', 1, 'AirPods', 'Code', '1444810184030633984', 0, '2021-10-04 07:42:45', '2021-10-04 07:42:45');
INSERT INTO `user_strategy_export_000` VALUES (4, 'fustack', 100001, 1444820311156670464, 10001, 2, 1, NULL, 0, '2', 1, 'iphone', 'Code', '1444820311156670464', 0, '2021-10-04 08:23:00', '2021-10-04 08:23:00');
INSERT INTO `user_strategy_export_000` VALUES (5, 'fustack', 100001, 1454313513303539712, 10001, 2, 1, NULL, 0, '4', 1, 'AirPods', 'Code', '1454313490931122176', 1, '2021-10-30 13:05:36', '2021-10-30 13:05:45');
INSERT INTO `user_strategy_export_000` VALUES (6, 'fustack', 100001, 1454313878879076352, 10001, 2, 1, '2021-10-30 13:07:52', 1, '3', 1, 'ipad', 'Code', '1454313878132490240', 1, '2021-10-30 13:07:03', '2021-10-30 13:07:52');
INSERT INTO `user_strategy_export_000` VALUES (7, 'fustack', 100001, 1454314085880561664, 10001, 2, 1, '2021-10-30 13:07:57', 1, '4', 1, 'AirPods', 'Code', '1454314085456936960', 1, '2021-10-30 13:07:52', '2021-10-30 13:07:57');
INSERT INTO `user_strategy_export_000` VALUES (8, 'fustack', 100001, 1454314251442323456, 10001, 2, 1, '2021-10-30 13:08:35', 1, '4', 1, 'AirPods', 'Code', '1454314250930618368', 1, '2021-10-30 13:08:32', '2021-10-30 13:08:35');
INSERT INTO `user_strategy_export_000` VALUES (9, 'fustack', 100001, 1454314395218870272, 10001, 2, 1, '2021-10-30 13:09:11', 1, '3', 1, 'ipad', 'Code', '1454314394698776576', 1, '2021-10-30 13:09:06', '2021-10-30 13:09:11');
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_001
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_001`;
CREATE TABLE `user_strategy_export_001` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_001
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_002
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_002`;
CREATE TABLE `user_strategy_export_002` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_002
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for user_strategy_export_003
-- ----------------------------
DROP TABLE IF EXISTS `user_strategy_export_003`;
CREATE TABLE `user_strategy_export_003` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`order_id` bigint(32) DEFAULT NULL COMMENT '订单ID',
`strategy_id` bigint(20) DEFAULT NULL COMMENT '策略ID',
`strategy_mode` tinyint(2) DEFAULT NULL COMMENT '策略方式(1:单项概率、2:总体概率)',
`grant_type` tinyint(2) DEFAULT NULL COMMENT '发放奖品方式(1:即时、2:定时[含活动结束]、3:人工)',
`grant_date` datetime(3) DEFAULT NULL COMMENT '发奖时间',
`grant_state` tinyint(4) DEFAULT NULL COMMENT '发奖状态',
`award_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '发奖ID',
`award_type` tinyint(2) DEFAULT NULL COMMENT '奖品类型(1:文字描述、2:兑换码、3:优惠券、4:实物奖品)',
`award_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品名称',
`award_content` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '奖品内容「文字描述、Key、码」',
`uuid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`mq_state` tinyint(4) DEFAULT NULL COMMENT '消息发送状态(0未发送、1发送成功、2发送失败)',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户策略计算结果表';
-- ----------------------------
-- Records of user_strategy_export_003
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for user_take_activity
-- ----------------------------
DROP TABLE IF EXISTS `user_take_activity`;
CREATE TABLE `user_take_activity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`take_id` bigint(20) DEFAULT NULL COMMENT '活动领取ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`activity_name` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '活动名称',
`take_date` datetime(3) DEFAULT NULL COMMENT '活动领取时间',
`take_count` int(11) DEFAULT NULL COMMENT '领取次数',
`strategy_id` int(11) DEFAULT NULL COMMENT '抽奖策略ID',
`state` tinyint(2) DEFAULT NULL COMMENT '活动单使用状态 0未使用、1已使用',
`uuid` varchar(128) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '防重ID',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uuid` (`uuid`) USING BTREE COMMENT '防重ID'
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户参与活动记录表';
-- ----------------------------
-- Records of user_take_activity
-- ----------------------------
BEGIN;
INSERT INTO `user_take_activity` VALUES (4, 'fustack', 1444537120189480960, 100001, '???', '2021-10-03 13:37:33', 1, 10001, 1, 'fustack_100001_1', '2021-10-03 13:37:42', '2021-10-03 13:37:42');
INSERT INTO `user_take_activity` VALUES (6, 'fustack', 1444539043961536512, 100001, '???', '2021-10-03 13:45:18', 2, 10001, 1, 'fustack_100001_2', '2021-10-03 13:45:37', '2021-10-03 13:45:37');
INSERT INTO `user_take_activity` VALUES (7, 'fustack', 1444540455500021760, 100001, '???', '2021-10-03 13:50:57', 3, 10001, 1, 'fustack_100001_3', '2021-10-03 13:50:57', '2021-10-03 13:50:57');
INSERT INTO `user_take_activity` VALUES (8, 'fustack', 1444541564645965824, 100001, '???', '2021-10-03 13:55:22', 4, 10001, 1, 'fustack_100001_4', '2021-10-03 13:55:21', '2021-10-03 13:55:21');
INSERT INTO `user_take_activity` VALUES (9, 'fustack', 1444820310565273600, 100001, '???', '2021-10-04 08:23:00', 5, 10001, 1, 'fustack_100001_5', '2021-10-04 08:23:00', '2021-10-04 08:23:00');
INSERT INTO `user_take_activity` VALUES (11, 'fustack', 1454313490931122176, 100001, '活动名', '2021-10-30 13:05:29', 6, 10001, 1, 'fustack_100001_6', '2021-10-30 13:05:30', '2021-10-30 13:05:30');
INSERT INTO `user_take_activity` VALUES (12, 'fustack', 1454313878132490240, 100001, '活动名', '2021-10-30 13:06:59', 7, 10001, 1, 'fustack_100001_7', '2021-10-30 13:07:03', '2021-10-30 13:07:03');
INSERT INTO `user_take_activity` VALUES (13, 'fustack', 1454314085456936960, 100001, '活动名', '2021-10-30 13:07:51', 8, 10001, 1, 'fustack_100001_8', '2021-10-30 13:07:52', '2021-10-30 13:07:52');
INSERT INTO `user_take_activity` VALUES (14, 'fustack', 1454314250930618368, 100001, '活动名', '2021-10-30 13:08:31', 9, 10001, 1, 'fustack_100001_9', '2021-10-30 13:08:31', '2021-10-30 13:08:31');
INSERT INTO `user_take_activity` VALUES (15, 'fustack', 1454314394698776576, 100001, '活动名', '2021-10-30 13:09:06', 10, 10001, 1, 'fustack_100001_10', '2021-10-30 13:09:06', '2021-10-30 13:09:06');
COMMIT;
-- ----------------------------
-- Table structure for user_take_activity_count
-- ----------------------------
DROP TABLE IF EXISTS `user_take_activity_count`;
CREATE TABLE `user_take_activity_count` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`u_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户ID',
`activity_id` bigint(20) DEFAULT NULL COMMENT '活动ID',
`total_count` int(11) DEFAULT NULL COMMENT '总计可领次数',
`left_count` int(11) DEFAULT NULL COMMENT '剩余领取次数',
`create_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime(3) DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_uId_activityId` (`u_id`,`activity_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='用户活动参与次数表';
-- ----------------------------
-- Records of user_take_activity_count
-- ----------------------------
BEGIN;
INSERT INTO `user_take_activity_count` VALUES (1, 'fustack', 100001, 10, 0, '2021-10-03 13:37:42', '2021-10-03 13:37:42');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
|
2302_77879529/lottery
|
doc/assets/sql/lottery_02.sql
|
PLpgSQL
|
apache-2.0
| 14,928
|
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50639
Source Host : localhost:3306
Source Schema : xxl_job
Target Server Type : MySQL
Target Server Version : 50639
File Encoding : 65001
Date: 04/12/2021 16:28:12
*/
create database xxl_job;
USE xxl_job;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for xxl_job_group
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_group`;
CREATE TABLE `xxl_job_group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app_name` varchar(64) NOT NULL COMMENT '执行器AppName',
`title` varchar(12) NOT NULL COMMENT '执行器名称',
`address_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '执行器地址类型:0=自动注册、1=手动录入',
`address_list` text COMMENT '执行器地址列表,多地址逗号分隔',
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_group
-- ----------------------------
BEGIN;
INSERT INTO `xxl_job_group` VALUES (1, 'xxl-job-executor-sample', '示例执行器', 0, NULL, '2021-11-20 20:28:29');
INSERT INTO `xxl_job_group` VALUES (2, 'lottery-job', '抽奖系统任务调度', 0, NULL, '2021-11-20 20:28:29');
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_info
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_info`;
CREATE TABLE `xxl_job_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_group` int(11) NOT NULL COMMENT '执行器主键ID',
`job_desc` varchar(255) NOT NULL,
`add_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`author` varchar(64) DEFAULT NULL COMMENT '作者',
`alarm_email` varchar(255) DEFAULT NULL COMMENT '报警邮件',
`schedule_type` varchar(50) NOT NULL DEFAULT 'NONE' COMMENT '调度类型',
`schedule_conf` varchar(128) DEFAULT NULL COMMENT '调度配置,值含义取决于调度类型',
`misfire_strategy` varchar(50) NOT NULL DEFAULT 'DO_NOTHING' COMMENT '调度过期策略',
`executor_route_strategy` varchar(50) DEFAULT NULL COMMENT '执行器路由策略',
`executor_handler` varchar(255) DEFAULT NULL COMMENT '执行器任务handler',
`executor_param` varchar(512) DEFAULT NULL COMMENT '执行器任务参数',
`executor_block_strategy` varchar(50) DEFAULT NULL COMMENT '阻塞处理策略',
`executor_timeout` int(11) NOT NULL DEFAULT '0' COMMENT '任务执行超时时间,单位秒',
`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT '失败重试次数',
`glue_type` varchar(50) NOT NULL COMMENT 'GLUE类型',
`glue_source` mediumtext COMMENT 'GLUE源代码',
`glue_remark` varchar(128) DEFAULT NULL COMMENT 'GLUE备注',
`glue_updatetime` datetime DEFAULT NULL COMMENT 'GLUE更新时间',
`child_jobid` varchar(255) DEFAULT NULL COMMENT '子任务ID,多个逗号分隔',
`trigger_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '调度状态:0-停止,1-运行',
`trigger_last_time` bigint(13) NOT NULL DEFAULT '0' COMMENT '上次调度时间',
`trigger_next_time` bigint(13) NOT NULL DEFAULT '0' COMMENT '下次调度时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_info
-- ----------------------------
BEGIN;
INSERT INTO `xxl_job_info` VALUES (1, 1, '测试任务1', '2018-11-03 22:21:31', '2021-11-06 14:54:29', 'XXL', '', 'CRON', '0/1 * * * * ?', 'DO_NOTHING', 'FIRST', 'demoJobHandler', '', 'SERIAL_EXECUTION', 0, 0, 'BEAN', '', 'GLUE代码初始化', '2018-11-03 22:21:31', '', 1, 1637411338000, 1637411339000);
INSERT INTO `xxl_job_info` VALUES (2, 2, '活动状态扫描', '2021-11-06 11:43:49', '2021-11-13 10:19:56', '小傅哥', '', 'CRON', '0/1 * * * * ?', 'DO_NOTHING', 'FIRST', 'lotteryActivityStateJobHandler', '', 'SERIAL_EXECUTION', 0, 0, 'BEAN', '', 'GLUE代码初始化', '2021-11-06 11:43:49', '', 0, 0, 0);
INSERT INTO `xxl_job_info` VALUES (3, 2, '扫描用户抽奖奖品发放MQ状态补偿', '2021-11-13 10:23:59', '2021-11-13 13:47:26', '小傅哥', '', 'CRON', '0/5 * * * * ?', 'DO_NOTHING', 'FIRST', 'lotteryOrderMQStateJobHandler', '1', 'SERIAL_EXECUTION', 0, 0, 'BEAN', '', 'GLUE代码初始化', '2021-11-13 10:23:59', '', 0, 0, 0);
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_lock
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_lock`;
CREATE TABLE `xxl_job_lock` (
`lock_name` varchar(50) NOT NULL COMMENT '锁名称',
PRIMARY KEY (`lock_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_lock
-- ----------------------------
BEGIN;
INSERT INTO `xxl_job_lock` VALUES ('schedule_lock');
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_log
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_log`;
CREATE TABLE `xxl_job_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`job_group` int(11) NOT NULL COMMENT '执行器主键ID',
`job_id` int(11) NOT NULL COMMENT '任务,主键ID',
`executor_address` varchar(255) DEFAULT NULL COMMENT '执行器地址,本次执行的地址',
`executor_handler` varchar(255) DEFAULT NULL COMMENT '执行器任务handler',
`executor_param` varchar(512) DEFAULT NULL COMMENT '执行器任务参数',
`executor_sharding_param` varchar(20) DEFAULT NULL COMMENT '执行器任务分片参数,格式如 1/2',
`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT '失败重试次数',
`trigger_time` datetime DEFAULT NULL COMMENT '调度-时间',
`trigger_code` int(11) NOT NULL COMMENT '调度-结果',
`trigger_msg` text COMMENT '调度-日志',
`handle_time` datetime DEFAULT NULL COMMENT '执行-时间',
`handle_code` int(11) NOT NULL COMMENT '执行-状态',
`handle_msg` text COMMENT '执行-日志',
`alarm_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '告警状态:0-默认、1-无需告警、2-告警成功、3-告警失败',
PRIMARY KEY (`id`),
KEY `I_trigger_time` (`trigger_time`),
KEY `I_handle_code` (`handle_code`)
) ENGINE=InnoDB AUTO_INCREMENT=56303 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_log
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_log_report
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_log_report`;
CREATE TABLE `xxl_job_log_report` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trigger_day` datetime DEFAULT NULL COMMENT '调度-时间',
`running_count` int(11) NOT NULL DEFAULT '0' COMMENT '运行中-日志数量',
`suc_count` int(11) NOT NULL DEFAULT '0' COMMENT '执行成功-日志数量',
`fail_count` int(11) NOT NULL DEFAULT '0' COMMENT '执行失败-日志数量',
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `i_trigger_day` (`trigger_day`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_log_report
-- ----------------------------
BEGIN;
INSERT INTO `xxl_job_log_report` VALUES (1, '2021-11-06 00:00:00', 0, 133, 17686, NULL);
INSERT INTO `xxl_job_log_report` VALUES (2, '2021-11-05 00:00:00', 0, 0, 0, NULL);
INSERT INTO `xxl_job_log_report` VALUES (3, '2021-11-04 00:00:00', 0, 0, 0, NULL);
INSERT INTO `xxl_job_log_report` VALUES (4, '2021-11-13 00:00:00', 0, 6, 13177, NULL);
INSERT INTO `xxl_job_log_report` VALUES (5, '2021-11-12 00:00:00', 0, 0, 0, NULL);
INSERT INTO `xxl_job_log_report` VALUES (6, '2021-11-11 00:00:00', 0, 0, 0, NULL);
INSERT INTO `xxl_job_log_report` VALUES (7, '2021-11-20 00:00:00', 0, 0, 25195, NULL);
INSERT INTO `xxl_job_log_report` VALUES (8, '2021-11-19 00:00:00', 0, 0, 0, NULL);
INSERT INTO `xxl_job_log_report` VALUES (9, '2021-11-18 00:00:00', 0, 0, 0, NULL);
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_logglue
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_logglue`;
CREATE TABLE `xxl_job_logglue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_id` int(11) NOT NULL COMMENT '任务,主键ID',
`glue_type` varchar(50) DEFAULT NULL COMMENT 'GLUE类型',
`glue_source` mediumtext COMMENT 'GLUE源代码',
`glue_remark` varchar(128) NOT NULL COMMENT 'GLUE备注',
`add_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_logglue
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_registry
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_registry`;
CREATE TABLE `xxl_job_registry` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`registry_group` varchar(50) NOT NULL,
`registry_key` varchar(255) NOT NULL,
`registry_value` varchar(255) NOT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `i_g_k_v` (`registry_group`,`registry_key`(191),`registry_value`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_registry
-- ----------------------------
BEGIN;
COMMIT;
-- ----------------------------
-- Table structure for xxl_job_user
-- ----------------------------
DROP TABLE IF EXISTS `xxl_job_user`;
CREATE TABLE `xxl_job_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT '账号',
`password` varchar(50) NOT NULL COMMENT '密码',
`role` tinyint(4) NOT NULL COMMENT '角色:0-普通用户、1-管理员',
`permission` varchar(255) DEFAULT NULL COMMENT '权限:执行器ID列表,多个逗号分割',
PRIMARY KEY (`id`),
UNIQUE KEY `i_username` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of xxl_job_user
-- ----------------------------
BEGIN;
INSERT INTO `xxl_job_user` VALUES (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
|
2302_77879529/lottery
|
doc/assets/sql/xxl-job.sql
|
PLpgSQL
|
apache-2.0
| 10,152
|
#!/bin/sh
# 使用说明,用来提示输入参数
usage() {
echo "Usage: sh 执行脚本.sh [base|services|stop|rm]"
exit 1
}
# 启动基础环境(必须)
base(){
docker-compose up -d lottery-mysql lottery-redis lottery-nacos lottery-kafka lottery-zookeeper
}
# 启动程序模块(必须)
services(){
docker-compose up -d lottery-website lottery-api lottery-draw lottery-erp
}
# 关闭所有环境/模块
stop(){
docker-compose stop
}
# 删除所有环境/模块
rm(){
docker-compose rm
}
# 删除所有环境/模块
down(){
docker-compose down
}
# 根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"base")
base
;;
"services")
services
;;
"stop")
stop
;;
"rm")
rm
;;
"down")
down
;;
*)
usage
;;
esac
|
2302_77879529/lottery
|
doc/docker/deploy.sh
|
Shell
|
apache-2.0
| 770
|
FROM openjdk:8-jre
MAINTAINER bytemecc
VOLUME /home/Lottery
RUN mkdir -p /home/Lottery
WORKDIR /home/Lottery
COPY ./jar/Lottery-API.jar /home/Lottery/app.jar
# ADD Lottery-API.jar /app.jar
RUN bash -c 'touch /home/Lottery/app.jar'
ENTRYPOINT ["java","-jar","/home/Lottery/app.jar"]
|
2302_77879529/lottery
|
doc/docker/lottery/api/Dockerfile
|
Dockerfile
|
apache-2.0
| 286
|
FROM openjdk:8-jre
MAINTAINER bytemecc
VOLUME /home/Lottery
RUN mkdir -p /home/Lottery
WORKDIR /home/Lottery
COPY ./jar/Lottery.jar /home/Lottery/app.jar
# ADD Lottery-API.jar /app.jar
RUN bash -c 'touch /home/Lottery/app.jar'
ENTRYPOINT ["java","-jar","/home/Lottery/app.jar"]
|
2302_77879529/lottery
|
doc/docker/lottery/draw/Dockerfile
|
Dockerfile
|
apache-2.0
| 283
|
FROM tomcat:8
COPY /usr/local/tomcat/conf/ ./lottery/erp/conf/
COPY ./webapps/ /usr/local/tomcat/webapps/
|
2302_77879529/lottery
|
doc/docker/lottery/erp/Dockerfile
|
Dockerfile
|
apache-2.0
| 111
|
# 基础镜像
FROM mysql:5.7
# author
MAINTAINER bytemecc
ENV MYSQL_ROOT_PASSWORD "自己的密码"
# 执行sql脚本
COPY ./db/ /docker-entrypoint-initdb.d/
|
2302_77879529/lottery
|
doc/docker/mysql/Dockerfile
|
Dockerfile
|
apache-2.0
| 164
|