How to use Flush method of state Package

Best Syzkaller code snippet using state.Flush

middleware.go

Source:middleware.go Github

copy

Full Screen

...66 // If nil, 0 will be used as task number regardless of instance ID.67 TaskNumAllocator TaskNumAllocator68 // IsDevMode should be set to true when running locally.69 IsDevMode bool70 // FlushInMiddleware is true to make Middleware(...) periodically71 // synchronously send metrics to the backend after handling a request.72 //73 // This is useful on Standard GAE that doesn't support asynchronous flushes74 // outside of a context of some request.75 //76 // If false, the user of the library *must* launch FlushPeriodically() in77 // a background goroutine. Otherwise metrics won't be sent.78 FlushInMiddleware bool79 // Settings, if non nil, are static preset settings to use.80 //81 // If nil, settings will be loaded dynamically through 'settings' module.82 Settings *Settings83 lock sync.RWMutex84 state *tsmon.State85 lastSettings Settings86 instanceID string // cached result of InstanceID() call87 flushingNow bool // true if some goroutine is flushing right now88 nextFlush time.Time // next time we should do the flush89 lastFlush time.Time // last successful flush90 flushRetry time.Duration // flush retry delay91 testingMonitor monitor.Monitor // mocked in unit tests92}93const (94 // noFlushErrorThreshold defines when we start to complain in error log that95 // the last successful flush (if ever) was too long ago.96 noFlushErrorThreshold = 5 * time.Minute97 // flushTimeout defines the deadline for the flush operation.98 flushTimeout = 5 * time.Second99 // flushMaxRetry defines the maximum delay between flush retries.100 flushMaxRetry = 10 * time.Minute101 // flushInitialRetry defines the initial retry delay. This102 // is doubled every retry, up to flushMaxRetry.103 flushInitialRetry = 5 * time.Second104)105// Middleware is a middleware that collects request metrics and triggers metric106// flushes.107func (s *State) Middleware(c *router.Context, next router.Handler) {108 state, settings := s.checkSettings(c.Context)109 if settings.Enabled {110 started := clock.Now(c.Context)111 req := c.Request112 userAgent, ok := req.Header["User-Agent"]113 if !ok || len(userAgent) == 0 {114 userAgent = []string{"Unknown"}115 }116 ctx := c.Context117 contentLength := c.Request.ContentLength118 nrw := iotools.NewResponseWriter(c.Writer)119 c.Writer = nrw120 defer func() {121 dur := clock.Now(ctx).Sub(started)122 metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,123 contentLength, nrw.ResponseSize(), userAgent[0])124 }()125 next(c)126 if s.FlushInMiddleware {127 s.flushIfNeededImpl(ctx, state, settings)128 }129 } else {130 next(c)131 }132}133// FlushPeriodically runs a loop that periodically flushes metrics.134//135// Blocks until the context is canceled. Handles (and logs) errors internally.136func (s *State) FlushPeriodically(c context.Context) {137 for {138 var nextFlush time.Time139 state, settings := s.checkSettings(c)140 if settings.Enabled {141 nextFlush = s.flushIfNeededImpl(c, state, settings)142 }143 // Don't sleep less than 1 sec to avoid busy looping. It is always OK to144 // flush a sec later. In most cases we'll be sleeping ~= FlushIntervalSec.145 sleep := time.Second146 if dt := nextFlush.Sub(clock.Now(c)); dt > sleep {147 sleep = dt148 }149 if r := <-clock.After(c, sleep); r.Err != nil {150 return // the context is canceled151 }152 }153}154// checkSettings fetches tsmon settings and initializes, reinitializes or155// deinitializes tsmon, as needed.156//157// Returns current tsmon state and settings. Panics if the context is using158// unexpected tsmon state.159func (s *State) checkSettings(c context.Context) (*tsmon.State, *Settings) {160 state := tsmon.GetState(c)161 var settings Settings162 if s.Settings != nil {163 settings = *s.Settings164 } else {165 settings = fetchCachedSettings(c)166 }167 // Read the values used when handling previous request. In most cases they168 // are identical to current ones and we can skip grabbing a heavier write169 // lock.170 s.lock.RLock()171 if s.state == state && s.lastSettings == settings {172 s.lock.RUnlock()173 return state, &settings174 }175 s.lock.RUnlock()176 // 'settings' or 'state' has changed. Reinitialize tsmon as needed under177 // the write lock.178 s.lock.Lock()179 defer s.lock.Unlock()180 // First call to 'checkSettings' ever?181 if s.state == nil {182 s.state = state183 s.state.SetMonitor(monitor.NewNilMonitor()) // doFlush uses its own monitor184 s.state.InhibitGlobalCallbacksOnFlush()185 } else if state != s.state {186 panic("tsmon state in the context was unexpectedly changed between requests")187 }188 switch {189 case !bool(s.lastSettings.Enabled) && bool(settings.Enabled):190 s.enableTsMon(c)191 case bool(s.lastSettings.Enabled) && !bool(settings.Enabled):192 s.disableTsMon(c)193 }194 s.lastSettings = settings195 return state, &settings196}197// enableTsMon puts in-memory metrics store in the context's tsmon state.198//199// Called with 's.lock' locked.200func (s *State) enableTsMon(c context.Context) {201 t := s.Target(c)202 t.TaskNum = -1 // will be assigned later via TaskNumAllocator203 s.state.SetStore(store.NewInMemory(&t))204 // Request the flush to be executed ASAP, so it registers a claim for a task205 // number via NotifyTaskIsAlive. Also reset 'lastFlush', so that we don't get206 // invalid logging that the last flush was long time ago.207 s.nextFlush = clock.Now(c)208 s.lastFlush = s.nextFlush209 // Set initial value for retry delay.210 s.flushRetry = flushInitialRetry211}212// disableTsMon puts nil metrics store in the context's tsmon state.213//214// Called with 's.lock' locked.215func (s *State) disableTsMon(c context.Context) {216 s.state.SetStore(store.NewNilStore())217}218// flushIfNeededImpl periodically flushes the accumulated metrics.219//220// It skips the flush if some other goroutine is already flushing. Logs errors.221//222// Returns a timestamp when the next flush should occur. It may be in the past223// if the flush is happening concurrently right now in another goroutine.224//225// TODO(vadimsh): Refactor flushIfNeededImpl + FlushPeriodically to be less226// awkward. Historically, flushIfNeededImpl was used only from Middleware and227// FlushPeriodically was slapped on top later.228func (s *State) flushIfNeededImpl(c context.Context, state *tsmon.State, settings *Settings) (nextFlush time.Time) {229 // Used to compare 'nextFlush' to 'now'. Needed to make sure we really do230 // the flush after sleeping in FlushPeriodically even if we happened to wake231 // up a few nanoseconds earlier.232 const epsilonT = 100 * time.Millisecond233 now := clock.Now(c)234 // Most of the time the flush is not needed and we can get away with235 // lightweight RLock.236 s.lock.RLock()237 nextFlush = s.nextFlush238 skip := s.flushingNow || now.Add(epsilonT).Before(nextFlush)239 s.lock.RUnlock()240 if skip {241 return242 }243 // Need to flush. Update flushingNow. Redo the check under write lock, as well244 // as do a bunch of other calls while we hold the lock. Will be useful later.245 s.lock.Lock()246 if s.instanceID == "" && s.InstanceID != nil {247 s.instanceID = s.InstanceID(c)248 }249 instanceID := s.instanceID250 lastFlush := s.lastFlush251 nextFlush = s.nextFlush252 skip = s.flushingNow || now.Add(epsilonT).Before(nextFlush)253 if !skip {254 s.flushingNow = true255 }256 s.lock.Unlock()257 if skip {258 return259 }260 // The flush must be fast. Limit it by some timeout.261 c, cancel := clock.WithTimeout(c, flushTimeout)262 defer cancel()263 // Report per-process statistic.264 versions.Report(c)265 if settings.ReportRuntimeStats {266 runtimestats.Report(c)267 }268 // Unset 'flushingNow' no matter what (even on panics).269 // If flush has failed, retry with back off to avoid270 // hammering the receiver.271 var err error272 defer func() {273 s.lock.Lock()274 defer s.lock.Unlock()275 s.flushingNow = false276 if err == nil || err == ErrNoTaskNumber {277 // Reset retry delay.278 s.flushRetry = flushInitialRetry279 s.nextFlush = now.Add(time.Duration(settings.FlushIntervalSec) * time.Second)280 if err == nil {281 s.lastFlush = now282 }283 } else {284 // Flush has failed, back off the next flush.285 if s.flushRetry < flushMaxRetry {286 s.flushRetry *= 2287 }288 s.nextFlush = now.Add(s.flushRetry)289 }290 nextFlush = s.nextFlush291 }()292 err = s.ensureTaskNumAndFlush(c, instanceID, state, settings)293 if err != nil {294 if err == ErrNoTaskNumber {295 logging.Warningf(c, "Skipping the tsmon flush: no task number assigned yet")296 } else {297 logging.WithError(err).Errorf(c, "Failed to flush tsmon metrics")298 }299 if sinceLastFlush := now.Sub(lastFlush); sinceLastFlush > noFlushErrorThreshold {300 logging.Errorf(c, "No successful tsmon flush for %s", sinceLastFlush)301 if s.TaskNumAllocator != nil {302 logging.Errorf(c, "Is /internal/cron/ts_mon/housekeeping running?")303 }304 }305 }306 // 'nextFlush' return value is constructed in the defer.307 return308}309// ensureTaskNumAndFlush gets a task number assigned to the process and flushes310// the metrics.311//312// Returns ErrNoTaskNumber if the task wasn't assigned a task number yet.313func (s *State) ensureTaskNumAndFlush(c context.Context, instanceID string, state *tsmon.State, settings *Settings) error {314 var task target.Task315 defTarget := state.Store().DefaultTarget()316 if t, ok := defTarget.(*target.Task); ok {317 task = *t318 } else {319 return fmt.Errorf("default tsmon target is not a Task (%T): %v", defTarget, defTarget)320 }321 // Notify the task number allocator that we are still alive and grab the322 // TaskNum assigned to us. Use 0 if TaskNumAllocator is nil.323 var assignedTaskNum int324 var err error325 if s.TaskNumAllocator != nil {326 assignedTaskNum, err = s.TaskNumAllocator.NotifyTaskIsAlive(c, &task, instanceID)327 if err != nil && err != ErrNoTaskNumber {328 return fmt.Errorf("failed to get task number assigned for %q - %s", instanceID, err)329 }330 }331 // Don't do the flush if we still haven't got a task number.332 if err == ErrNoTaskNumber {333 if task.TaskNum >= 0 {334 logging.Warningf(c, "The task was inactive for too long and lost its task number, clearing cumulative metrics")335 state.ResetCumulativeMetrics(c)336 }337 task.TaskNum = -1338 state.Store().SetDefaultTarget(&task)339 return ErrNoTaskNumber340 }341 task.TaskNum = int32(assignedTaskNum)342 state.Store().SetDefaultTarget(&task)343 return s.doFlush(c, state, settings)344}345// doFlush actually sends the metrics to the monitor.346func (s *State) doFlush(c context.Context, state *tsmon.State, settings *Settings) error {347 var mon monitor.Monitor348 var err error349 if s.testingMonitor != nil {350 mon = s.testingMonitor351 } else if s.IsDevMode || settings.ProdXAccount == "" {352 mon = monitor.NewDebugMonitor("")353 } else {354 logging.Infof(c, "Sending metrics to ProdX using %s", settings.ProdXAccount)355 transport, err := auth.GetRPCTransport(356 c,357 auth.AsActor,358 auth.WithServiceAccount(settings.ProdXAccount),359 auth.WithScopes(monitor.ProdxmonScopes...))360 if err != nil {361 return err362 }363 endpoint, err := url.Parse(prodXEndpoint)364 if err != nil {365 return err366 }367 mon, err = monitor.NewHTTPMonitor(c, &http.Client{Transport: transport}, endpoint)368 if err != nil {369 return err370 }371 }372 defer mon.Close()373 if err = state.Flush(c, mon); err != nil {374 return err375 }376 return nil377}...

