model

package
v3.6.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2018 License: LGPL-3.0 Imports: 14 Imported by: 78

README

Package cron implements a cron spec parser and job runner. Usage Callers may register Funcs to be invoked on a given schedule. Cron will run them in their own goroutines. c := cron.New() c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") }) c.AddFunc("@hourly", func() { fmt.Println("Every hour") }) c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") }) c.Start() .. // Funcs are invoked in their own goroutine, asynchronously. ... // Funcs may also be added to a running Cron c.AddFunc("@daily", func() { fmt.Println("Every day") }) .. // Inspect the cron job entries' next and previous run times. inspect(c.Entries()) .. c.Stop() // Stop the scheduler (does not stop any jobs already running). CRON Expression Format A cron expression represents a set of times, using 6 space-separated fields.

Field name Mandatory? Allowed values Allowed special characters
Seconds Yes 0-59 * / , -
Minutes Yes 0-59 * / , -
Hours Yes 0-23 * / , -
Day of month Yes 1-31 * / , - ?
Month Yes 1-12 or JAN-DEC * / , -
Day of week Yes 0-6 or SUN-SAT * / , - ?
Note: Month and Day-of-week field values are case insensitive. "SUN", "Sun",
and "sun" are equally accepted.
Special Characters
Asterisk ( * )
The asterisk indicates that the cron expression will match for all values of the
field; e.g., using an asterisk in the 5th field (month) would indicate every
month.
Slash ( / )
Slashes are used to describe increments of ranges. For example 3-59/15 in the
1st field (minutes) would indicate the 3rd minute of the hour and every 15
minutes thereafter. The form "*/..." is equivalent to the form "first-last/...",
that is, an increment over the largest possible range of the field. The form
"N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the
increment until the end of that specific range. It does not wrap around.
Comma ( , )
Commas are used to separate items of a list. For example, using "MON,WED,FRI" in
the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.
Hyphen ( - )
Hyphens are used to define ranges. For example, 9-17 would indicate every
hour between 9am and 5pm inclusive.
Question mark ( ? )
Question mark may be used instead of '*' for leaving either day-of-month or
day-of-week blank.
Predefined schedules
You may use one of several pre-defined schedules in place of a cron expression.
Entry Description Equivalent To
----- ----------- -------------
@yearly (or @annually) Run once a year, midnight, Jan. 1st 0 0 0 1 1 *
@monthly Run once a month, midnight, first of month 0 0 0 1 * *
@weekly Run once a week, midnight on Sunday 0 0 0 * * 0
@daily (or @midnight) Run once a day, midnight 0 0 0 * * *
@hourly Run once an hour, beginning of hour 0 0 * * * *
Intervals
You may also schedule a job to execute at fixed intervals, starting at the time it's added
or cron is run. This is supported by formatting the cron spec like this:
@every
where "duration" is a string accepted by time.ParseDuration
(http://golang.org/pkg/time/#ParseDuration).
For example, "@every 1h30m10s" would indicate a schedule that activates immediately,
and then every 1 hour, 30 minutes, 10 seconds.
Note: The interval does not take the job runtime into account. For example,
if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes,
it will have only 2 minutes of idle time between each run.
Time zones
All interpretation and scheduling is done in the machine's local time zone (as
provided by the Go time package (http://www.golang.org/pkg/time).
Be aware that jobs scheduled during daylight-savings leap-ahead transitions will
not be run!
Thread safety
Since the Cron service runs concurrently with the calling code, some amount of
care must be taken to ensure proper synchronization.
All cron methods are designed to be correctly synchronized as long as the caller
ensures that invocations have a clear happens-before ordering between them.
Implementation
Cron entries are stored in an array, sorted by their next activation time. Cron
sleeps until the next job is due to be run.
Upon waking:
  • it runs each entry that is active on that second
  • it calculates the next run times for the jobs that were run
  • it re-sorts the array of entries by next activation time.
  • it goes to sleep until the soonest job.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AtLeastOnceStrategy = "AtLeastOnce"

AtLeastOnceStrategy 至少已执行一次

View Source
var ComputeNode = "compute"

ComputeNode 计算节点

View Source
var LBNode = "lb"

LBNode 边缘负载均衡节点

View Source
var ManageNode = "manage"

ManageNode 管理节点

View Source
var SameNodeStrategy = "SameNode"

SameNodeStrategy 相同节点已执行

View Source
var StorageNode = "storage"

StorageNode 存储节点

Functions

func DoRequest

func DoRequest(baseAPI, query, queryType, method string, body []byte) ([]byte, int, error)

Types

type APIHostNode

type APIHostNode struct {
	ID         string            `json:"uuid" validate:"uuid"`
	HostName   string            `json:"host_name" validate:"host_name"`
	InternalIP string            `json:"internal_ip" validate:"internal_ip|ip"`
	ExternalIP string            `json:"external_ip" validate:"external_ip|ip"`
	RootPass   string            `json:"root_pass,omitempty"`
	Role       []string          `json:"role" validate:"role|required"`
	Labels     map[string]string `json:"labels"`
}

APIHostNode api host node

func (APIHostNode) Clone

func (a APIHostNode) Clone() *HostNode

Clone Clone

type AllocatedResources

type AllocatedResources struct {
	CPURequests     int64
	CPULimits       int64
	MemoryRequests  int64
	MemoryLimits    int64
	MemoryRequestsR string
	MemoryLimitsR   string
	CPURequestsR    string
	CPULimitsR      string
}

type Body

type Body struct {
	List interface{} `json:"list"`
	Bean interface{} `json:"bean,omitempty"`
}

type ClusterNode

type ClusterNode struct {
	PID        string          `json:"pid"` // 进程 pid
	Version    string          `json:"version"`
	UpTime     time.Time       `json:"up"`        // 启动时间
	DownTime   time.Time       `json:"down"`      // 上次关闭时间
	Alived     bool            `json:"alived"`    // 是否可用
	Connected  bool            `json:"connected"` // 当 Alived 为 true 时有效,表示心跳是否正常
	Conditions []NodeCondition `json:"conditions"`
}

ClusterNode 集群节点实体

type ClusterResource

type ClusterResource struct {
	Node   int     `json:"node"`
	Tenant int     `json:"tenant"`
	CapCpu int     `json:"cap_cpu"`
	CapMem int     `json:"cap_mem"`
	ReqCpu float32 `json:"req_cpu"`
	ReqMem int     `json:"req_mem"`
}

Resource 资源

type ConditionStatus

type ConditionStatus string

ConditionStatus ConditionStatus

const (
	ConditionTrue    ConditionStatus = "True"
	ConditionFalse   ConditionStatus = "False"
	ConditionUnknown ConditionStatus = "Unknown"
)

These are valid condition statuses. "ConditionTrue" means a resource is in the condition. "ConditionFalse" means a resource is not in the condition. "ConditionUnknown" means kubernetes can't decide if a resource is in the condition or not. In the future, we could add other intermediate conditions, e.g. ConditionDegraded.

type Config

type Config struct {
	Cn    string `json:"cn_name"`
	Name  string `json:"name"`
	Value string `json:"value"`
}

type ConfigUnit

type ConfigUnit struct {
	//配置名称 例如:network
	Name   string `json:"name" validate:"name|required"`
	CNName string `json:"cn_name" validate:"cn_name"`
	//类型 例如:midonet
	Value     interface{} `json:"value" validate:"value|required"`
	ValueType string      `json:"value_type"`
	//可选类型 类型名称和需要的配置项
	OptionalValue []string                `json:"optional_value,omitempty"`
	DependConfig  map[string][]ConfigUnit `json:"depend_config,omitempty"`
	//是否用户可配置
	IsConfigurable bool `json:"is_configurable"`
}

ConfigUnit 一个配置单元

func (ConfigUnit) String

func (c ConfigUnit) String() string

type DependStrategy

type DependStrategy struct {
	DependTaskID      string `json:"depend_task_id"`
	DetermineStrategy string `json:"strategy"`
}

DependStrategy 依赖策略

type ExecedTask

type ExecedTask struct {
	ID             string   `json:"id"`
	Seq            int      `json:"seq"`
	Desc           string   `json:"desc"`
	Status         string   `json:"status"`
	CompleteStatus string   `json:"complete_status"`
	ErrorMsg       string   `json:"err_msg"`
	Depends        []string `json:"dep"`
	Next           []string `json:"next"`
}

type Expr

type Expr struct {
	Body struct {
		// expr
		// in: body
		// required: true
		Expr string `json:"expr" validate:"expr|required"`
	}
}

type FirstConfig

type FirstConfig struct {
	StorageMode     string `json:"storage_mode"`
	StorageHost     string `json:"storage_host,omitempty"`
	StorageEndPoint string `json:"storage_endpoint,omitempty"`

	NetworkMode string `json:"network_mode"`
	ZKHosts     string `json:"zk_host,omitempty"`
	CassandraIP string `json:"cassandra_ip,omitempty"`
	K8SAPIAddr  string `json:"k8s_apiserver,omitempty"`
	MasterIP    string `json:"master_ip,omitempty"`
	DNS         string `json:"dns,omitempty"`
	ZMQSub      string `json:"zmq_sub,omitempty"`
	ZMQTo       string `json:"zmq_to,omitempty"`
	EtcdIP      string `json:"etcd_ip,omitempty"`
}

type GlobalConfig

type GlobalConfig struct {
	Configs map[string]*ConfigUnit `json:"configs"`
}

GlobalConfig 全局配置

func CreateDefaultGlobalConfig

func CreateDefaultGlobalConfig() *GlobalConfig

CreateDefaultGlobalConfig 生成默认配置

func CreateGlobalConfig

func CreateGlobalConfig(kvs []*mvccpb.KeyValue) (*GlobalConfig, error)

CreateGlobalConfig 生成配置

func (*GlobalConfig) Add

func (g *GlobalConfig) Add(c ConfigUnit)

Add 添加配置

func (GlobalConfig) Bytes

func (g GlobalConfig) Bytes() []byte

Bytes Bytes

func (*GlobalConfig) Delete

func (g *GlobalConfig) Delete(Name string)

Delete 删除配置

func (*GlobalConfig) Get

func (g *GlobalConfig) Get(name string) *ConfigUnit

Get 获取配置

func (*GlobalConfig) String

func (g *GlobalConfig) String() string

String String

type HostNode

type HostNode struct {
	ID              string            `json:"uuid"`
	HostName        string            `json:"host_name"`
	CreateTime      time.Time         `json:"create_time"`
	InternalIP      string            `json:"internal_ip"`
	ExternalIP      string            `json:"external_ip"`
	RootPass        string            `json:"root_pass,omitempty"`
	KeyPath         string            `json:"key_path,omitempty"` //管理节点key文件路径
	AvailableMemory int64             `json:"available_memory"`
	AvailableCPU    int64             `json:"available_cpu"`
	Mode            string            `json:"mode"`
	Role            HostRule          `json:"role"`          //节点属性 compute manage storage
	Status          string            `json:"status"`        //节点状态 create,init,running,stop,delete
	Labels          map[string]string `json:"labels"`        //节点标签 内置标签+用户自定义标签
	Unschedulable   bool              `json:"unschedulable"` //不可调度
	NodeStatus      *v1.NodeStatus    `json:"node_status,omitempty"`
	ClusterNode
}

HostNode 集群节点实体

func GetNodeFromKV

func GetNodeFromKV(kv *mvccpb.KeyValue) *HostNode

GetNodeFromKV 从etcd解析node信息

func GetNodes

func GetNodes() (nodes []*HostNode, err error)

GetNodes 获取节点

func (*HostNode) Decode

func (n *HostNode) Decode(data []byte) error

Decode decode node info

func (*HostNode) Del

func (h *HostNode) Del() (*client.DeleteResponse, error)

Del 删除

func (*HostNode) DeleteCondition

func (h *HostNode) DeleteCondition(types ...NodeConditionType)

DeleteCondition DeleteCondition

func (*HostNode) DeleteNode

func (h *HostNode) DeleteNode() (*client.DeleteResponse, error)

DeleteNode 删除节点

func (*HostNode) Down

func (h *HostNode) Down()

Down 节点下线

func (*HostNode) Put

func (h *HostNode) Put(opts ...client.OpOption) (*client.PutResponse, error)

Put 节点上线更新

func (*HostNode) String

func (h *HostNode) String() string

String string

func (*HostNode) UpdataCondition

func (n *HostNode) UpdataCondition(conditions ...NodeCondition)

UpdataCondition 更新状态

func (*HostNode) UpdataK8sCondition

func (n *HostNode) UpdataK8sCondition(conditions []v1.NodeCondition)

UpdataK8sCondition 更新k8s节点的状态到rainbond节点

func (*HostNode) Update

func (h *HostNode) Update() (*client.PutResponse, error)

Update 更新节点信息,由节点启动时调用

type HostRule

type HostRule []string

HostRule 节点角色

func (HostRule) HasRule

func (h HostRule) HasRule(rule string) bool

HasRule 是否具有什么角色

func (HostRule) String

func (h HostRule) String() string

type InitStatus

type InitStatus struct {
	Status   int    `json:"status"`
	StatusCN string `json:"cn"`
	HostID   string `json:"uuid"`
}

type InstallStatus

type InstallStatus struct {
	Status   int           `json:"status"`
	StatusCN string        `json:"cn"`
	Tasks    []*ExecedTask `json:"tasks"`
}

type Login

type Login struct {
	HostPort  string `json:"hostport"`
	LoginType bool   `json:"type"`
	HostType  string `json:"hosttype"`
	RootPwd   string `json:"pwd,omitempty"`
}

type LoginResult

type LoginResult struct {
	HostPort  string `json:"hostport"`
	LoginType bool   `json:"type"`
	Result    string `json:"result"`
}

type NodeCondition

type NodeCondition struct {
	// Type of node condition.
	Type NodeConditionType `json:"type" `
	// Status of the condition, one of True, False, Unknown.
	Status ConditionStatus `json:"status" `
	// Last time we got an update on a given condition.
	// +optional
	LastHeartbeatTime time.Time `json:"lastHeartbeatTime,omitempty" `
	// Last time the condition transit from one status to another.
	// +optional
	LastTransitionTime time.Time `json:"lastTransitionTime,omitempty" `
	// (brief) reason for the condition's last transition.
	// +optional
	Reason string `json:"reason,omitempty"`
	// Human readable message indicating details about last transition.
	// +optional
	Message string `json:"message,omitempty"`
}

NodeCondition contains condition information for a node.

type NodeConditionType

type NodeConditionType string

NodeConditionType NodeConditionType

const (
	// NodeReady means this node is working
	NodeReady NodeConditionType = "Ready"
	// InstallNotReady means  the installation task was not completed in this node.
	InstallNotReady NodeConditionType = "InstallNotReady"
	// NodeInit means node already install rainbond node and regist
	NodeInit       NodeConditionType = "NodeInit"
	OutOfDisk      NodeConditionType = "OutOfDisk"
	MemoryPressure NodeConditionType = "MemoryPressure"
	DiskPressure   NodeConditionType = "DiskPressure"
)

These are valid conditions of node.

func (NodeConditionType) Compare

func (nt NodeConditionType) Compare(ent NodeConditionType) bool

Compare 比较

type NodeDetails

type NodeDetails struct {
	Name               string              `json:"name"`
	Role               []string            `json:"role"`
	Status             string              `json:"status"`
	Labels             map[string]string   `json:"labels"`
	Annotations        map[string]string   `json:"annotations"`
	CreationTimestamp  string              `json:"creationtimestamp"`
	Conditions         []v1.NodeCondition  `json:"conditions"`
	Addresses          map[string]string   `json:"addresses"`
	Capacity           map[string]string   `json:"capacity"`
	Allocatable        map[string]string   `json:"allocatable"`
	SystemInfo         v1.NodeSystemInfo   `json:"systeminfo"`
	ExternalID         string              `json:"externalid"`
	NonterminatedPods  []*Pods             `json:"nonterminatedpods"`
	AllocatedResources map[string]string   `json:"allocatedresources"`
	Events             map[string][]string `json:"events"`
}

NodeDetails NodeDetails

type NodeList

type NodeList []*HostNode

func (NodeList) Len

func (list NodeList) Len() int

func (NodeList) Less

func (list NodeList) Less(i, j int) bool

func (NodeList) Swap

func (list NodeList) Swap(i, j int)

type NodePodResource

type NodePodResource struct {
	AllocatedResources `json:"allocatedresources"`
	Resource           `json:"allocatable"`
}

type Pods

type Pods struct {
	Namespace       string `json:"namespace"`
	Id              string `json:"id"`
	Name            string `json:"name"`
	TenantName      string `json:"tenant_name"`
	CPURequests     string `json:"cpurequest"`
	CPURequestsR    string `json:"cpurequestr"`
	CPULimits       string `json:"cpulimits"`
	CPULimitsR      string `json:"cpulimitsr"`
	MemoryRequests  string `json:"memoryrequests"`
	MemoryRequestsR string `json:"memoryrequestsr"`
	MemoryLimits    string `json:"memorylimits"`
	MemoryLimitsR   string `json:"memorylimitsr"`
}

type Prome

type Prome struct {
	Status string    `json:"status"`
	Data   PromeData `json:"data"`
}

type PromeData

type PromeData struct {
	ResultType string             `json:"resultType"`
	Result     []*PromeResultCore `json:"result"`
}

type PromeResultCore

type PromeResultCore struct {
	Metric map[string]string `json:"metric"`
	Value  []interface{}     `json:"value"`
	Values []interface{}     `json:"values"`
}

type PrometheusAPI

type PrometheusAPI struct {
	API string
}

func (*PrometheusAPI) Query

func (s *PrometheusAPI) Query(query string) (*Prome, *utils.APIHandleError)

Get Get

func (*PrometheusAPI) QueryRange

func (s *PrometheusAPI) QueryRange(query string, start, end, step string) (*Prome, *utils.APIHandleError)

Get Get

type PrometheusInterface

type PrometheusInterface interface {
	Query(query string) *Prome
	QueryRange(query string, start, end, step string) *Prome
}

type Resource

type Resource struct {
	CpuR int `json:"cpu"`
	MemR int `json:"mem"`
}

Resource 资源

type ResponseBody

type ResponseBody struct {
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
	MsgCN string `json:"msgcn"`
	Body  Body   `json:"body,omitempty"`
}

type Scheduler

type Scheduler struct {
	Mode   string                     `json:"mode"` //立即调度(Intime),触发调度(Passive)
	Status map[string]SchedulerStatus `json:"status"`
}

Scheduler 调度状态

type SchedulerStatus

type SchedulerStatus struct {
	Status          string    `json:"status"`
	Message         string    `json:"message"`
	SchedulerTime   time.Time `json:"scheduler_time"`   //调度时间
	SchedulerMaster string    `json:"scheduler_master"` //调度的管理节点
}

SchedulerStatus 调度状态

type Shell

type Shell struct {
	Cmd []string `json:"cmd"`
}

Shell 执行脚本配置

type Task

type Task struct {
	Name    string    `json:"name" validate:"name|required"`
	ID      string    `json:"id" validate:"id|uuid"`
	TempID  string    `json:"temp_id,omitempty" validate:"temp_id|uuid"`
	Temp    *TaskTemp `json:"temp,omitempty"`
	GroupID string    `json:"group_id,omitempty"`
	//执行的节点
	Nodes []string `json:"nodes"`
	//执行时间定义
	//例如每30分钟执行一次:@every 30m
	Timer   string `json:"timer"`
	TimeOut int64  `json:"time_out"`
	// 执行任务失败重试次数
	// 默认为 0,不重试
	Retry int `json:"retry"`
	// 执行任务失败重试时间间隔
	// 单位秒,如果不大于 0 则马上重试
	Interval int `json:"interval"`
	//ExecCount 执行次数
	ExecCount int `json:"exec_count"`
	//每个执行节点执行状态
	Status       map[string]TaskStatus `json:"status,omitempty"`
	Scheduler    Scheduler             `json:"scheduler"`
	CreateTime   time.Time             `json:"create_time"`
	StartTime    time.Time             `json:"start_time"`
	CompleteTime time.Time             `json:"complete_time"`
	ResultPath   string                `json:"result_path"`
	EventID      string                `json:"event_id"`
	RunMode      string                `json:"run_mode"`
	OutPut       []*TaskOutPut         `json:"out_put"`
}

Task 任务

func (Task) CanBeDelete

func (t Task) CanBeDelete() bool

CanBeDelete 能否被删除

func (*Task) Decode

func (t *Task) Decode(data []byte) error

Decode Decode

func (Task) String

func (t Task) String() string

func (*Task) UpdataOutPut

func (t *Task) UpdataOutPut(output TaskOutPut)

UpdataOutPut 更新状态

type TaskGroup

type TaskGroup struct {
	Name       string           `json:"name" validate:"name|required"`
	ID         string           `json:"id" validate:"id|uuid"`
	Tasks      []*Task          `json:"tasks"`
	CreateTime time.Time        `json:"create_time"`
	Status     *TaskGroupStatus `json:"status"`
}

TaskGroup 任务组

func (TaskGroup) CanBeDelete

func (t TaskGroup) CanBeDelete() bool

CanBeDelete 是否能被删除

func (TaskGroup) String

func (t TaskGroup) String() string

type TaskGroupStatus

type TaskGroupStatus struct {
	TaskStatus map[string]TaskStatus `json:"task_status"`
	InitTime   time.Time             `json:"init_time"`
	StartTime  time.Time             `json:"start_time"`
	EndTime    time.Time             `json:"end_time"`
	Status     string                `json:"status"` //create init exec complete timeout
}

TaskGroupStatus 任务组状态

type TaskOutPut

type TaskOutPut struct {
	NodeID string            `json:"node_id"`
	JobID  string            `json:"job_id"`
	Global map[string]string `json:"global"`
	Inner  map[string]string `json:"inner"`
	//返回数据类型,检测结果类(check) 执行安装类 (install) 普通类 (common)
	Type       string             `json:"type"`
	Status     []TaskOutPutStatus `json:"status"`
	ExecStatus string             `json:"exec_status"`
	Body       string             `json:"body"`
}

TaskOutPut 任务输出

func ParseTaskOutPut

func ParseTaskOutPut(body string) (t TaskOutPut, err error)

ParseTaskOutPut json parse

type TaskOutPutStatus

type TaskOutPutStatus struct {
	Name string `json:"name"`
	//节点属性
	ConditionType string `json:"condition_type"`
	//节点属性值
	ConditionStatus string   `json:"condition_status"`
	NextTask        []string `json:"next_tasks,omitempty"`
	NextGroups      []string `json:"next_groups,omitempty"`
}

TaskOutPutStatus 输出数据

type TaskResult

type TaskResult []*ExecedTask

func (TaskResult) Len

func (c TaskResult) Len() int

func (TaskResult) Less

func (c TaskResult) Less(i, j int) bool

func (TaskResult) Swap

func (c TaskResult) Swap(i, j int)

type TaskStatus

type TaskStatus struct {
	JobID        string    `json:"job_id"`
	Status       string    `json:"status"` //执行状态,create init exec complete timeout
	StartTime    time.Time `json:"start_time"`
	EndTime      time.Time `json:"end_time"`
	TakeTime     int       `json:"take_time"`
	CompleStatus string    `json:"comple_status"`
	//脚本退出码
	ShellCode int    `json:"shell_code"`
	Message   string `json:"message,omitempty"`
}

TaskStatus 任务状态

type TaskTemp

type TaskTemp struct {
	Name       string            `json:"name" validate:"name|required"`
	ID         string            `json:"id" validate:"id|uuid"`
	Shell      Shell             `json:"shell"`
	Envs       map[string]string `json:"envs,omitempty"`
	Input      string            `json:"input,omitempty"`
	Args       []string          `json:"args,omitempty"`
	Depends    []DependStrategy  `json:"depends,omitempty"`
	Timeout    int               `json:"timeout" validate:"timeout|required|numeric"`
	CreateTime time.Time         `json:"create_time"`
	Labels     map[string]string `json:"labels,omitempty"`
}

TaskTemp 任务模版

func (TaskTemp) String

func (t TaskTemp) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL