Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(331)

Side by Side Diff: appengine/logdog/coordinator/backend/archiveCron.go

Issue 1863973002: LogDog: Update to archival V2. (Closed) Base URL: https://github.com/luci/luci-go@grpcutil-errors
Patch Set: Minor fixes, works in dev now. Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package backend 5 package backend
6 6
7 import ( 7 import (
8 "fmt" 8 "fmt"
9 "net/http" 9 "net/http"
10 » "time" 10 » "sync/atomic"
11 11
12 "github.com/julienschmidt/httprouter" 12 "github.com/julienschmidt/httprouter"
13 "github.com/luci/gae/filter/dsQueryBatch" 13 "github.com/luci/gae/filter/dsQueryBatch"
14 ds "github.com/luci/gae/service/datastore" 14 ds "github.com/luci/gae/service/datastore"
15 tq "github.com/luci/gae/service/taskqueue" 15 tq "github.com/luci/gae/service/taskqueue"
16 "github.com/luci/luci-go/appengine/logdog/coordinator" 16 "github.com/luci/luci-go/appengine/logdog/coordinator"
17 "github.com/luci/luci-go/appengine/logdog/coordinator/config" 17 "github.com/luci/luci-go/appengine/logdog/coordinator/config"
18 "github.com/luci/luci-go/common/api/logdog_coordinator/services/v1"
19 "github.com/luci/luci-go/common/clock" 18 "github.com/luci/luci-go/common/clock"
20 "github.com/luci/luci-go/common/errors" 19 "github.com/luci/luci-go/common/errors"
21 log "github.com/luci/luci-go/common/logging" 20 log "github.com/luci/luci-go/common/logging"
21 "github.com/luci/luci-go/common/parallel"
22 "github.com/luci/luci-go/common/proto/logdog/svcconfig" 22 "github.com/luci/luci-go/common/proto/logdog/svcconfig"
23 "golang.org/x/net/context" 23 "golang.org/x/net/context"
24 ) 24 )
25 25
26 const archiveTaskVersion = "v1" 26 const archiveTaskVersion = "v4"
27 27
28 // archiveTaskQueueName returns the task queue name for archival, or an error 28 // archiveTaskQueueName returns the task queue name for archival, or an error
29 // if it's not configured. 29 // if it's not configured.
30 func archiveTaskQueueName(cfg *svcconfig.Config) (string, error) { 30 func archiveTaskQueueName(cfg *svcconfig.Config) (string, error) {
31 q := cfg.GetCoordinator().ArchiveTaskQueue 31 q := cfg.GetCoordinator().ArchiveTaskQueue
32 if q == "" { 32 if q == "" {
33 return "", errors.New("missing archive task queue name") 33 return "", errors.New("missing archive task queue name")
34 } 34 }
35 return q, nil 35 return q, nil
36 } 36 }
37 37
38 func archiveTaskNameForHash(hashID string) string {
39 return fmt.Sprintf("archive-%s-%s", hashID, archiveTaskVersion)
40 }
41
42 // createArchiveTask creates a new archive Task.
43 func createArchiveTask(cfg *svcconfig.Coordinator, ls *coordinator.LogStream, co mplete bool) (*tq.Task, error) {
44 desc := logdog.ArchiveTask{
45 Path: string(ls.Path()),
46 Complete: complete,
47 }
48 t, err := createPullTask(&desc)
49 if err != nil {
50 return nil, err
51 }
52
53 t.Name = archiveTaskNameForHash(ls.HashID())
54 return t, nil
55 }
56
57 // HandleArchiveCron is the handler for the archive cron endpoint. This scans 38 // HandleArchiveCron is the handler for the archive cron endpoint. This scans
58 // for terminal log streams that are ready for archival. 39 // for log streams that are ready for archival.
59 // 40 //
60 // This will be called periodically by AppEngine cron. 41 // This will be called periodically by AppEngine cron.
61 func (b *Backend) HandleArchiveCron(c context.Context, w http.ResponseWriter, r *http.Request, p httprouter.Params) { 42 func (b *Backend) HandleArchiveCron(c context.Context, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
62 errorWrapper(c, w, func() error { 43 errorWrapper(c, w, func() error {
63 » » return b.archiveCron(c, true) 44 » » return b.archiveCron(c)
64 }) 45 })
65 } 46 }
66 47
67 // HandleArchiveCronNT is the handler for the archive non-terminal cron 48 func (b *Backend) archiveCron(c context.Context) error {
68 // endpoint. This scans for non-terminal log streams that have not been updated
69 // in sufficiently long that we're willing to declare them complete and mark
70 // them terminal.
71 //
72 // This will be called periodically by AppEngine cron.
73 func (b *Backend) HandleArchiveCronNT(c context.Context, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
74 » errorWrapper(c, w, func() error {
75 » » return b.archiveCron(c, false)
76 » })
77 }
78
79 // HandleArchiveCronPurge purges all archival tasks from the task queue.
80 func (b *Backend) HandleArchiveCronPurge(c context.Context, w http.ResponseWrite r, r *http.Request, p httprouter.Params) {
81 » errorWrapper(c, w, func() error {
82 » » cfg, err := config.Load(c)
83 » » if err != nil {
84 » » » log.WithError(err).Errorf(c, "Failed to load configurati on.")
85 » » » return err
86 » » }
87
88 » » queueName, err := archiveTaskQueueName(cfg)
89 » » if err != nil {
90 » » » log.Errorf(c, "Failed to get task queue name.")
91 » » » return err
92 » » }
93
94 » » if err := tq.Get(c).Purge(queueName); err != nil {
95 » » » log.Fields{
96 » » » » log.ErrorKey: err,
97 » » » » "queue": queueName,
98 » » » }.Errorf(c, "Failed to purge task queue.")
99 » » » return err
100 » » }
101 » » return nil
102 » })
103 }
104
105 func (b *Backend) archiveCron(c context.Context, complete bool) error {
106 cfg, err := config.Load(c) 49 cfg, err := config.Load(c)
107 if err != nil { 50 if err != nil {
108 » » log.WithError(err).Errorf(c, "Failed to load configuration.") 51 » » return fmt.Errorf("failed to load configuration: %v", err)
109 » » return err 52 » }
53 » ccfg := cfg.GetCoordinator()
54
55 » if ccfg.ArchiveTaskQueue == "" {
56 » » return errors.New("missing archival task queue name")
110 } 57 }
111 58
112 » queueName, err := archiveTaskQueueName(cfg) 59 » archiveDelayMax := ccfg.ArchiveDelayMax.Duration()
113 » if err != nil { 60 » if archiveDelayMax <= 0 {
114 » » log.Errorf(c, "Failed to get task queue name.") 61 » » return fmt.Errorf("must have positive maximum archive delay, not %q", archiveDelayMax.String())
115 » » return err
116 } 62 }
117 63
118 » now := clock.Now(c).UTC() 64 » threshold := clock.Now(c).UTC().Add(-archiveDelayMax)
119 » q := ds.NewQuery("LogStream") 65 » log.Fields{
66 » » "threshold": threshold,
67 » }.Infof(c, "Querying for all streaming logs created before max archival threshold.")
120 68
121 » var threshold time.Duration 69 » // Query for log streams that were created <= our threshold and that are
122 » if complete { 70 » // still in LSStreaming state.
123 » » threshold = cfg.GetCoordinator().ArchiveDelay.Duration() 71 » //
124 » » q = q.Eq("State", coordinator.LSTerminated) 72 » // We order descending because this is already an index that we use for our
125 » } else { 73 » // "logdog.Logs.Query".
126 » » threshold = cfg.GetCoordinator().ArchiveDelayMax.Duration() 74 » q := ds.NewQuery("LogStream").
127 » » q = q.Eq("State", coordinator.LSPending) 75 » » Eq("State", coordinator.LSStreaming).
128 » } 76 » » Lte("Created", threshold).
129 » q = q.Lte("Updated", now.Add(-threshold)) 77 » » Order("-Created", "State")
130 78
131 » // If the log stream has a terminal index, and its Updated time is less than 79 » // Since these logs are beyond maximum archival delay, we will dispatch
132 » // the maximum archive delay, require this archival to be complete (no 80 » // archival immediately.
133 » // missing LogEntry). 81 » params := coordinator.ArchivalParams{}
134 » //
135 » // If we're past maximum archive delay, settle for any (even empty) arch ival.
136 » // This is a failsafe to prevent logs from sitting in limbo forever.
137 » maxDelay := cfg.GetCoordinator().ArchiveDelayMax.Duration()
138 82
139 » // Perform a query, dispatching tasks in batches. 83 » // Create archive tasks for our expired log streams in parallel.
140 batch := b.getMultiTaskBatchSize() 84 batch := b.getMultiTaskBatchSize()
85 var tasked int32
86 var failed int32
141 87
142 » ti := tq.Get(c) 88 » var ierr error
143 » tasks := make([]*tq.Task, 0, batch) 89 » parallel.Ignore(parallel.Run(batch, func(taskC chan<- func() error) {
144 » totalScheduledTasks := 0 90 » » // Run a batched query across the expired log stream space.
145 » addAndMaybeDispatchTasks := func(task *tq.Task) error { 91 » » ierr = ds.Get(dsQueryBatch.BatchQueries(c, int32(batch))).Run(q, func(ls *coordinator.LogStream) error {
146 » » switch task { 92 » » » log.Fields{
147 » » case nil: 93 » » » » "path": ls.Path(),
148 » » » if len(tasks) == 0 { 94 » » » » "id": ls.HashID(),
95 » » » }.Infof(c, "Identified expired log stream.")
96
97 » » » // Archive this log stream in a transaction.
98 » » » taskC <- func() error {
99 » » » » err := ds.Get(c).RunInTransaction(func(c context .Context) error {
100 » » » » » createdTask, err := params.CreateTask(tq .Get(c), ls, ccfg.ArchiveTaskQueue)
Vadim Sh. 2016/04/07 01:21:32 nit: you can check ls.State outside the transactio
dnj 2016/04/11 17:20:03 Is this worth doing (and incurring another write c
101 » » » » » if err != nil {
102 » » » » » » return err
103 » » » » » }
104
105 » » » » » if !createdTask {
106 » » » » » » return nil
107 » » » » » }
108 » » » » » return ds.Get(c).Put(ls)
109 » » » » }, nil)
110
111 » » » » if err != nil {
112 » » » » » log.Fields{
113 » » » » » » log.ErrorKey: err,
114 » » » » » » "path": ls.Path(),
115 » » » » » }.Errorf(c, "Failed to archive log strea m.")
116 » » » » » atomic.AddInt32(&failed, 1)
117 » » » » » return nil // Nothing will consume it an yway.
118 » » » » }
119
120 » » » » log.Fields{
121 » » » » » "path": ls.Path(),
122 » » » » » "id": ls.HashID(),
123 » » » » » "archiveTask": ls.ArchiveTaskName,
124 » » » » }.Infof(c, "Created archive task.")
125 » » » » atomic.AddInt32(&tasked, 1)
149 return nil 126 return nil
150 } 127 }
151 128
152 » » default: 129 » » » return nil
153 » » » tasks = append(tasks, task) 130 » » })
154 » » » if len(tasks) < batch { 131 » }))
155 » » » » return nil
156 » » » }
157 » » }
158 132
159 » » err := ti.AddMulti(tasks, queueName) 133 » // Return an error code if we experienced any failures. This doesn't rea lly
160 » » if merr, ok := err.(errors.MultiError); ok { 134 » // have an impact, but it will show up as a "!" in the cron UI.
161 » » » for _, e := range merr { 135 » switch {
162 » » » » log.Warningf(c, "Task add error: %v", e) 136 » case ierr != nil:
163 » » » } 137 » » log.Fields{
164 » » } 138 » » » log.ErrorKey: err,
165 » » if err := errors.Filter(err, tq.ErrTaskAlreadyAdded); err != nil { 139 » » » "archiveCount": tasked,
166 » » » log.Fields{ 140 » » }.Errorf(c, "Failed to execute expired tasks query.")
167 » » » » log.ErrorKey: err, 141 » » return ierr
168 » » » » "queue": queueName,
169 » » » » "numTasks": len(tasks),
170 » » » » "scheduledTaskCount": totalScheduledTasks,
171 » » » }.Errorf(c, "Failed to add tasks to task queue.")
172 » » » return errors.New("failed to add tasks to task queue")
173 » » }
174 142
175 » » totalScheduledTasks += len(tasks) 143 » case failed > 0:
176 » » tasks = tasks[:0] 144 » » log.Fields{
145 » » » log.ErrorKey: err,
146 » » » "archiveCount": tasked,
147 » » » "failCount": failed,
148 » » }.Errorf(c, "Failed to archive candidate all streams.")
149 » » return errors.New("failed to archive all candidate streams")
150
151 » default:
152 » » log.Fields{
153 » » » "archiveCount": tasked,
154 » » }.Infof(c, "Archive sweep completed successfully.")
177 return nil 155 return nil
178 } 156 }
179
180 err = ds.Get(dsQueryBatch.BatchQueries(c, int32(batch))).Run(q, func(ls *coordinator.LogStream) error {
181 requireComplete := !now.After(ls.Updated.Add(maxDelay))
182 if !requireComplete {
183 log.Fields{
184 "path": ls.Path(),
185 "id": ls.HashID(),
186 "updatedTimestamp": ls.Updated,
187 "maxDelay": maxDelay,
188 }.Warningf(c, "Identified log stream past maximum archiv al delay.")
189 } else {
190 log.Fields{
191 "id": ls.HashID(),
192 "updated": ls.Updated.String(),
193 }.Infof(c, "Identified log stream ready for archival.")
194 }
195
196 task, err := createArchiveTask(cfg.GetCoordinator(), ls, require Complete)
197 if err != nil {
198 log.Fields{
199 log.ErrorKey: err,
200 "path": ls.Path(),
201 }.Errorf(c, "Failed to create archive task.")
202 return err
203 }
204
205 return addAndMaybeDispatchTasks(task)
206 })
207 if err != nil {
208 log.Fields{
209 log.ErrorKey: err,
210 "scheduledTaskCount": totalScheduledTasks,
211 }.Errorf(c, "Outer archive query failed.")
212 return errors.New("outer archive query failed")
213 }
214
215 // Dispatch any remaining enqueued tasks.
216 if err := addAndMaybeDispatchTasks(nil); err != nil {
217 return err
218 }
219
220 log.Fields{
221 "scheduledTaskCount": totalScheduledTasks,
222 }.Debugf(c, "Archive sweep completed successfully.")
223 return nil
224 } 157 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698