github.com/mmatczuk/gohan@v0.0.0-20170206152520-30e45d9bdb69/extension/gohanscript/lib/job.go (about) 1 // Copyright (C) 2016 Juniper Networks, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 // implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 package lib 17 18 import ( 19 "github.com/cloudwan/gohan/extension/gohanscript" 20 "github.com/cloudwan/gohan/job" 21 ) 22 23 func init() { 24 gohanscript.RegisterStmtParser("job", backgroundJob) 25 } 26 27 func backgroundJob(stmt *gohanscript.Stmt) (func(*gohanscript.Context) (interface{}, error), error) { 28 stmts, err := gohanscript.MakeStmts(stmt.File, stmt.RawNode["job"]) 29 if err != nil { 30 return nil, stmt.Errorf("background code error: %s", err) 31 } 32 queueArg, err := gohanscript.NewValue(stmt.RawData["queue"]) 33 if err != nil { 34 return nil, stmt.Errorf("background code error: %s", err) 35 } 36 f, err := gohanscript.StmtsToFunc("job", stmts) 37 if err != nil { 38 return nil, err 39 } 40 return func(context *gohanscript.Context) (interface{}, error) { 41 queue := queueArg.Value(context).(*job.Queue) 42 newContext := context.Extend(map[string]interface{}{}) 43 queue.Add( 44 job.NewJob(func() { 45 f(newContext) 46 newContext.VM.Stop() 47 })) 48 return nil, nil 49 }, nil 50 } 51 52 //MakeQueue makes new worker queue with specfied workers 53 func MakeQueue(workers int) *job.Queue { 54 return job.NewQueue(uint(workers)) 55 } 56 57 //WaitQueue waits queue get empty 58 func WaitQueue(queue *job.Queue) { 59 queue.Wait() 60 } 61 62 //Stop stops work queue 63 func Stop(queue *job.Queue) { 64 queue.Stop() 65 } 66 67 //ForceStop force stop queue 68 func ForceStop(queue *job.Queue) { 69 queue.ForceStop() 70 }