Full Screen

Full Screen

batchedproducer_test.go

Source:batchedproducer_test.go Github

copy

Full Screen

...20 "time"21)22type mockBatchedProducer struct {23 BatchedProducer24 onFlushFunc AssemblyFunc25}26func (prod *mockBatchedProducer) Configure(conf PluginConfigReader) {27}28func (prod *mockBatchedProducer) Produce(workers *sync.WaitGroup) {29 // start default BatchMessageLoop30 prod.BatchMessageLoop(workers, func() AssemblyFunc { return prod.onFlushFunc })31}32func getMockBatchedProducer() mockBatchedProducer {33 return mockBatchedProducer{34 BatchedProducer: BatchedProducer{35 DirectProducer: DirectProducer{36 SimpleProducer: SimpleProducer{37 control: make(chan PluginControl),38 streams: []MessageStreamID{},39 fallbackStream: nil, //it must be set after registration of stream40 runState: new(PluginRunState),41 modulators: ModulatorArray{},42 shutdownTimeout: 10 * time.Millisecond,43 Logger: logrus.WithField("Scope", "test"),44 },45 },46 },47 }48}49func TestBatchedProducerConfigure(t *testing.T) {50 expect := ttesting.NewExpect(t)51 mockProducer := mockBatchedProducer{}52 mockConf := NewPluginConfig("mockBatched", "mockBatchedProducer")53 mockConf.Override("Streams", []string{"testBoundStream"})54 mockConf.Override("FallbackStream", "mockStream")55 // Router needs to be configured to avoid unknown class errors56 registerMockRouter("mockStream")57 reader := NewPluginConfigReader(&mockConf)58 err := reader.Configure(&mockProducer)59 expect.NoError(err)60}61func TestBatchedProducerState(t *testing.T) {62 expect := ttesting.NewExpect(t)63 mockProducer := mockBatchedProducer{}64 mockProducer.runState = new(PluginRunState)65 mockProducer.setState(PluginStateActive)66 expect.Equal(PluginStateActive, mockProducer.GetState())67 expect.True(mockProducer.IsActive())68 mockProducer.setState(PluginStateWaiting)69 expect.True(mockProducer.IsBlocked())70 mockProducer.setState(PluginStateStopping)71 expect.True(mockProducer.IsStopping())72 expect.True(mockProducer.IsActiveOrStopping())73}74func TestBatchedProducerCallback(t *testing.T) {75 expect := ttesting.NewExpect(t)76 mockProducer := mockBatchedProducer{}77 rollBackCalled := false78 rollCallBack := func() {79 rollBackCalled = true80 }81 mockProducer.SetRollCallback(rollCallBack)82 mockProducer.onRoll()83 expect.True(rollBackCalled)84 stopCallBackCalled := false85 stopCallBack := func() {86 stopCallBackCalled = true87 }88 mockProducer.SetStopCallback(stopCallBack)89 mockProducer.onStop()90 expect.True(stopCallBackCalled)91}92func TestBatchedProducerEnqueue(t *testing.T) {93 expect := ttesting.NewExpect(t)94 mockP := getMockBatchedProducer()95 // configure and init producer96 mockConf := NewPluginConfig("BatchedProducerEnqueue", "mockBatchedProducer")97 mockConf.Override("Streams", []string{"testBoundStream"})98 mockConf.Override("Batch/MaxCount", 3)99 mockConf.Override("Batch/FlushCount", 2)100 mockConf.Override("Batch/TimeoutSec", 1)101 reader := NewPluginConfigReader(&mockConf)102 err := reader.Configure(&mockP)103 expect.NoError(err)104 // init test message105 msg := NewMessage(nil, []byte("BatchedProducerEnqueueTest"), nil, 1)106 // init flush func for test107 onBatchFlushExecutedGuard := sync.RWMutex{}108 onBatchFlushExecuted := false109 mockP.onFlushFunc = func(messages []*Message) {110 onBatchFlushExecutedGuard.Lock()111 onBatchFlushExecuted = true112 onBatchFlushExecutedGuard.Unlock()113 expect.Equal(2, len(messages)) // expect two messages because one is send during "stopping" state114 expect.Equal("BatchedProducerEnqueueTest", messages[0].String())115 expect.Equal("BatchedProducerEnqueueTest", messages[1].String())116 }117 // init WaitGroup and start produce method (loop)118 waitForTest := new(sync.WaitGroup)119 waitForTest.Add(1)120 go func() {121 defer waitForTest.Done()122 mockP.Produce(waitForTest)123 }()124 mockP.setState(PluginStateActive)125 // enqueue test messages126 mockP.Enqueue(msg, time.Second)127 mockP.Enqueue(msg, time.Second)128 // wait for flush129 time.Sleep(1500 * time.Millisecond)130 // expect execution of flush method131 onBatchFlushExecutedGuard.RLock()132 expect.Equal(true, onBatchFlushExecuted)133 onBatchFlushExecutedGuard.RUnlock()134 // stop producer135 mockP.Control() <- PluginControlStopProducer // trigger stopLoop (stop expect.NonBlocking)136 waitForTest.Wait()137}138func TestBatchedProducerClose(t *testing.T) {139 expect := ttesting.NewExpect(t)140 mockP := getMockBatchedProducer()141 // configure and init producer142 mockConf := NewPluginConfig("mockBatchedProducerClose", "mockBatchedProducer")143 mockConf.Override("Streams", []string{"testBoundStream"})144 reader := NewPluginConfigReader(&mockConf)145 err := reader.Configure(&mockP)146 expect.NoError(err)147 // init test message148 msg := NewMessage(nil, []byte("BatchedProducerEnqueueTest"), nil, 1)149 // init flush func for test150 onBatchFlushExecuted := false151 mockP.onFlushFunc = func(messages []*Message) {152 onBatchFlushExecuted = true153 expect.Equal(2, len(messages)) // expect two messages because one is send during "stopping" state154 expect.Equal("BatchedProducerEnqueueTest", messages[0].String())155 expect.Equal("BatchedProducerEnqueueTest", messages[1].String())156 }157 // init WaitGroup and start produce method (loop)158 waitForTest := new(sync.WaitGroup)159 waitForTest.Add(1)160 go func() {161 defer waitForTest.Done()162 mockP.Produce(waitForTest)163 }()164 mockP.setState(PluginStateActive)165 // enqueue test messages166 mockP.Enqueue(msg, time.Second)167 mockP.Enqueue(msg, time.Second)168 // stop producer169 mockP.Control() <- PluginControlStopProducer // trigger stopLoop (stop expect.NonBlocking)170 waitForTest.Wait()171 time.Sleep(500 * time.Millisecond)172 // expect execution of flush method173 expect.Equal(true, onBatchFlushExecuted)174}...

Full Screen

Full Screen

action.go

Source:action.go Github

copy

Full Screen

...6 "go-common/library/log"7)8func (s *Service) actionAct(c context.Context, act *model.Action) (err error) {9 switch act.Action {10 case model.ActFlushDM:11 fc := new(model.Flush)12 if err = json.Unmarshal(act.Data, &fc); err != nil {13 log.Error("json.Unmarshal(%s) error(%v)", act.Data, err)14 return15 }16 s.asyncAddFlushDM(c, fc)17 case model.ActFlushDMSeg:18 fc := new(model.FlushDMSeg)19 if err = json.Unmarshal(act.Data, &fc); err != nil {20 log.Error("json.Unmarshal(%s) error(%v)", act.Data, err)21 return22 }23 if fc.Page == nil {24 log.Error("s.ActFlushDMSeg(+%v) error page nil", fc)25 return26 }27 // async flush cache28 s.asyncAddFlushDMSeg(c, fc)29 case model.ActAddDM:30 var (31 dm = &model.DM{}32 sub *model.Subject33 )34 if err = json.Unmarshal(act.Data, &dm); err != nil {35 log.Error("json.Unmarshal(%s) error(%v)", act.Data, err)36 return37 }38 if sub, err = s.subject(c, dm.Type, dm.Oid); err != nil {39 return40 }41 if err = s.actionAddDM(c, sub, dm); err != nil {42 log.Error("s.actionAddDM(+%v) error(%v)", dm, err)43 return44 }45 if dm.State == model.StateNormal || dm.State == model.StateMonitorAfter {46 // 1. 创作中心最新1000条弹幕47 s.asyncAddRecent(c, dm)48 // 2. 刷新全段弹幕,NOTE 忽略redis缓存报错49 if ok, _ := s.dao.ExpireDMCache(c, dm.Type, dm.Oid); ok {50 s.dao.AddDMCache(c, dm)51 }52 s.asyncAddFlushDM(c, &model.Flush{53 Type: dm.Type,54 Oid: dm.Oid,55 Force: false,56 })57 // 3. 刷新分段弹幕缓存,NOTE 忽略redis缓存报错58 var p *model.Page59 if p, err = s.pageinfo(c, sub.Pid, dm); err != nil {60 return61 }62 switch dm.Pool {63 case model.PoolNormal:64 if ok, _ := s.dao.ExpireDMID(c, dm.Type, dm.Oid, p.Total, p.Num); ok {65 s.dao.AddDMIDCache(c, dm.Type, dm.Oid, p.Total, p.Num, dm.ID)66 }67 case model.PoolSubtitle:68 if ok, _ := s.dao.ExpireDMIDSubtitle(c, dm.Type, dm.Oid); ok {69 s.dao.AddDMIDSubtitleCache(c, dm.Type, dm.Oid, dm)70 }71 case model.PoolSpecial:72 if err = s.specialLocationUpdate(c, dm.Type, dm.Oid); err != nil {73 return74 }75 // TODO add cache76 default:77 return78 }79 s.dao.AddIdxContentCaches(c, dm.Type, dm.Oid, dm)80 s.asyncAddFlushDMSeg(c, &model.FlushDMSeg{81 Type: dm.Type,82 Oid: dm.Oid,83 Force: false,84 Page: p,85 })86 }87 s.bnjDmCount(c, sub, dm)88 }89 return90}91func (s *Service) actionFlushDM(c context.Context, tp int32, oid int64, force bool) (err error) {92 sub, err := s.subject(c, tp, oid)93 if err != nil {94 return95 }96 if force {97 s.dao.DelDMCache(c, tp, oid) // delete redis cache,ignore error98 }99 xml, err := s.genXML(c, sub) // generate xml from redis or database100 if err != nil {101 log.Error("s.genXML(%d) error(%v)", oid, err)102 return103 }104 data, err := s.gzflate(xml, 4)105 if err != nil {106 log.Error("s.gzflate(type:%d,oid:%d) error(%v)", tp, oid, err)107 return108 }109 if err = s.dao.AddXMLCache(c, sub.Oid, data); err != nil {110 return111 }112 log.Info("actionFlushDM type:%d,oid:%d fore:%v", tp, oid, force)113 return114}115// actionAddDM add dm index and content to db by transaction.116func (s *Service) actionAddDM(c context.Context, sub *model.Subject, dm *model.DM) (err error) {117 tx, err := s.dao.BeginTran(c)118 if err != nil {119 return120 }121 // special dm122 if dm.Pool == model.PoolSpecial && dm.ContentSpe != nil {123 if _, err = s.dao.TxAddContentSpecial(tx, dm.ContentSpe); err != nil {124 return tx.Rollback()125 }126 }127 if _, err = s.dao.TxAddContent(tx, dm.Oid, dm.Content); err != nil {128 return tx.Rollback()129 }130 if _, err = s.dao.TxAddIndex(tx, dm); err != nil {131 return tx.Rollback()132 }133 if dm.State == model.StateMonitorBefore || dm.State == model.StateMonitorAfter {134 if _, err = s.dao.TxIncrSubMCount(tx, dm.Type, dm.Oid); err != nil {135 return tx.Rollback()136 }137 }138 var count int64139 if dm.State == model.StateNormal || dm.State == model.StateMonitorAfter || dm.State == model.StateHide {140 count = 1141 if sub.Childpool == model.PoolNormal && dm.Pool != model.PoolNormal {142 sub.Childpool = 1143 }144 }145 if _, err = s.dao.TxIncrSubjectCount(tx, sub.Type, sub.Oid, 1, count, sub.Childpool); err != nil {146 return tx.Rollback()147 }148 return tx.Commit()149}150// actionFlushXMLDmSeg flush xml dm seg151func (s *Service) actionFlushXMLDmSeg(c context.Context, tp int32, oid int64, p *model.Page, force bool) (err error) {152 var (153 sub *model.Subject154 duration int64155 seg *model.Segment156 )157 if sub, err = s.subject(c, tp, oid); err != nil {158 return159 }160 if force {161 if err = s.dao.DelDMIDCache(c, tp, oid, p.Total, p.Num); err != nil {162 return163 }164 if sub.Childpool > 0 {165 s.dao.DelDMIDSubtitleCache(c, tp, oid)166 }167 }168 if duration, err = s.videoDuration(c, sub.Pid, sub.Oid); err != nil {169 return170 }171 ps, _ := model.SegmentPoint(p.Num, duration)172 if seg, err = s.segmentInfo(c, sub.Pid, sub.Oid, ps, duration); err != nil {173 return174 }175 res, err := s.dmSegXML(c, sub, seg)176 if err != nil {177 return178 }179 if err = s.dao.SetXMLSegCache(c, tp, oid, seg.Cnt, seg.Num, res); err != nil {180 return181 }182 log.Info("actionFlushXMLDmSeg type:%d,oid:%d,seg:%+v", tp, oid, seg)183 return184}185func (s *Service) flushDmSegCache(c context.Context, fc *model.FlushDMSeg) (err error) {186 if fc.Page == nil {187 return188 }189 if err = s.actionFlushXMLDmSeg(c, fc.Type, fc.Oid, fc.Page, fc.Force); err != nil {190 return191 }192 return193}194func (s *Service) flushDmCache(c context.Context, fc *model.Flush) (err error) {195 if err = s.actionFlushDM(c, fc.Type, fc.Oid, fc.Force); err != nil {196 return197 }198 if err = s.dao.DelAjaxDMCache(c, fc.Oid); err != nil {199 return200 }201 return202}...

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", foo)4 http.HandleFunc("/bar", bar)5 http.ListenAndServe(":8080", nil)6}7func foo(w http.ResponseWriter, r *http.Request) {8 fmt.Println("foo ran")9}10func bar(w http.ResponseWriter, r *http.Request) {11 fmt.Println("bar ran")12}13import (14func main() {15 http.HandleFunc("/", foo)16 http.HandleFunc("/bar", bar)17 http.ListenAndServe(":8080", nil)18}19func foo(w http.ResponseWriter, r *http.Request) {20 fmt.Println("foo ran")21}22func bar(w http.ResponseWriter, r *http.Request) {23 fmt.Println("bar ran")24}25import (26func main() {27 http.HandleFunc("/", foo)28 http.HandleFunc("/bar", bar)29 http.ListenAndServe(":8080", nil)30}31func foo(w http.ResponseWriter, r *http.Request) {32 fmt.Println("foo ran")33}34func bar(w http.ResponseWriter, r *http.Request) {35 fmt.Println("bar ran")36}37import (38func main() {39 http.HandleFunc("/", foo)40 http.HandleFunc("/bar", bar)41 http.ListenAndServe(":8080", nil)42}43func foo(w http.ResponseWriter, r *http.Request) {44 fmt.Println("foo ran")45}46func bar(w http.ResponseWriter, r *http.Request) {47 fmt.Println("bar ran")48}49import (50func main() {51 http.HandleFunc("/", foo)52 http.HandleFunc("/bar", bar)53 http.ListenAndServe(":8080", nil)54}55func foo(w http.ResponseWriter, r *http.Request) {56 fmt.Println("foo ran")57}58func bar(w http.ResponseWriter, r *http.Request) {59 fmt.Println("bar ran")60}

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 w.Header().Set("Content-Type", "text/html")5 w.Write([]byte("<h1>Go Web Programming</h1>"))6 w.(http.Flusher).Flush()7 w.Write([]byte("<h2>Chapter 1</h2>"))8 w.(http.Flusher).Flush()9 w.Write([]byte("<h3>Introduction</h3>"))10 w.(http.Flusher).Flush()11 w.Write([]byte("<p>Hello World</p>"))12 w.(http.Flusher).Flush()13 })14 http.HandleFunc("/template", func(w http.ResponseWriter, r *http.Request) {15 w.Header().Set("Content-Type", "text/html")16 tpl := template.Must(template.ParseFiles("index.html"))17 tpl.Execute(w, nil)18 })19 http.ListenAndServe(":8080", nil)20}21import (22func main() {23 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {24 w.Header().Set("Content-Type", "text/html")25 w.Write([]byte("<h1>Go Web Programming</h1>"))26 w.(http.Flusher).Flush()27 w.Write([]byte("<h2>Chapter 1</h2>"))28 w.(http.Flusher).Flush()29 w.Write([]byte("<h3>Introduction</h3>"))30 w.(http.Flusher).Flush()31 w.Write([]byte("<p>Hello World</p>"))32 w.(http.Flusher).Flush()33 })34 http.HandleFunc("/template", func(w http.ResponseWriter, r *http.Request) {35 w.Header().Set("Content-Type", "text/html")36 tpl := template.Must(template.ParseFiles("index.html"))

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 scanner := bufio.NewScanner(os.Stdin)4 for scanner.Scan() {5 fmt.Println(scanner.Text())6 }7 scanner.Flush()8}

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 state := terraform.NewState()4 resource := terraform.NewResourceState("aws_instance", "foo", map[string]interface{}{5 })6 state.RootModule().Resources["aws_instance.foo"] = resource7 state.Flush()8}9import (10func main() {11 state := terraform.NewState()12 resource := terraform.NewResourceState("aws_instance", "foo", map[string]interface{}{13 })14 state.RootModule().Resources["aws_instance.foo"] = resource15 err := state.WriteState(remote.NewInmemClient())16 if err != nil {17 panic(err)18 }19}20import (21func main() {22 state := terraform.NewState()23 resource := terraform.NewResourceState("aws_instance", "foo", map[string]interface{}{24 })25 state.RootModule().Resources["aws_instance.foo"] = resource26 err := state.WriteState(remote.NewInmemClient())27 if err != nil {28 panic(err)29 }30 state, err = state.ReadState(remote.NewInmemClient())31 if err != nil {

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 f, _ := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)5 defer f.Close()6 io.WriteString(f, "Hello World")7 f.Sync()8 f.Close()9}10import (11func main() {12 fmt.Println("Hello, playground")13 f, _ := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)14 defer f.Close()15 io.WriteString(f, "Hello World")16 f.WriteAt([]byte("Hello World"), 0)17 f.Close()18}19import (20func main() {21 fmt.Println("Hello, playground")22 f, _ := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)23 defer f.Close()24 io.WriteString(f, "Hello World")25 f.WriteString("Hello World")26 f.Close()27}28import (29func main() {30 fmt.Println("Hello, playground")31 f, _ := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)32 defer f.Close()33 io.WriteString(f, "Hello World")34 f.Seek(0, 0)35 f.Close()36}37import (38func main() {39 fmt.Println("Hello, playground")40 f, _ := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)41 defer f.Close()42 io.WriteString(f, "Hello World")43 f.Truncate(0)44 f.Close()45}

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, _ := os.Create("test.txt")4 w := bufio.NewWriter(f)5 w.WriteString("Hello, World!")6 w.Flush()7}

Full Screen

Full Screen

Flush

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 state := &terraform.State{}4 resource := &terraform.ResourceState{5 Primary: &terraform.InstanceState{6 Attributes: map[string]string{7 },8 },9 }10 state.RootModule().Resources["aws_instance.foo"] = resource11 state.WriteTo(os.Stdout)12}13import (14func main() {15 state := &terraform.State{}16 resource := &terraform.ResourceState{17 Primary: &terraform.InstanceState{18 Attributes: map[string]string{19 },20 },21 }22 state.RootModule().Resources["aws_instance.foo"] = resource23 state.WriteTo(os.Stdout)24}25import (26func main() {27 state := &terraform.State{}28 resource := &terraform.ResourceState{29 Primary: &terraform.InstanceState{30 Attributes: map[string]string{31 },32 },33 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful