-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext-version.js
More file actions
1641 lines (1571 loc) · 52.4 KB
/
context-version.js
File metadata and controls
1641 lines (1571 loc) · 52.4 KB
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
'use strict'
const async = require('async')
const BaseSchema = require('models/mongo/schemas/base')
const Boom = require('dat-middleware').Boom
const exists = require('101/exists')
const find = require('101/find')
const hasKeypaths = require('101/has-keypaths')
const isObject = require('101/is-object')
const isString = require('101/is-string')
const keypather = require('keypather')()
const moment = require('moment')
const mongoose = require('mongoose')
const noop = require('101/noop')
const pick = require('101/pick')
const Promise = require('bluebird')
const monitorDog = require('monitor-dog')
const error = require('error')
const Github = require('models/apis/github')
const InfraCodeVersion = require('models/mongo/infra-code-version')
const logger = require('logger').child({ module: 'ContextVersion' })
const messenger = require('socket/messenger')
const monitor = require('monitor-dog')
const objectId = require('objectid')
const rabbitMQ = require('models/rabbitmq')
var ContextVersion
/**
* d1 >= d2
* @param {Date} d1 date1
* @param {Date} d2 date2
* @return {Boolean} d1 >= d2
*/
var dateGTE = function (d1, d2) {
return (d1 - d2) >= 0
}
var dateLTE = function (d1, d2) {
return (d1 - d2) <= 0
}
function emitIfCompleted (cv) {
var log = logger.child({
contextVersion: cv
})
log.trace('emitIfCompleted')
if (cv.build.completed) {
log.trace('emitIfCompleted completed true')
messenger.emitContextVersionUpdate(cv, 'build_completed')
} else {
log.trace('emitIfCompleted completed false')
}
}
var ContextVersionSchema = require('models/mongo/schemas/context-version')
/**
* @param {String} contextVersionId
* @return {ContextVersion}
* @throws {ContextVersion.NotFoundError} if not found
*/
ContextVersionSchema.statics.findContextVersionById = (contextVersionId) => {
return ContextVersion.findAndAssert({
_id: contextVersionId
})
}
/**
* @param {Object} query mongo format query
* @return {ContextVersion}
* @throws {ContextVersion.NotFoundError} if not found
*/
ContextVersionSchema.statics.findAndAssert = (query) => {
return ContextVersion.findOneAsync(query)
.tap((contextVersion) => {
if (!contextVersion) {
logger.error({ query }, 'failed to find context version')
throw new ContextVersion.NotFoundError(query)
}
})
}
/**
* @param {SessionUser} sessionUser
* @param {String} repoName
* @param {String} branchName - optional branch name
* @return {Object}
* @return {String} .repo
* @return {String} .lowerRepo
* @return {String} .commit
* @return {String} .branch
* @return {String} .publicKey
* @return {String} .privateKey
*/
ContextVersionSchema.statics.createAppcodeVersion = function (sessionUser, repoName, branchName) {
const log = logger.child({
method: 'createAppcodeVersion',
sessionUser, repoName, branchName
})
log.trace('called')
const token = sessionUser.accounts.github.accessToken
const github = new Github({ token })
return github.getRepoAsync(repoName)
.then((githubRepoInfo) => {
if (!branchName) {
return { githubRepoInfo }
}
return github.getBranchAsync(repoName, branchName)
.then(function (githubBranchInfo) {
return {
githubRepoInfo,
githubBranchInfo
}
})
})
.then((resp) => {
log.trace({ resp }, 'data from github')
const githubRepoInfo = resp.githubRepoInfo
const githubBranchInfo = resp.githubBranchInfo
const defaultBranch = githubRepoInfo.default_branch
const branch = githubBranchInfo ? githubBranchInfo.name : defaultBranch
return Promise.props({
keys: github.createHooksAndKeys(repoName),
branchInfo: githubBranchInfo || github.getBranchAsync(repoName, defaultBranch)
})
.then((githubInfo) => {
const commit = githubInfo.branchInfo.commit.sha
return {
repo: repoName,
lowerRepo: repoName.toLowerCase(),
commit,
branch,
publicKey: githubInfo.keys.publicKey,
privateKey: githubInfo.keys.privateKey
}
})
})
}
/**
* Modifies a ContextVersion query by adding AppCode specific conditions.
* @param {ContextVersion} contextVersion Context version to use when modifying
* the query.
* @param {object} query The mongo query to modify.
*/
ContextVersionSchema.statics.addAppCodeVersionQuery = function (
contextVersion,
query
) {
if (contextVersion.context) {
// Necessary because of multiple instances with same repo
query.context = objectId(contextVersion.context)
}
if (contextVersion.appCodeVersions.length) {
query.$and = query.$and || []
contextVersion.appCodeVersions.forEach(function (acv) {
query.$and.push({
appCodeVersions: {
$elemMatch: {
lowerRepo: acv.lowerRepo,
commit: acv.commit
}
}
})
})
query.$and.push({
appCodeVersions: {
$size: contextVersion.appCodeVersions.length
}
})
} else {
query.appCodeVersions = { $size: 0 }
}
return query
}
/**
* Writes the build logs from the context version and sends them through the socket
* @param stream
* @throws error when logs in not an array or a string
*/
ContextVersionSchema.methods.writeLogsToPrimusStream = function (stream) {
var logs = keypather.get(this, 'build.log')
if (isString(logs)) {
logs = [{
type: 'log',
content: logs
}]
} else if (!Array.isArray(logs)) {
throw new Error('cannot stream logs that are not strings or arrays')
}
var log = logger.child({
contextVersion: this,
logLength: logs.length,
streamId: stream.id
})
log.trace('writeLogsToPrimusStream')
var timer = monitor.timer('build_logs.streaming', true)
var startingIndex = 0
async.whilst(function () {
return startingIndex < logs.length
}, function (cb) {
var nextIndex = startingIndex + process.env.BUILD_LOG_PER_BATCH_LIMIT
var endingIndex = (logs.length < nextIndex) ? logs.length : nextIndex
stream.write(logs.slice(startingIndex, endingIndex))
startingIndex = nextIndex
setTimeout(cb)
}, function (err) {
log.trace('writeLogsToPrimusStream finished')
timer.stop()
stream.end()
if (err) {
throw err
}
})
}
/**
* @param {Object} props
* {String} props.context
* {String} props.createdBy.github
* {String} props.owner.github
* {String} props.advanced
* {Array} props.appCodeVersions
* @param {String} dockerFileContent
* @param {Object} infraCodeVersionProps
* @param {ObjectId} infraCodeVersionProps.parent
* @param {Boolean} infraCodeVersionProps.edited
* @return {ContextVersion}
*/
ContextVersionSchema.statics.createWithDockerFileContent = function (props, dockerFileContent, infraCodeVersionProps) {
const log = logger.child(Object.assign({
method: 'createWithDockerFileContent',
dockerFileContent,
infraCodeVersionProps
}, props))
log.info('called')
const infraCodeVersionOpts = Object.assign({
context: props.context
}, infraCodeVersionProps || {})
log.info({ infraCodeVersionOpts }, 'creating new infraCodeVersion')
const infraCodeVersion = new InfraCodeVersion(infraCodeVersionOpts)
return infraCodeVersion.initWithDefaultsAsync()
.then((newInfraCodeVersion) => {
return newInfraCodeVersion.saveAsync()
})
.then((savedInfraCodeVersion) => {
return savedInfraCodeVersion.createFsAsync({
name: 'Dockerfile',
path: '/',
body: dockerFileContent
})
.then(() => {
const cvOpts = Object.assign({}, props, {
infraCodeVersion: savedInfraCodeVersion._id
})
log.info({ opts: cvOpts }, 'saving contextVersion')
const contextVersion = new ContextVersion(cvOpts)
return contextVersion.saveAsync()
})
.tap((savedContextVersion) => {
log.info({ contextVersion: savedContextVersion }, 'saved contextVersion')
})
})
}
/**
* @param {Object} props
* {String} props.context
* {String} props.createdBy.github
* {String} props.owner.github
* {String} props.advanced
* {Array} props.appCodeVersions
* @param {ObjectId} infraCodeVersionProps.parent
* @param {Boolean} infraCodeVersionProps.edited
* @return {ContextVersion}
*/
ContextVersionSchema.statics.createWithNewInfraCode = function (props, infraCodeVersionProps) {
const log = logger.child(Object.assign({
method: 'createWithNewInfraCode',
infraCodeVersionProps
}, props))
log.info('called')
const infraCodeVersionOpts = Object.assign({
context: props.context
}, infraCodeVersionProps || {})
log.info({ infraCodeVersionOpts }, 'creating new infraCodeVersion')
const infraCodeVersion = new InfraCodeVersion(infraCodeVersionOpts)
return infraCodeVersion.initWithDefaultsAsync()
.then((newInfraCodeVersion) => {
return newInfraCodeVersion.saveAsync()
})
.then((savedInfraCodeVersion) => {
log.info({ infraCodeVersion: savedInfraCodeVersion }, 'saved infraCodeVersion')
const cvOpts = Object.assign({}, props, {
infraCodeVersion: savedInfraCodeVersion._id
})
log.info({ opts: cvOpts }, 'saving contextVersion')
const contextVersion = new ContextVersion(cvOpts)
return contextVersion.saveAsync()
.tap((savedContextVersion) => {
log.info({ contextVersion: savedContextVersion }, 'saved contextVersion')
})
})
.catch((err) => {
log.error({ err }, 'failed to save infraCodeVersion or contextVersion')
infraCodeVersion.bucket()
infraCodeVersion.removeSourceDir(noop)
throw err
})
}
var copyFields = [
'advanced',
'appCodeVersions',
'buildDockerfilePath',
'context',
'dockRemoved',
'owner',
'userContainerMemoryInBytes'
]
/**
* Creates a new Context Version.
* @param {Object} user User object who will be the 'createdBy' user.
* @param {Object} version Context Version to copy.
* @param {Function} cb Returns the new Context Version.
*/
ContextVersionSchema.statics.createDeepCopy = function (user, version, cb) {
const log = logger.child({
method: 'ContextVersionSchema.statics.createDeepCopy',
sessionUserId: keypather.get(user, 'accounts.github.id'),
contextVersion: version
})
log.info('called')
if (version.build) {
delete version.build.log
} else if (version._doc.build) {
delete version._doc.build.log
}
version = version.toJSON ? version.toJSON() : version
var newVersion = new ContextVersion(pick(version, copyFields))
if (version.dockerHost) {
newVersion.prevDockerHost = version.dockerHost
}
newVersion.createdBy = {
github: user.accounts.github.id
}
if (!version.infraCodeVersion) {
return cb(Boom.badImplementation('version is missing infraCodeVersion'))
}
InfraCodeVersion.createCopyById(version.infraCodeVersion,
function (err, newInfraCodeVersion) {
if (err) { return cb(err) }
newVersion.infraCodeVersion = newInfraCodeVersion._id
newVersion.save(function (err, version) {
if (err) {
newInfraCodeVersion.remove() // remove error handled below
}
cb(err, version)
})
})
}
/**
* Fetch github user models for an instance owner
* and instance createdBy user
* @param {Object} sessionUser
* @param {Function} cb
*/
ContextVersionSchema.methods.populateOwner = function (sessionUser, cb) {
const log = logger.child({
contextVersion: this,
sessionUser: sessionUser,
method: 'populateOwner'
})
log.trace('called')
var self = this
if (!sessionUser) {
return cb(Boom.badImplementation('SessionUser is required'))
}
sessionUser.findGithubUserByGithubId(this.owner.github, function (err, data) {
if (err) { return cb(err) }
self.owner.username = data.login
self.owner.gravatar = data.avatar_url
cb(null, self)
})
}
/**
* This function is used to not only set the started Date on the current ContextVersion object,
* but it throws an error if started has already been called previous to this iteration. This
* function also sets the edited flag on the InfraCodeVersion to false, since it can no longer
* be changed after this point.
* @param user user object of the current user
* @param buildProps {Object} Probably the body
* @param cb callback
*/
ContextVersionSchema.methods.setBuildStarted = function (user, buildProps, cb) {
if (typeof buildProps === 'function') {
cb = buildProps
buildProps = {}
}
const log = logger.child({
contextVersion: this,
sessionUser: user,
buildProps,
method: 'setBuildStarted'
})
log.info('called')
var update = {}
// FIXME: lets get rid of cv.containerId soon (now mirrors build._id)
// - used for buildLogs (change to build._id)
update.$set = {
'build.started': Date.now(),
'build.triggeredBy.github': user.accounts.github.id
}
Object.keys(buildProps).forEach(function (key) {
update.$set['build.' + key] = buildProps[key]
})
var contextVersion = this
var query = {
_id: contextVersion._id,
'build.started': {
$exists: false
}
}
var triggerAcv = keypather.get(buildProps, 'triggeredAction.appCodeVersion')
if (triggerAcv) {
query['appCodeVersions.lowerRepo'] = triggerAcv.repo.toLowerCase()
update.$set['appCodeVersions.$.commit'] = triggerAcv.commit
}
async.waterfall([
findAndCheckInfraCodeEditedFlag,
setContextVersionBuildStarted,
afterSetBuildStarted
], cb)
function findAndCheckInfraCodeEditedFlag (cb) {
const infraCodeVersionId = contextVersion.infraCodeVersion
log.info({ infraCodeVersionId }, 'search for infraCodeVersion')
InfraCodeVersion.findById(infraCodeVersionId, function (err, infraCodeVersion) {
if (err) { return cb(err) }
if (!infraCodeVersion) {
err = Boom.conflict('InfraCodeVersion could not be found', {
contextVersion: contextVersion._id,
infraCodeVersion: contextVersion.infraCodeVersion
})
return cb(err)
}
if (!infraCodeVersion.parent) {
// Something went horribly wrong somewhere if we're here. If an infraCode doesn't have
// a parent, and it doesn't have an edited property, it's a source
err = Boom.conflict('Cannot use source infracode versions with builds', {
debug: {
contextVersion: contextVersion._id,
infraCodeVersion: contextVersion.infraCodeVersion
}
})
return cb(err)
}
if (!infraCodeVersion.edited) {
log.trace({
infraCodeVersion
}, 'infraCodeVersion was not edited, using parent instead')
// If the current infraCodeVersion hasn't been edited, then we should set the
// contextVersion's infraCode to its parent, and delete this one
update.$set.infraCodeVersion = infraCodeVersion.parent
InfraCodeVersion.removeById(infraCodeVersion._id, error.logIfErr)
}
cb()
})
}
function setContextVersionBuildStarted (cb) {
ContextVersion.findOneAndUpdate(query, update, cb)
}
function afterSetBuildStarted (updatedContextVersion, cb) {
if (!updatedContextVersion) {
var err = Boom.conflict('Context version build is already in progress.', {
debug: { contextVersion: contextVersion._id }
})
return cb(err)
}
messenger.emitContextVersionUpdate(updatedContextVersion, 'build_starting')
cb(null, updatedContextVersion)
}
}
/**
* Finds and replaces with parentInfra if infra is unedited
* @param {callback} callback(self/duplicateVersion)
*/
ContextVersionSchema.methods.dedupeInfra = function (cb) {
const log = logger.child({
contextVersion: this,
method: 'dedupeInfra'
})
log.info('called')
var contextVersion = this
const icvId = contextVersion.infraCodeVersion
InfraCodeVersion.findById(icvId, function (err, icv) {
if (err) { return cb(err) }
if (!icv.edited) {
contextVersion.set('infraCodeVersion', icv.parent)
contextVersion.save(function (err) {
if (err) { return cb(err) }
log.info({ icvId }, 'deduped infra: use parent')
InfraCodeVersion.removeById(icvId, next)
})
} else {
next()
}
function next (err) {
cb(err, contextVersion)
}
})
}
/**
* Looks for completed contextVersions with the same state
* @param {Function} callback callback(self/duplicateVersion)
*/
ContextVersionSchema.methods.dedupe = function (callback) {
const log = logger.child({
method: 'ContextVersionSchema.methods.dedupe',
contextVersion: this,
started: this.started,
infraCodeVersion: this.infraCodeVersion
})
log.info('called')
var self = this
if (!this.owner) {
log.warn('dedupe !this.owner')
error.log(Boom.badImplementation('context version owner is null during dedupe', { cv: this }))
}
if (this.started) {
log.warn('dedupe !this.started')
// build is already started and possibly built. no need to check for duplicate.
return callback(null, self)
}
async.waterfall([
dedupeInfra,
dedupeSelf
], callback)
var query, opts, allFields
function dedupeInfra (cb) {
log.info('ContextVersionSchema.methods.dedupe dedupeInfra')
self.dedupeInfra(function (err) {
if (err) {
log.warn({
err: err
}, 'dedupe self.dedupeInfra error')
} else {
log.trace('dedupe self.dedupeInfra success')
}
cb(err)
})
}
function dedupeSelf (cb) {
log.info('ContextVersionSchema.methods.dedupe dedupeSelf')
// ownership is essentially verified by infraCodeVersionId
// but we should make this more secure
query = {
'build.failed': { $ne: true },
'build.started': { $exists: true },
infraCodeVersion: self.infraCodeVersion
}
if (exists(self.advanced)) {
query.advanced = self.advanced
}
query = ContextVersion.addAppCodeVersionQuery(self, query)
opts = {
sort: '-build.started',
limit: 1
}
allFields = null
// find all potential duplicates (acv branches may be different)
ContextVersion.find(query, allFields, opts, function (err, duplicates) {
if (err) {
log.error({
err: err
}, 'dedupe dedupeSelf ContextVersion.find error')
return cb(err)
}
var latestDupe = duplicates[0]
if (!latestDupe) {
log.trace('dedupe dedupeSelf no dupes found')
// no dupes found
return cb(null, self)
} else if (latestDupe.build.completed && keypather.get(latestDupe, 'build.failed')) {
// Build container failed, do not dedupe
log.trace('dedupe dedupeSelf build container failed, do not dedupe')
return cb(null, self)
} else { // dupes were found
log.trace('dedupe dedupeSelf - dupes found')
if (self.appCodeVersions.length === 0) {
log.trace('dedupe dedupeSelf - dupes found + no branches')
// No github repos, so no chance for branch to
// latestDupe is latestExactDupe in this case
self.remove(error.logIfErr) // delete self
if (!latestDupe.owner) {
var msg = 'latestDupe context version owner is null after dedupe'
error.log(Boom.badImplementation(msg, { cv: latestDupe }))
}
return cb(null, latestDupe)
} else {
log.trace('dedupe dedupeSelf - dupes found w/ branches')
// contextVersion has github repos -
// query only matches repo and commit (bc same commit can live on separate branches)
// make sure github repos branches match.
latestDupeWithSameBranches(function (err, latestExactDupe) {
if (err) {
log.error({
err: err
}, 'dedupe dedupeSelf latestDupeWithSameBranches error')
return cb(err)
}
if (latestExactDupe &&
dateGTE(latestExactDupe.build.started, latestDupe.build.started)) {
log.trace('dedupe dedupeSelf latestDupeWithSameBranches ' +
'found latest exact dupe')
// latest exact dupe will have exact same appCodeVersion branches
// also compare dates with the build-equivalent dupe and make sure it is the latest
self.remove(error.logIfErr) // delete self
if (!latestExactDupe.owner) {
log.warn('dedupe dedupeSelf latestDupeWithSameBranches ' +
'found latest exact dupe !owner')
var msg = 'latestDupe context version owner is null after exact dedupe'
error.log(Boom.badImplementation(msg, { cv: latestDupe }))
}
return cb(null, latestExactDupe)
} else {
log.trace('dedupe dedupeSelf latestDupeWithSameBranches no dupe found')
// no exact dupe found (repos and commits matched but branches didnt),
// or exact dupe was not the absolute latest build we have with that state (acv, icv)
// NOTE: Rely on "dedupeBuild" method called later on to handle this dedupe case
return cb(null, self)
}
})
}
}
})
}
function latestDupeWithSameBranches (cb) {
query.$and.map(function (acvQuery, i) {
if (acvQuery.appCodeVersions.$elemMatch) {
acvQuery.appCodeVersions.$elemMatch.lowerBranch =
self.appCodeVersions[i].lowerBranch
}
return acvQuery
})
ContextVersion.find(query, allFields, opts, function (err, exactDupes) {
if (err) { return cb(err) }
cb(null, exactDupes[0])
})
}
}
/**
* find context version in creating state
* @param {String} contextVersionId id of cv to find
* @returns {Promise}
* @resolves {Instance} when cv in creating state found
* @throws {ContextVersion.NotFoundError} If cv with contextVersionId not found
* @throws {ContextVersion.IncorrectStateError} If cv not in creating state
*/
ContextVersionSchema.statics.findOneCreating = (contextVersionId) => {
var log = logger.child({
contextVersionId,
method: 'findOneCreating'
})
log.info('called')
var query = {
_id: contextVersionId
}
return ContextVersion.findAndAssert(query)
.tap((contextVersion) => {
// state should not exist here.
if (contextVersion.state) {
throw new ContextVersion.IncorrectStateError('creating', contextVersion)
}
})
}
/**
* @param {string} buildId - build id associated with context version
* @param {string} errorMessage - runnable error message (optional)
* @return {Promise}
*/
ContextVersionSchema.statics.updateAndGetFailedBuild = (buildId, errorMessage) => {
var log = logger.child({
buildId: buildId,
method: 'updateWithFailedBuild'
})
log.info('updateWithFailedBuild called')
var update = {
$set: {
'build.completed': Date.now(),
'build.failed': true,
'state': ContextVersion.states.buildErrored
}
}
// if there is a runnable error we will have an error message
if (errorMessage) {
update.$set['build.error.message'] = errorMessage
}
return ContextVersion._updateByBuildIdAndEmit(buildId, update)
}
/**
* @param {string} buildId - build id associated with context version
* @return {Promise}
*/
ContextVersionSchema.statics.updateAndGetSuccessfulBuild = (buildId) => {
var log = logger.child({
buildId: buildId,
method: 'updateAndGetSuccessfulBuild'
})
log.info('updateAndGetSuccessfulBuild called')
var update = {
$set: {
'build.completed': Date.now(),
'build.failed': false,
'state': ContextVersion.states.buildSucceeded
}
}
return ContextVersion._updateByBuildIdAndEmit(buildId, update)
}
ContextVersionSchema.statics._updateByBuildIdAndEmit = (buildId, update) => {
return ContextVersion.updateByAsync('build._id', buildId, update, { multi: true })
.then(() => {
return ContextVersion.findByAsync('build._id', buildId)
})
.each(emitIfCompleted)
}
/**
* order of operations:
* - find contextVersionId, check to make sure it doesn't have the repo yet (409 otherwise), and
* add the new repo to it (atomically)
* - add the hook through github (pass error if we come to one)
* - if failed to add hook, revert change in mongo
* @param {SessionUser} sessionUser
* @param {String} contextVersionId
* @param {Object} repoInfo
* @param {String} repoInfo.commit
* @param {String} repoInfo.branch
* @param {String} repoInfo.repo
*/
ContextVersionSchema.statics.addGithubRepoToVersion = function (sessionUser, contextVersionId, repoInfo) {
var token = sessionUser.accounts.github.accessToken
var lowerRepo = repoInfo.repo.toLowerCase()
var github = new Github({ token })
return ContextVersion.findOneAndUpdateAsync({
_id: contextVersionId,
'appCodeVersions.lowerRepo': { $ne: lowerRepo }
}, {
$push: { appCodeVersions: repoInfo }
})
.tap((contextVersion) => {
// this is our check to make sure the repo isn't added to this context version yet
if (!contextVersion) {
throw Boom.conflict('Github Repository already added')
}
})
.then(() => {
return github.getRepoAsync(repoInfo.repo)
})
.then((githubRepoInfo) => {
return github.createHooksAndKeys(repoInfo.repo)
.catch((updateErr) => {
// we failed to talk with github - remove entry
// remove entry in appCodeVersions
return ContextVersion.findOneAndUpdateAsync({
_id: contextVersionId
}, {
$pull: {
appCodeVersions: {
lowerRepo: lowerRepo
}
}
})
.then((contextVersion) => {
if (!contextVersion) {
throw Boom.badImplementation('could not remove the repo from your project')
}
})
})
.then((githubKeys) => {
if (!githubKeys) {
throw new ContextVersion.DeployKeyError(contextVersionId)
}
// update the database with the keys that were added, and gogogo!
return ContextVersion.findOneAndUpdateAsync({
_id: contextVersionId,
'appCodeVersions.lowerRepo': lowerRepo
}, {
$set: {
'appCodeVersions.$.defaultBranch': githubRepoInfo.default_branch,
'appCodeVersions.$.publicKey': githubKeys.publicKey,
'appCodeVersions.$.privateKey': githubKeys.privateKey
}
})
.then((contextVersion) => {
if (!contextVersion) {
throw Boom.badImplementation('could not save deploy keys')
}
})
})
})
}
ContextVersionSchema.methods.pullAppCodeVersion = function (appCodeVersionId, cb) {
var log = logger.child({
appCodeVersionId: appCodeVersionId,
method: 'pullAppCodeVersion'
})
log.trace('pullAppCodeVersion called')
var contextVersion = this
var found =
find(contextVersion.appCodeVersions, hasKeypaths({
'_id.toString()': appCodeVersionId.toString()
}))
if (!found) {
cb(Boom.notFound('AppCodeVersion with _id "' + appCodeVersionId + '" not found'))
} else {
contextVersion.update({
$pull: {
appCodeVersions: {
_id: appCodeVersionId
}
}
}, cb)
}
}
/**
* returns the main appCodeVersion
* @param {object} appCodeVersions CV's appCodeVersions array
* @return {object} main appCodeVersion or null if not exist
*/
ContextVersionSchema.statics.getMainAppCodeVersion = function (appCodeVersions) {
var log = logger.child({
appCodeVersions: appCodeVersions,
method: 'getMainAppCodeVersion'
})
log.trace('getMainAppCodeVersion called')
if (!Array.isArray(appCodeVersions)) { return null }
if (appCodeVersions.length === 0) { return null }
return find(appCodeVersions, function (appCodeVersion) {
return !appCodeVersion.additionalRepo
})
}
/**
* returns the main appCodeVersion
* @return {object} main appCodeVersion
*/
ContextVersionSchema.methods.getMainAppCodeVersion = function () {
var log = logger.child({
contextVersion: this,
method: 'getMainAppCodeVersion'
})
log.trace('getMainAppCodeVersion called')
return ContextVersion.getMainAppCodeVersion(this.appCodeVersions)
}
/**
* Generate a query to query for appCodeVersions by repo, branch and commit
* @param {Array} [appCodeVersion] - Array of appCodeVersion
* @param {Object} appCodeVersion - Object with parameters to query appCodeVersions
* @param {String} appCodeVersion.repo - Name of repo for which to query appCodeVersions
* @param {String} appCodeVersion.branch - Name of branch for which to query appCodeVersions
* @param {String} appCodeVersion.commit - Commit for which to query appCodeVersions
* @returns {Object} acvs - query object for mongo
*/
ContextVersionSchema.statics.generateQueryForAppCodeVersions = function (appCodeVersions) {
var log = logger.child({
appCodeVersions: appCodeVersions,
method: 'generateQueryForAppCodeVersions'
})
log.trace('generateQueryForAppCodeVersions called')
if (!Array.isArray(appCodeVersions)) {
throw Boom.badRequest('`appCodeVersions` must be an array')
}
appCodeVersions.forEach(function (acv) {
if (!isObject(acv)) {
throw Boom.badRequest('All `appCodeVersion`s must be objects')
}
if (![acv.repo, acv.branch, acv.commit].every(isString)) {
throw Boom.badRequest('`appCodeVersion` repo, branch and commit properties are required and must all be strings')
}
})
/* We need to get the versions that match the app code versions we were given in an
* array (i.e. [{repo, branch, commit}, {repo, branch, commit}]). This function loops
* quickly over that list and makes a mongo query so that we match ALL the truples we
* were given, and (with the $size parameter) not a subset.
*/
var acvsQuery = {
$size: 0,
$all: [
// for reference, this is what we need to have in $all
// {
// $elemMatch: {
// repo: '',
// branch: '',
// commit: ''
// }
// }
]
}
appCodeVersions.forEach(function (acv) {
acvsQuery.$size += 1
var elemMatch = {
$elemMatch: {
lowerRepo: acv.repo.toLowerCase(),
lowerBranch: acv.branch.toLowerCase(),
commit: acv.commit
}
}
acvsQuery.$all.push(elemMatch)
})
return acvsQuery
}
/**
* Generate a query to query for appCodeVersions by repo and branch
* @param {String} repo - Name of the repo
* @param {String} branch - Name of the branch
* @returns {Object} query - query object for mongo
*/
ContextVersionSchema.statics.generateQueryForBranchAndRepo = function (repo, branch) {
var log = logger.child({
repo: repo,
branch: branch,
method: 'generateQueryForBranchAndRepo'
})
log.trace('generateQueryForBranchAndRepo called')
if (!isString(repo) || !isString(branch)) {
throw Boom.badRequest('`repo` and `branch` must both be strings')
}
return {
appCodeVersions: {
$elemMatch: {
lowerRepo: repo.toLowerCase(),
lowerBranch: branch.toLowerCase(),
additionalRepo: { $exists: false }
}
}
}
}
ContextVersionSchema.methods.modifyAppCodeVersionWithLatestCommit = function (user, cb) {
const log = logger.child({
contextVersion: this,
user: user,
method: 'modifyAppCodeVersionWithLatestCommit'
})
log.info('called')
var self = this
var updatableAdditionalRepos = this.appCodeVersions.filter(function (acv) {
return acv.additionalRepo && acv.useLatest
})
// if nothing to update - just return current contextVersion
if (!updatableAdditionalRepos || updatableAdditionalRepos.length === 0) {
log.trace('finish no updatableAdditionalRepos')
return cb(null, this)
}
// This token might belong to HelloRunnable since this API call might be
// called by the worker. It might not have access to the branch
var githubToken = keypather.get(user, 'accounts.github.accessToken')
async.each(updatableAdditionalRepos, function (acv, eachCb) {
var github = new Github({ token: githubToken })
log.trace(
{ repo: acv.repo, branch: acv.branch },
'modifyAppCodeVersionWithLatestCommit getBranch'
)
github.getBranch(acv.repo, acv.branch, function (err, branch) {
if (err) {
log.error(
{ repo: acv.repo, branch: acv.branch, err: err },
'modifyAppCodeVersionWithLatestCommit getBranch failed. Does this user have access to this repo?'
)
return eachCb(err)
}
var commit = keypather.get(branch, 'commit.sha')
self.modifyAppCodeVersion(acv._id, { commit: commit }, eachCb)
})