-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
2976 lines (2687 loc) · 92.3 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cassandra
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/uber/peloton/.gen/peloton/api/v0/job"
"github.com/uber/peloton/.gen/peloton/api/v0/peloton"
"github.com/uber/peloton/.gen/peloton/api/v0/query"
"github.com/uber/peloton/.gen/peloton/api/v0/task"
"github.com/uber/peloton/.gen/peloton/api/v0/update"
pb_volume "github.com/uber/peloton/.gen/peloton/api/v0/volume"
"github.com/uber/peloton/.gen/peloton/api/v1alpha/job/stateless"
v1alphapeloton "github.com/uber/peloton/.gen/peloton/api/v1alpha/peloton"
"github.com/uber/peloton/.gen/peloton/api/v1alpha/pod"
"github.com/uber/peloton/.gen/peloton/private/models"
versionutil "github.com/uber/peloton/pkg/common/util/entityversion"
"github.com/uber/peloton/pkg/common"
apiconvertor "github.com/uber/peloton/pkg/common/api"
"github.com/uber/peloton/pkg/common/backoff"
"github.com/uber/peloton/pkg/common/util"
"github.com/uber/peloton/pkg/storage"
"github.com/uber/peloton/pkg/storage/cassandra/api"
"github.com/uber/peloton/pkg/storage/cassandra/impl"
ormcassandra "github.com/uber/peloton/pkg/storage/connectors/cassandra"
ormobjects "github.com/uber/peloton/pkg/storage/objects"
qb "github.com/uber/peloton/pkg/storage/querybuilder"
_ "github.com/gemnasium/migrate/driver/cassandra" // Pull in C* driver for migrate
"github.com/gemnasium/migrate/migrate"
"github.com/gocql/gocql"
"github.com/gogo/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/uber-go/tally"
"go.uber.org/yarpc/yarpcerrors"
)
const (
taskIDFmt = "%s-%d"
// DB table names
jobConfigTable = "job_config"
jobRuntimeTable = "job_runtime"
jobIndexTable = "job_index"
taskConfigV2Table = "task_config_v2"
taskConfigTable = "task_config"
taskRuntimeTable = "task_runtime"
podEventsTable = "pod_events"
updatesTable = "update_info"
podWorkflowEventsTable = "pod_workflow_events"
frameworksTable = "frameworks"
updatesByJobView = "mv_updates_by_job"
volumeTable = "persistent_volumes"
// DB field names
creationTimeField = "creation_time"
completionTimeField = "completion_time"
stateField = "state"
// Task query sort by field
hostField = "host"
instanceIDField = "instanceId"
messageField = "message"
nameField = "name"
reasonField = "reason"
_defaultQueryLimit uint32 = 10
_defaultQueryMaxLimit uint32 = 100
_defaultWorkflowEventsDedupeWarnLimit = 1000
jobIndexTimeFormat = "20060102150405"
jobQueryDefaultSpanInDays = 7
jobQueryJitter = time.Second * 30
// _defaultPodEventsLimit is default number of pod events
// to read if not provided for jobID + instanceID
_defaultPodEventsLimit = 100
// Default context timeout for the method to cleanup old
// job updates from the storage
_jobUpdatesCleanupTimeout = 120 * time.Second
)
// GenerateTestCassandraConfig generates a test config for local C* client
// This is meant for sharing testing code only, not for production
func GenerateTestCassandraConfig() *Config {
return &Config{
CassandraConn: &impl.CassandraConn{
ContactPoints: []string{"127.0.0.1"},
Port: 9043,
CQLVersion: "3.4.2",
MaxGoRoutines: 1000,
},
StoreName: "peloton_test",
Migrations: "migrations",
Replication: &Replication{
Strategy: "SimpleStrategy",
Replicas: []*Replica{
{
Name: "replication_factor",
Value: 1,
},
},
},
}
}
// ToOrmConfig is needed to generate ORM config from legacy config so that the
// ORM code doesn't depend on legacy storage code and can be imported into the
// legacy code
func ToOrmConfig(c *Config) *ormcassandra.Config {
return &ormcassandra.Config{
CassandraConn: &ormcassandra.CassandraConn{
ContactPoints: c.CassandraConn.ContactPoints,
Port: c.CassandraConn.Port,
Username: c.CassandraConn.Username,
Password: c.CassandraConn.Password,
Consistency: c.CassandraConn.Consistency,
ConnectionsPerHost: c.CassandraConn.ConnectionsPerHost,
Timeout: c.CassandraConn.Timeout,
SocketKeepalive: c.CassandraConn.SocketKeepalive,
ProtoVersion: c.CassandraConn.ProtoVersion,
TTL: c.CassandraConn.TTL,
LocalDCOnly: c.CassandraConn.LocalDCOnly,
DataCenter: c.CassandraConn.DataCenter,
PageSize: c.CassandraConn.PageSize,
RetryCount: c.CassandraConn.RetryCount,
HostPolicy: c.CassandraConn.HostPolicy,
TimeoutLimit: c.CassandraConn.TimeoutLimit,
CQLVersion: c.CassandraConn.CQLVersion,
MaxGoRoutines: c.CassandraConn.MaxGoRoutines,
},
StoreName: c.StoreName,
}
}
type luceneClauses []string
// AutoMigrate migrates the db schemas for cassandra
func (c *Config) AutoMigrate() []error {
connString := c.MigrateString()
errs, ok := migrate.UpSync(connString, c.Migrations)
log.Infof("UpSync complete")
if !ok {
log.Errorf("UpSync failed with errors: %v", errs)
return errs
}
return nil
}
// MigrateString returns the db string required for database migration
// The code assumes that the keyspace (indicated by StoreName) is already created
func (c *Config) MigrateString() string {
// see https://github.com/gemnasium/migrate/pull/17 on why disable_init_host_lookup is needed
// This is for making local testing faster with docker running on mac
connStr := fmt.Sprintf("cassandra://%v:%v/%v?protocol=4&disable_init_host_lookup",
c.CassandraConn.ContactPoints[0],
c.CassandraConn.Port,
c.StoreName)
if len(c.CassandraConn.Username) != 0 {
connStr = fmt.Sprintf("cassandra://%v:%v@%v:%v/%v",
c.CassandraConn.Username,
c.CassandraConn.Password,
c.CassandraConn.ContactPoints[0],
c.CassandraConn.Port,
c.StoreName)
}
connStr = strings.Replace(connStr, " ", "", -1)
log.Infof("Cassandra migration string %v", connStr)
return connStr
}
// Store implements JobStore, TaskStore, UpdateStore, FrameworkInfoStore,
// and PersistentVolumeStore using a cassandra backend
// TODO: Break this up into different files (and or structs) that implement
// each of these interfaces to keep code modular.
type Store struct {
DataStore api.DataStore
jobConfigOps ormobjects.JobConfigOps
jobRuntimeOps ormobjects.JobRuntimeOps
jobUpdateEventsOps ormobjects.JobUpdateEventsOps
taskConfigV2Ops ormobjects.TaskConfigV2Ops
metrics *storage.Metrics
Conf *Config
retryPolicy backoff.RetryPolicy
}
// NewStore creates a Store
func NewStore(config *Config, scope tally.Scope) (*Store, error) {
dataStore, err := impl.CreateStore(config.CassandraConn, config.StoreName, scope)
if err != nil {
log.Errorf("Failed to NewStore, err=%v", err)
return nil, err
}
ormStore, ormErr := ormobjects.NewCassandraStore(
ToOrmConfig(config),
scope)
if ormErr != nil {
log.WithError(ormErr).Fatal("Failed to create ORM store for Cassandra")
}
return &Store{
DataStore: dataStore,
// DO NOT ADD MORE ORM Objects here. These are added here for
// supporting Job.Query() which cannot be fully moved to ORM
jobConfigOps: ormobjects.NewJobConfigOps(ormStore),
jobRuntimeOps: ormobjects.NewJobRuntimeOps(ormStore),
jobUpdateEventsOps: ormobjects.NewJobUpdateEventsOps(ormStore),
taskConfigV2Ops: ormobjects.NewTaskConfigV2Ops(ormStore),
metrics: storage.NewMetrics(scope.SubScope("storage")),
Conf: config,
retryPolicy: backoff.NewRetryPolicy(5, 50*time.Millisecond),
}, nil
}
func (s *Store) handleDataStoreError(err error, p backoff.Retrier) error {
retry := false
newErr := err
switch err.(type) {
// TBD handle errOverloaded and errBootstrapping after error types added in gocql
case *gocql.RequestErrReadFailure:
s.metrics.ErrorMetrics.ReadFailure.Inc(1)
return yarpcerrors.AbortedErrorf("read failure during statement execution %v", err.Error())
case *gocql.RequestErrWriteFailure:
s.metrics.ErrorMetrics.WriteFailure.Inc(1)
return yarpcerrors.AbortedErrorf("write failure during statement execution %v", err.Error())
case *gocql.RequestErrAlreadyExists:
s.metrics.ErrorMetrics.AlreadyExists.Inc(1)
return yarpcerrors.AlreadyExistsErrorf("already exists error during statement execution %v", err.Error())
case *gocql.RequestErrReadTimeout:
s.metrics.ErrorMetrics.ReadTimeout.Inc(1)
return yarpcerrors.DeadlineExceededErrorf("read timeout during statement execution: %v", err.Error())
case *gocql.RequestErrWriteTimeout:
s.metrics.ErrorMetrics.WriteTimeout.Inc(1)
return yarpcerrors.DeadlineExceededErrorf("write timeout during statement execution: %v", err.Error())
case *gocql.RequestErrUnavailable:
s.metrics.ErrorMetrics.RequestUnavailable.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("request unavailable during statement execution: %v", err.Error())
}
switch err {
case gocql.ErrTooManyTimeouts:
s.metrics.ErrorMetrics.TooManyTimeouts.Inc(1)
return yarpcerrors.DeadlineExceededErrorf("too many timeouts during statement execution: %v", err.Error())
case gocql.ErrUnavailable:
s.metrics.ErrorMetrics.ConnUnavailable.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("unavailable error during statement execution: %v", err.Error())
case gocql.ErrSessionClosed:
s.metrics.ErrorMetrics.SessionClosed.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("session closed during statement execution: %v", err.Error())
case gocql.ErrNoConnections:
s.metrics.ErrorMetrics.NoConnections.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("no connections during statement execution: %v", err.Error())
case gocql.ErrConnectionClosed:
s.metrics.ErrorMetrics.ConnectionClosed.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("connections closed during statement execution: %v", err.Error())
case gocql.ErrNoStreams:
s.metrics.ErrorMetrics.NoStreams.Inc(1)
retry = true
newErr = yarpcerrors.UnavailableErrorf("no streams during statement execution: %v", err.Error())
}
if retry {
if backoff.CheckRetry(p) {
return nil
}
return newErr
}
return newErr
}
func (s *Store) executeWrite(ctx context.Context, stmt api.Statement) (api.ResultSet, error) {
p := backoff.NewRetrier(s.retryPolicy)
for {
result, err := s.DataStore.Execute(ctx, stmt)
if err == nil {
return result, err
}
err = s.handleDataStoreError(err, p)
if err != nil {
if !common.IsTransientError(err) {
s.metrics.ErrorMetrics.NotTransient.Inc(1)
}
return result, err
}
}
}
func (s *Store) executeRead(
ctx context.Context,
stmt api.Statement) ([]map[string]interface{}, error) {
p := backoff.NewRetrier(s.retryPolicy)
for {
result, err := s.DataStore.Execute(ctx, stmt)
if err == nil {
if result != nil {
defer result.Close()
}
allResults, nErr := result.All(ctx)
if nErr == nil {
return allResults, nErr
}
result.Close()
err = nErr
}
err = s.handleDataStoreError(err, p)
if err != nil {
if !common.IsTransientError(err) {
s.metrics.ErrorMetrics.NotTransient.Inc(1)
}
return nil, err
}
}
}
// Compress a blob using gzip
func compress(buffer []byte) ([]byte, error) {
var b bytes.Buffer
w := gzip.NewWriter(&b)
if _, err := w.Write(buffer); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Uncompress a blob using gzip, return original blob if it was not compressed
func uncompress(buffer []byte) ([]byte, error) {
b := bytes.NewBuffer(buffer)
r, err := gzip.NewReader(b)
if err != nil {
if err == gzip.ErrHeader {
// blob was not compressed, so we can ignore this error. We can
// look for only checksum errors which will mean data corruption
return buffer, nil
}
return nil, err
}
defer r.Close()
uncompressed, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return uncompressed, nil
}
// GetMaxJobConfigVersion returns the maximum version of configs of a given job
func (s *Store) GetMaxJobConfigVersion(
ctx context.Context,
jobID string) (uint64, error) {
queryBuilder := s.DataStore.NewQuery()
stmt := queryBuilder.Select("MAX(version)").From(jobConfigTable).
Where(qb.Eq{"job_id": jobID})
allResults, err := s.executeRead(ctx, stmt)
if err != nil {
log.Errorf("Fail to get max version of job %v: %v", jobID, err)
return 0, err
}
log.Debugf("max version: %v", allResults)
for _, value := range allResults {
for _, max := range value {
// version is store as big int in Cassandra
// gocql would cast big int to int64
return uint64(max.(int64)), nil
}
}
return 0, nil
}
// WithTimeRangeFilter will take timerange and time_field (creation_time|completion_time) as
// input and create a range filter on those fields and append to the clauses list
func (c *luceneClauses) WithTimeRangeFilter(timeRange *peloton.TimeRange, timeField string) error {
if timeRange == nil || c == nil {
return nil
}
if timeField != creationTimeField && timeField != completionTimeField {
return fmt.Errorf("Invalid time field %s", timeField)
}
// Create filter if time range is not nil
min, err := ptypes.Timestamp(timeRange.GetMin())
if err != nil {
log.WithField("timeRange", timeRange).
WithField("timeField", timeField).
WithError(err).
Error("fail to get min time range")
return err
}
max, err := ptypes.Timestamp(timeRange.GetMax())
if err != nil {
log.WithField("timeRange", timeRange).
WithField("timeField", timeField).
WithError(err).
Error("fail to get max time range")
return err
}
// validate min and max limits are legit (i.e. max > min)
if max.Before(min) {
return fmt.Errorf("Incorrect timerange")
}
timeRangeMinStr := fmt.Sprintf(min.Format(jobIndexTimeFormat))
timeRangeMaxStr := fmt.Sprintf(max.Format(jobIndexTimeFormat))
*c = append(*c, fmt.Sprintf(`{type: "range", field:"%s", lower: "%s", upper: "%s", include_lower: true}`, timeField, timeRangeMinStr, timeRangeMaxStr))
return nil
}
// QueryJobs returns all jobs in the resource pool that matches the spec.
func (s *Store) QueryJobs(ctx context.Context, respoolID *peloton.ResourcePoolID, spec *job.QuerySpec, summaryOnly bool) ([]*job.JobInfo, []*job.JobSummary, uint32, error) {
// Query is based on stratio lucene index on jobs.
// See https://github.com/Stratio/cassandra-lucene-index
// We are using "must" for the labels and only return the jobs that contains all
// label values
// TODO: investigate if there are any golang library that can build lucene query
var clauses luceneClauses
if spec == nil {
return nil, nil, 0, nil
}
// Labels field must contain value of the specified labels
for _, label := range spec.GetLabels() {
clauses = append(clauses, fmt.Sprintf(`{type: "contains", field:"labels", values:%s}`, strconv.Quote(label.Value)))
}
// jobconfig field must contain all specified keywords
for _, word := range spec.GetKeywords() {
// Lucene for some reason does wildcard search as case insensitive
// However, to match individual words we still need to match
// by exact keyword. Using boolean filter to do this.
// using the "should" syntax will enable us to match on either
// wildcard search or exact match
wildcardWord := fmt.Sprintf("*%s*", strings.ToLower(word))
clauses = append(clauses, fmt.Sprintf(
`{type: "boolean",`+
`should: [`+
`{type: "wildcard", field:"config", value:%s},`+
`{type: "match", field:"config", value:%s}`+
`]`+
`}`, strconv.Quote(wildcardWord), strconv.Quote(word)))
}
// Add support on query by job state
// queryTerminalStates will be set if the spec contains any
// terminal job state. In this case we will restrict the
// job query to query for jobs over the last 7 days.
// This is a temporary fix so that lucene index query doesn't
// time out when searching for ALL jobs with terminal states
// which is a huge number.
// TODO (adityacb): change this once we have query spec support
// a custom time range
queryTerminalStates := false
if len(spec.GetJobStates()) > 0 {
values := ""
for i, s := range spec.GetJobStates() {
if util.IsPelotonJobStateTerminal(s) {
queryTerminalStates = true
}
values = values + strconv.Quote(s.String())
if i < len(spec.JobStates)-1 {
values = values + ","
}
}
clauses = append(clauses, fmt.Sprintf(`{type: "contains", field:"state", values:[%s]}`, values))
}
if respoolID != nil {
clauses = append(clauses, fmt.Sprintf(`{type: "contains", field:"respool_id", values:%s}`, strconv.Quote(respoolID.GetValue())))
}
owner := spec.GetOwner()
if owner != "" {
clauses = append(clauses, fmt.Sprintf(`{type: "match", field:"owner", value:%s}`, strconv.Quote(owner)))
}
name := spec.GetName()
if name != "" {
wildcardName := fmt.Sprintf("*%s*", name)
clauses = append(clauses, fmt.Sprintf(`{type: "wildcard", field:"name", value:%s}`, strconv.Quote(wildcardName)))
}
creationTimeRange := spec.GetCreationTimeRange()
completionTimeRange := spec.GetCompletionTimeRange()
err := clauses.WithTimeRangeFilter(creationTimeRange, creationTimeField)
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
err = clauses.WithTimeRangeFilter(completionTimeRange, completionTimeField)
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
// If no time range is specified in query spec, but the query is for terminal state,
// use default time range
if creationTimeRange == nil && completionTimeRange == nil && queryTerminalStates {
// Add jobQueryJitter to max bound to account for jobs
// that have just been created.
// if time range is not specified and the job is in terminal state,
// apply a default range of last 7 days
// TODO (adityacb): remove artificially enforcing default time range for
// completed jobs once UI supports query by time range.
now := time.Now().Add(jobQueryJitter).UTC()
max, err := ptypes.TimestampProto(now)
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
min, err := ptypes.TimestampProto(now.AddDate(0, 0, -jobQueryDefaultSpanInDays))
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
defaultCreationTimeRange := &peloton.TimeRange{Min: min, Max: max}
err = clauses.WithTimeRangeFilter(defaultCreationTimeRange, "creation_time")
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
}
where := `expr(job_index_lucene_v2, '{filter: [`
for i, c := range clauses {
if i > 0 {
where += ", "
}
where += c
}
where += "]"
// add default sorting by creation time in descending order in case orderby
// is not specificed in the query spec
var orderBy = spec.GetPagination().GetOrderBy()
if orderBy == nil || len(orderBy) == 0 {
orderBy = []*query.OrderBy{
{
Order: query.OrderBy_DESC,
Property: &query.PropertyPath{
Value: "creation_time",
},
},
}
}
// add sorter into the query
where += ", sort:["
count := 0
for _, order := range orderBy {
where += fmt.Sprintf("{field: \"%s\"", order.Property.GetValue())
if order.Order == query.OrderBy_DESC {
where += ", reverse: true"
}
where += "}"
if count < len(orderBy)-1 {
where += ","
}
count++
}
where += "]"
where += "}')"
maxLimit := _defaultQueryMaxLimit
if spec.GetPagination().GetMaxLimit() != 0 {
maxLimit = spec.GetPagination().GetMaxLimit()
}
where += fmt.Sprintf(" Limit %d", maxLimit)
log.WithField("where", where).Debug("query string")
queryBuilder := s.DataStore.NewQuery()
stmt := queryBuilder.Select("job_id",
"name",
"owner",
"job_type",
"respool_id",
"instance_count",
"labels",
"runtime_info").
From(jobIndexTable)
stmt = stmt.Where(where)
allResults, err := s.executeRead(ctx, stmt)
if err != nil {
uql, args, _, _ := stmt.ToUql()
log.WithField("labels", spec.GetLabels()).
WithField("uql", uql).
WithField("args", args).
WithError(err).
Error("fail to query jobs")
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
total := uint32(len(allResults))
// Apply offset and limit.
begin := spec.GetPagination().GetOffset()
if begin > total {
begin = total
}
allResults = allResults[begin:]
end := _defaultQueryLimit
if spec.GetPagination() != nil {
limit := spec.GetPagination().GetLimit()
if limit > 0 {
// end should not be 0, it will yield in empty result
end = limit
}
}
if end > uint32(len(allResults)) {
end = uint32(len(allResults))
}
allResults = allResults[:end]
summaryResults, err := s.getJobSummaryFromResultMap(ctx, allResults)
if summaryOnly {
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
// Lucene index entry for some batch jobs may be out of sync with the
// base job_index table. Scrub such jobs from the summary list.
summaryResults, err := s.reconcileStaleBatchJobsFromJobSummaryList(
ctx, summaryResults, queryTerminalStates)
if err != nil {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, err
}
s.metrics.JobMetrics.JobQuery.Inc(1)
return nil, summaryResults, total, nil
}
var results []*job.JobInfo
for _, value := range allResults {
id, ok := value["job_id"].(qb.UUID)
if !ok {
s.metrics.JobMetrics.JobQueryFail.Inc(1)
return nil, nil, 0, fmt.Errorf("got invalid response from cassandra")
}
jobID := &peloton.JobID{
Value: id.String(),
}
jobRuntime, err := s.jobRuntimeOps.Get(ctx, jobID)
if err != nil {
log.WithError(err).
WithField("job_id", id.String()).
Warn("no job runtime found when executing jobs query")
continue
}
// TODO (chunyang.shen): use job/task cache to get JobConfig T1760469
jobConfig, _, err := s.jobConfigOps.GetCurrentVersion(ctx, jobID)
if err != nil {
log.WithField("labels", spec.GetLabels()).
WithField("job_id", id.String()).
WithError(err).
Error("fail to query jobs as not able to get job config")
continue
}
// Unset instance config as its size can be huge as a workaround for UI query.
// We should figure out long term support for grpc size limit.
jobConfig.InstanceConfig = nil
results = append(results, &job.JobInfo{
Id: jobID,
Config: jobConfig,
Runtime: jobRuntime,
})
}
s.metrics.JobMetrics.JobQuery.Inc(1)
return results, summaryResults, total, nil
}
// CreateTaskRuntime creates a task runtime for a peloton job
func (s *Store) CreateTaskRuntime(
ctx context.Context,
jobID *peloton.JobID,
instanceID uint32,
runtime *task.RuntimeInfo,
owner string,
jobType job.JobType) error {
runtimeBuffer, err := proto.Marshal(runtime)
if err != nil {
log.WithField("job_id", jobID.GetValue()).
WithField("instance_id", instanceID).
WithError(err).
Error("Failed to create task runtime")
s.metrics.TaskMetrics.TaskCreateFail.Inc(1)
return err
}
queryBuilder := s.DataStore.NewQuery()
stmt := queryBuilder.Insert(taskRuntimeTable).
Columns(
"job_id",
"instance_id",
"version",
"update_time",
"state",
"runtime_info").
Values(
jobID.GetValue(),
instanceID,
runtime.GetRevision().GetVersion(),
time.Now().UTC(),
runtime.GetState().String(),
runtimeBuffer)
// IfNotExist() will cause Writing task runtimes to Cassandra concurrently
// failed with Operation timed out issue when batch size is small, e.g. 1.
// For now, we have to drop the IfNotExist()
taskID := fmt.Sprintf(taskIDFmt, jobID, instanceID)
if err := s.applyStatement(ctx, stmt, taskID); err != nil {
s.metrics.TaskMetrics.TaskCreateFail.Inc(1)
return err
}
s.metrics.TaskMetrics.TaskCreate.Inc(1)
err = s.addPodEvent(ctx, jobID, instanceID, runtime)
if err != nil {
log.Errorf("Unable to log task state changes for job ID %v instance %v, error = %v", jobID.GetValue(), instanceID, err)
return err
}
return nil
}
// addPodEvent upserts single pod state change for a Job -> Instance -> Run.
// Task state events are sorted by reverse chronological run_id and time of event.
func (s *Store) addPodEvent(
ctx context.Context,
jobID *peloton.JobID,
instanceID uint32,
runtime *task.RuntimeInfo) error {
var runID, prevRunID, desiredRunID uint64
var err, errMessage error
errLog := false
if runID, err = util.ParseRunID(
runtime.GetMesosTaskId().GetValue()); err != nil {
errLog = true
errMessage = err
}
// when creating a task, GetPrevMesosTaskId is empty,
// set prevRunID to 0
if len(runtime.GetPrevMesosTaskId().GetValue()) == 0 {
prevRunID = 0
} else if prevRunID, err = util.ParseRunID(
runtime.GetPrevMesosTaskId().GetValue()); err != nil {
errLog = true
errMessage = err
}
// old job does not have desired mesos task id, make it the same as runID
// TODO: remove the line after all tasks have desired mesos task id
if len(runtime.GetDesiredMesosTaskId().GetValue()) == 0 {
desiredRunID = runID
} else if desiredRunID, err = util.ParseRunID(
runtime.GetDesiredMesosTaskId().GetValue()); err != nil {
errLog = true
errMessage = err
}
if errLog {
s.metrics.TaskMetrics.PodEventsAddFail.Inc(1)
return errMessage
}
queryBuilder := s.DataStore.NewQuery()
stmt := queryBuilder.Insert(podEventsTable).
Columns(
"job_id",
"instance_id",
"run_id",
"desired_run_id",
"previous_run_id",
"update_time",
"actual_state",
"goal_state",
"healthy",
"hostname",
"agent_id",
"config_version",
"desired_config_version",
"volumeID",
"message",
"reason",
"update_timestamp").
Values(
jobID.GetValue(),
instanceID,
runID,
desiredRunID,
prevRunID,
qb.UUID{UUID: gocql.UUIDFromTime(time.Now())},
runtime.GetState().String(),
runtime.GetGoalState().String(),
runtime.GetHealthy().String(),
runtime.GetHost(),
runtime.GetAgentID().GetValue(),
runtime.GetConfigVersion(),
runtime.GetDesiredConfigVersion(),
runtime.GetVolumeID().GetValue(),
runtime.GetMessage(),
runtime.GetReason(),
time.Now()).Into(podEventsTable)
err = s.applyStatement(ctx, stmt, runtime.GetMesosTaskId().GetValue())
if err != nil {
s.metrics.TaskMetrics.PodEventsAddFail.Inc(1)
return err
}
s.metrics.TaskMetrics.PodEventsAddSuccess.Inc(1)
return nil
}
// GetPodEvents returns pod events for a Job + Instance + PodID (optional)
// Pod events are sorted by PodID + Timestamp
// only is called from this file
func (s *Store) GetPodEvents(
ctx context.Context,
jobID string,
instanceID uint32,
podID ...string) ([]*pod.PodEvent, error) {
var stmt qb.SelectBuilder
queryBuilder := s.DataStore.NewQuery()
// Events are sorted in descinding order by PodID and then update time.
stmt = queryBuilder.Select("*").From(podEventsTable).
Where(qb.Eq{
"job_id": jobID,
"instance_id": instanceID})
if len(podID) > 0 && len(podID[0]) > 0 {
runID, err := util.ParseRunID(podID[0])
if err != nil {
return nil, err
}
stmt = stmt.Where(qb.Eq{"run_id": runID})
} else {
statement := queryBuilder.Select("run_id").From(podEventsTable).
Where(qb.Eq{
"job_id": jobID,
"instance_id": instanceID}).
Limit(1)
res, err := s.executeRead(ctx, statement)
if err != nil {
s.metrics.TaskMetrics.PodEventsGetFail.Inc(1)
return nil, err
}
for _, value := range res {
stmt = stmt.Where(qb.Eq{"run_id": value["run_id"].(int64)})
}
}
allResults, err := s.executeRead(ctx, stmt)
if err != nil {
s.metrics.TaskMetrics.PodEventsGetFail.Inc(1)
return nil, err
}
var podEvents []*pod.PodEvent
b := bytes.Buffer{}
b.WriteString(jobID)
b.WriteString("-")
b.WriteString(strconv.FormatUint(uint64(instanceID), 10))
podName := b.String()
for _, value := range allResults {
podEvent := &pod.PodEvent{}
b.Reset()
b.WriteString(podName)
b.WriteString("-")
b.WriteString(strconv.FormatInt(value["run_id"].(int64), 10))
mesosTaskID := b.String()
b.Reset()
b.WriteString(podName)
b.WriteString("-")
b.WriteString(strconv.FormatInt(value["previous_run_id"].(int64), 10))
prevMesosTaskID := b.String()
b.Reset()
b.WriteString(podName)
b.WriteString("-")
b.WriteString(strconv.FormatInt(value["desired_run_id"].(int64), 10))
desiredMesosTaskID := b.String()
// Set podEvent fields
podEvent.PodId = &v1alphapeloton.PodID{
Value: mesosTaskID,
}
podEvent.PrevPodId = &v1alphapeloton.PodID{
Value: prevMesosTaskID,
}
podEvent.DesiredPodId = &v1alphapeloton.PodID{
Value: desiredMesosTaskID,
}
podEvent.Timestamp =
value["update_time"].(qb.UUID).Time().Format(time.RFC3339)
podEvent.Version = versionutil.GetPodEntityVersion(
uint64(value["config_version"].(int64)))
podEvent.DesiredVersion = versionutil.GetPodEntityVersion(
uint64(value["desired_config_version"].(int64)))
podEvent.ActualState = apiconvertor.ConvertTaskStateToPodState(
task.TaskState(task.TaskState_value[value["actual_state"].(string)])).String()
podEvent.DesiredState = apiconvertor.ConvertTaskStateToPodState(
task.TaskState(task.TaskState_value[value["goal_state"].(string)])).String()
podEvent.Healthy = pod.HealthState(
task.HealthState_value[value["healthy"].(string)]).String()
podEvent.Message = value["message"].(string)
podEvent.Reason = value["reason"].(string)
podEvent.AgentId = value["agent_id"].(string)
podEvent.Hostname = value["hostname"].(string)
podEvents = append(podEvents, podEvent)
}
s.metrics.TaskMetrics.PodEventsGetSucess.Inc(1)
return podEvents, nil
}
// DeletePodEvents deletes the pod events for provided JobID,
// InstanceID and RunID in the range [fromRunID-toRunID)
func (s *Store) DeletePodEvents(
ctx context.Context,
jobID string,
instanceID uint32,
fromRunID uint64,
toRunID uint64,
) error {
queryBuilder := s.DataStore.NewQuery()
stmt := queryBuilder.
Delete(podEventsTable).
Where(qb.Eq{"job_id": jobID, "instance_id": instanceID}).
Where("run_id >= ?", fromRunID).
Where("run_id < ?", toRunID)
if err := s.applyStatement(ctx, stmt, jobID); err != nil {
s.metrics.TaskMetrics.PodEventsDeleteFail.Inc(1)
return err
}
s.metrics.TaskMetrics.PodEventsDeleteSucess.Inc(1)
return nil
}