// setUpEnvironment sets the environment for the tests up. func setUpEnvironment(param scenarioParam) (*Environment, *OrdersAndShipments) { applog.Infof("starting set-up of environment") rand.Seed(time.Now().Unix()) env := NewEnvironment(Id(param.Id)) oas := newOrdersAndShipments(param.Orders) bfm := BehaviorFactoryMap{ "shop": NewShopBehaviorFactory(oas), "supply": SupplyBehaviorFactory, "distribution": NewDistributionBehaviorFactory(oas), "manufacturer": BroadcastBehaviorFactory, } manufacturerRange := param.Items / 10 for i := 1; i < 11; i++ { manufacturerId := NewId("manufacturer", i-1) itemNoLow := (i - 1) * manufacturerRange itemNoHigh := i*manufacturerRange - 1 packagingSize := (rand.Intn(99) + 1) * 10 bfm[manufacturerId] = NewManufacturerBehaviorFactory(itemNoLow, itemNoHigh, packagingSize) } for itemNo := 0; itemNo <= param.Items; itemNo++ { stockCellId := NewId("stock", itemNo) bfm[stockCellId] = NewStockItemBehaviorFactory(itemNo) } sm := SubscriptionMap{ "supply": {"manufacturer"}, "manufacturer": { "manufacturer:0", "manufacturer:1", "manufacturer:2", "manufacturer:3", "manufacturer:4", "manufacturer:5", "manufacturer:6", "manufacturer:7", "manufacturer:8", "manufacturer:9", }, "manufacturer:0": {"supply"}, "manufacturer:1": {"supply"}, "manufacturer:2": {"supply"}, "manufacturer:3": {"supply"}, "manufacturer:4": {"supply"}, "manufacturer:5": {"supply"}, "manufacturer:6": {"supply"}, "manufacturer:7": {"supply"}, "manufacturer:8": {"supply"}, "manufacturer:9": {"supply"}, } applog.Infof("adding cells, subscriptions and ticker") env.AddCells(bfm) env.SubscribeAll(sm) env.AddTicker("manufacturing", "supply", 500*time.Millisecond) env.AddTicker("shipment", "manufacturer", 100*time.Millisecond) applog.Infof("set-up of environment done") return env, oas }
func (a *ManufacturerAgent) Process(event ebus.Event) error { switch event.Topic() { case a.orderedTopic: // Store a new manufacturing order. var item OrderItem a.err = event.Payload(&item) if a.err != nil { return a.err } a.openOrders[item.ItemNo] += item.Quantity case a.manufacturedTopic: // Deliver random numbers of each item. a.shipmentNo++ shipment := Shipment{a.shipmentNo, 0, make(map[int]ShipmentItem)} for itemNo, quantity := range a.openOrders { shipmentQuantity := rand.Intn(quantity) + 1 if quantity == shipmentQuantity { delete(a.openOrders, itemNo) } else { a.openOrders[itemNo] = quantity - shipmentQuantity } shipment.ShipmentItems[itemNo] = ShipmentItem{a.shipmentNo, itemNo, shipmentQuantity} } ebus.Emit(shipment, "ManufacturingShipped") } if len(a.openOrders)%10 == 0 { applog.Infof("manufacturer: topic %q open orders are %d", event.Topic(), len(a.openOrders)) } return nil }
func (a *DeliveryAgent) Process(event ebus.Event) error { switch event.Topic() { case a.receivedTopic: // Received a new order. var order Order a.err = event.Payload(&order) if a.err != nil { return a.err } a.openOrders[order.OrderNo] = true case a.packedTopic: // Deliver the packed order. var shipment Shipment a.err = event.Payload(&shipment) if a.err != nil { return a.err } delete(a.openOrders, shipment.OrderNo) ebus.Emit(len(a.openOrders), "OrderDelivered") } if len(a.openOrders)%10 == 0 { applog.Infof("delivery: topic %q open orders are %d", event.Topic(), len(a.openOrders)) } return nil }
// runScenarioTest runs a test with the given number of orders func runScenarioTest(assert *asserts.Asserts, param scenarioParam) { applog.Infof(param.String()) monitoring.Reset() env, oas := setUpEnvironment(param) for on := 0; on < param.Orders; on++ { env.EmitSimple("shop", "order", generateOrder(on, param.Items)) } oas.Wait(param.Orders) ol, sl := oas.Lengths() assert.Equal(ol, param.Orders, "All orders have been placed.") assert.Equal(sl, param.Orders, "All orders have been delivered.") assert.Equal(ol, sl, "The number of orders and shipments is equal.") time.Sleep(2 * time.Second) env.Shutdown() time.Sleep(2 * time.Second) monitoring.MeasuringPointsPrintAll() monitoring.StaySetVariablesPrintAll() }
// Dispatch the encapsulated request to the according handler methods // depending on the HTTP method. func dispatch(ctx *Context, h ResourceHandler) bool { defer func() { if err := recover(); err != nil { // Shit happens! TODO: Better error handling. msg := fmt.Sprintf("internal server error: '%v' in context: '%v'", err, ctx) applog.Criticalf(msg) http.Error(ctx.ResponseWriter, msg, http.StatusInternalServerError) } }() applog.Infof("dispatching %s", ctx) switch ctx.Request.Method { case "GET": return h.Get(ctx) case "PUT": if ph, ok := h.(PutResourceHandler); ok { return ph.Put(ctx) } case "POST": if ph, ok := h.(PostResourceHandler); ok { return ph.Post(ctx) } case "DELETE": if dh, ok := h.(DeleteResourceHandler); ok { return dh.Delete(ctx) } } applog.Errorf("method not allowed: %s", ctx) http.Error(ctx.ResponseWriter, "405 method not allowed", http.StatusMethodNotAllowed) return false }
// Stop the behavior. func (b *supplyBehavior) Stop() { for itemNo, quantity := range b.itemQuantities { if quantity > 0 { applog.Infof("supply needs still %d pieces of item %d", quantity, itemNo) } } }
// Stop the behavior. func (b *stockItemBehavior) Stop() { quantity := 0 for _, orderItem := range b.orderItems { quantity += orderItem.Quantity } if quantity > 0 { applog.Infof("stock item %d needs %d items, has %d", b.itemNo, quantity, b.quantity) } }
// Test log at all levels. func TestAllLevels(t *testing.T) { applog.SetLevel(applog.LevelDebug) applog.Debugf("Debug.") applog.Infof("Info.") applog.Warningf("Warning.") applog.Errorf("Error.") applog.Criticalf("Critical.") }
// Test logging from level warning and above. func TestWarningAndAbove(t *testing.T) { applog.SetLevel(applog.LevelWarning) applog.Debugf("Debug.") applog.Infof("Info.") applog.Warningf("Warning.") applog.Errorf("Error.") applog.Criticalf("Critical.") }
func Main() { logLevel := flag.Int("log", applog.LevelDebug, "The Logging Level[0-4]") flag.Parse() setupLogger(*logLevel) world.Start() http.HandleFunc("/ws", serveWs) applog.Infof("Starting websocket listener on port 8888") http.ListenAndServe(":8888", nil) }
// Stop ends the collecting. func (oas *OrdersAndShipments) Wait(orders int) { timeout := time.Duration(10*orders) * time.Millisecond applog.Infof("waiting for max %v", timeout) select { case <-oas.DoneChan: return case <-time.After(timeout): return } }
// Test getting a doc. func TestGet(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) u, _ := url.Parse("http://www.rssboard.org/files/sample-rss-2.xml") r, err := rss.Get(u) assert.Nil(err, "Getting the RSS document returns no error.") err = r.Validate() assert.Nil(err, "Validating returns no error.") b := &bytes.Buffer{} err = rss.Encode(b, r) assert.Nil(err, "Encoding returns no error.") applog.Infof("--- RSS ---\n%s", b) }
// Test getting a feed. func TestGet(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) u, _ := url.Parse("http://mue.tideland.biz/feeds/posts/default") f, err := atom.Get(u) assert.Nil(err, "Getting the Atom document returns no error.") err = f.Validate() assert.Nil(err, "Validating returns no error.") b := &bytes.Buffer{} err = atom.Encode(b, f) assert.Nil(err, "Encoding returns no error.") applog.Infof("--- Atom ---\n%s", b) }
func (a *WaitAgent) Process(event ebus.Event) error { var rest int a.err = event.Payload(&rest) if a.err != nil { return a.err } applog.Infof("wait: %d orders remaining", rest) if rest == 0 { a.done <- true } return nil }
// Test logging with the go logger. func TestGoLogger(t *testing.T) { log.SetOutput(os.Stdout) applog.SetLevel(applog.LevelDebug) applog.SetLogger(applog.GoLogger{}) applog.Debugf("Debug.") applog.Infof("Info.") applog.Warningf("Warning.") applog.Errorf("Error.") applog.Criticalf("Critical.") }
// runScenarioTest runs a test with the given number of orders func runScenarioTest(assert *asserts.Asserts, param scenarioParam) { applog.Infof(param.String()) monitoring.Reset() // Prepare test. done := make(chan bool) provider := config.NewMapConfigurationProvider() config := config.New(provider) config.Set("backend", "single") assert.Nil(ebus.Init(config), "single node backend started") StartShopAgent() StartWarehouseAgent() StartManufacturerAgent() StartDeliveryAgent() StartWaitAgent(done) // Run orders. for on := 0; on < param.Orders; on++ { order := generateOrder(on) err := ebus.Emit(order, "OrderReceived") assert.Nil(err, "order emitted") } select { case <-done: applog.Infof("order processing done") case <-time.After(param.Timeout): assert.Fail("timeout during wait for processed orders") } // Finalize test. err := ebus.Stop() assert.Nil(err, "stopped the bus") time.Sleep(time.Second) monitoring.MeasuringPointsPrintAll() }
// loop is the backend loop for the collector. func (oas *OrdersAndShipments) loop() { for { select { case order := <-oas.OrderChan: oas.Orders[order.OrderNo] = order case shipment := <-oas.ShipmentChan: oas.Shipments[shipment.ShipmentNo] = shipment } if len(oas.Shipments) == oas.Count { applog.Infof("all shipments are done (%d = %d)", len(oas.Shipments), oas.Count) oas.DoneChan <- true return } } }
// Test logging with an own logger. func TestOwnLogger(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) ownLogger := &testLogger{[]string{}} applog.SetLevel(applog.LevelDebug) applog.SetLogger(ownLogger) applog.Debugf("Debug.") applog.Infof("Info.") applog.Warningf("Warning.") applog.Errorf("Error.") applog.Criticalf("Critical.") assert.Length(ownLogger.logs, 5, "Everything logged.") }
// Test parsing and composing of date/times. func TestParseComposeTime(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) nowOne := time.Now() nowStr := atom.ComposeTime(nowOne) applog.Infof("Now as string: %s", nowStr) year, month, day := nowOne.Date() hour, min, sec := nowOne.Clock() loc := nowOne.Location() nowCmp := time.Date(year, month, day, hour, min, sec, 0, loc) nowTwo, err := atom.ParseTime(nowStr) assert.Nil(err, "No error during time parsing.") assert.Equal(nowCmp, nowTwo, "Both times have to be equal.") }
// logCommand logs a command and its execution status. func (urp *unifiedRequestProtocol) logCommand(ec *envCommand) { // Format the command for the log entry. formatCommand := func() string { var log string if ec.multi { log = "multi " } log += "command " + ec.command for _, arg := range ec.args { log = fmt.Sprintf("%s %v", log, arg) } return log } // Positive commands only if wanted, errors always. if ec.rs.IsOK() { if urp.database.configuration.LogCommands { applog.Infof("%s OK", formatCommand()) } } else { applog.Errorf("%s ERROR %v", formatCommand(), ec.rs.err) } }
// Test parsing and composing of date/times. func TestParseComposeTime(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) nowOne := time.Now() nowStr := rss.ComposeTime(nowOne) applog.Infof("Now as string: %s", nowStr) year, month, day := nowOne.Date() hour, min, _ := nowOne.Clock() loc := nowOne.Location() nowCmp := time.Date(year, month, day, hour, min, 0, 0, loc) nowTwo, err := rss.ParseTime(nowStr) assert.Nil(err, "No error during time parsing.") assert.Equal(nowCmp, nowTwo, "Both times have to be equal.") // Now some tests with different date formats. _, err = rss.ParseTime("21 Jun 2012 23:00 CEST") assert.Nil(err, "No error during time parsing.") _, err = rss.ParseTime("Thu, 21 Jun 2012 23:00 CEST") assert.Nil(err, "No error during time parsing.") _, err = rss.ParseTime("Thu, 21 Jun 2012 23:00 +0100") assert.Nil(err, "No error during time parsing.") }
// Stop the behavior. func (b *manufacturerBehavior) Stop() { if b.manufacturedQuantity > 0 { applog.Infof("manufacturer for %d to %d has %d unshipped items", b.itemNoLow, b.itemNoHigh, b.manufacturedQuantity) } }
// Process processes an event. func (l *LogAgent) Process(event Event) error { applog.Infof("agent: %q event topic: %q", l.id, event.Topic()) return nil }
// ProcessEvent processes an event. func (b *logBehavior) ProcessEvent(e Event, emitter EventEmitter) { applog.Infof("cell: '%s' event topic: '%s' payload: '%v'", b.id, e.Topic(), e.Payload()) }
// Stop the behavior. func (b *orderBehavior) Stop() { for itemNo, item := range b.openItems { applog.Infof("order %d has item %d open, needs %d", b.orderNo, itemNo, item.Quantity) } }