-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJenkinsfile
More file actions
1554 lines (1332 loc) · 85.1 KB
/
Copy pathJenkinsfile
File metadata and controls
1554 lines (1332 loc) · 85.1 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
// Jenkinsfile for FLUID CLI Package Building
// Builds Python wheel on every commit and stores in artifact branch
pipeline {
agent any
environment {
// Package info
PACKAGE_NAME = 'fluid-forge'
PACKAGE_DIR = '.'
// Infrastructure config - sourced from Jenkins parameters (set via Build with Parameters)
// First run: click "Build with Parameters" and fill in your NAS details
// Subsequent runs: Jenkins remembers the last values
NAS_HOST = "${params.NAS_HOST}"
NAS_SSH_USER = "${params.NAS_SSH_USER}"
PYPI_PORT = "${params.PYPI_PORT}"
// Artifact storage - SEPARATE REPOSITORY (constructed from params)
ARTIFACT_REPO = "ssh://${params.NAS_SSH_USER}@${params.NAS_HOST}/volume1/git-server/fluid-cli-builds.git"
ARTIFACT_DIR = 'builds'
// Source Git config
GIT_SERVER = "ssh://${params.NAS_SSH_USER}@${params.NAS_HOST}/volume1/git-server/dustlabs/at/fluid/fluid-forge-cli.git"
SDK_REPO = "ssh://${params.NAS_SSH_USER}@${params.NAS_HOST}/volume1/git-server/dustlabs/at/fluid/fluid-provider-sdk.git"
// PyPI config (constructed from params)
PYPI_URL = "http://${params.NAS_HOST}:${params.PYPI_PORT}"
PYPI_SIMPLE_URL = "http://${params.NAS_HOST}:${params.PYPI_PORT}/simple"
// Docker registry
DOCKER_REGISTRY = "${params.DOCKER_REGISTRY}"
DOCKER_IMAGE = "${params.DOCKER_REGISTRY}/fluid-forge-cli"
// Python config
PYTHON_VERSION = '3.11'
}
options {
buildDiscarder(logRotator(numToKeepStr: '30'))
timestamps()
timeout(time: 30, unit: 'MINUTES')
}
stages {
stage('Validate Parameters') {
steps {
script {
if (!params.NAS_HOST?.trim()) {
currentBuild.result = 'NOT_BUILT'
currentBuild.description = 'First run — parameters registered. Re-run with "Build with Parameters".'
echo """
╔══════════════════════════════════════════════════════════════╗
║ ✅ PIPELINE REGISTERED — Parameters are now available ║
╠══════════════════════════════════════════════════════════════╣
║ ║
║ This was a first-run scan. Jenkins has now loaded the ║
║ pipeline parameters. ║
║ ║
║ NEXT STEP: Click "Build with Parameters" and set: ║
║ • NAS_HOST → Your NAS IP (e.g. 192.168.1.100) ║
║ • NAS_SSH_USER → SSH user on the NAS ║
║ • PYPI_PORT → Private PyPI port (default: 8080) ║
║ • DOCKER_REGISTRY → Docker registry (default: localhost) ║
║ ║
║ Jenkins will remember these values for future builds. ║
╚══════════════════════════════════════════════════════════════╝
"""
// Stop the entire pipeline gracefully (grey status, not red)
error('First-run parameter registration complete. Re-run with "Build with Parameters".')
}
echo "✅ Infrastructure config: NAS=${params.NAS_HOST}, User=${params.NAS_SSH_USER}, PyPI port=${params.PYPI_PORT}, Docker=${params.DOCKER_REGISTRY}"
}
}
}
stage('Clean Workspace') {
steps {
echo "🧹 Cleaning workspace for fresh build..."
cleanWs()
// Checkout fresh code
checkout scm
echo "✅ Fresh workspace ready"
}
}
stage('Setup Python Environment') {
steps {
script {
// Multi-Profile Pipeline Strategy
// Check if this is a promoted build (override profile)
if (params.OVERRIDE_PROFILE) {
env.BUILD_PROFILE = params.OVERRIDE_PROFILE
env.PROFILES_TO_BUILD = params.OVERRIDE_PROFILE
env.INITIAL_PROFILE = params.OVERRIDE_PROFILE
echo "🔄 PROMOTED BUILD from ${params.PARENT_BUILD}"
echo "🎯 Building forced profile: ${params.OVERRIDE_PROFILE}"
} else {
// Normal branch-based detection
def branchName = env.BRANCH_NAME ?: 'unknown'
// Determine which profiles to build in cascade
if (branchName == 'main') {
env.PROFILES_TO_BUILD = 'experimental,stable'
env.INITIAL_PROFILE = 'experimental'
} else if (branchName.startsWith('release/beta')) {
env.PROFILES_TO_BUILD = 'experimental,beta,stable'
env.INITIAL_PROFILE = 'experimental'
} else {
// Feature branches build all profiles
env.PROFILES_TO_BUILD = 'experimental,alpha,beta,stable'
env.INITIAL_PROFILE = 'experimental'
}
env.BUILD_PROFILE = env.INITIAL_PROFILE
echo "🔧 Multi-Profile Cascade Build"
echo "📦 Branch: ${branchName}"
echo "🎯 Profile cascade: ${env.PROFILES_TO_BUILD}"
echo "▶️ Starting with: ${env.BUILD_PROFILE}"
}
}
echo "Setting up Python environment"
sh '''
cd ${PACKAGE_DIR}
# Find available Python 3 by actually testing it
PYTHON_CMD=""
for py in python3.11 python3.10 python3.9 python3.8 python3; do
if $py --version >/dev/null 2>&1; then
PYTHON_CMD=$py
echo "Found working Python: $PYTHON_CMD"
break
fi
done
if [ -z "$PYTHON_CMD" ]; then
echo "ERROR: Python 3.8+ not found!"
echo "Tried: python3.11, python3.10, python3.9, python3.8, python3"
exit 1
fi
echo "Using Python: $PYTHON_CMD ($($PYTHON_CMD --version 2>&1))"
# Create virtual environment (try venv first, fallback to virtualenv)
if $PYTHON_CMD -m venv .venv 2>/dev/null; then
echo "Created venv successfully"
elif $PYTHON_CMD -m pip install --user --break-system-packages virtualenv 2>/dev/null && $PYTHON_CMD -m virtualenv .venv; then
echo "Created virtualenv successfully"
else
echo "ERROR: Could not create virtual environment"
echo "Installing python3-venv on Jenkins server..."
echo "Please run: sudo apt install python3-venv python3-pip"
exit 1
fi
# Activate and upgrade pip
. .venv/bin/activate
pip install --upgrade pip setuptools wheel
# Install build tools and feature release dependencies
pip install build twine pyyaml
'''
}
}
stage('Publish SDK to Private PyPI') {
steps {
echo "📦 Ensuring fluid-provider-sdk is available"
withCredentials([usernamePassword(credentialsId: 'pypi-server-credentials',
usernameVariable: 'PYPI_USER',
passwordVariable: 'PYPI_PASS'),
sshUserPrivateKey(credentialsId: 'khyana-synology-git-ssh',
keyFileVariable: 'SSH_KEY')]) {
sh '''
export GIT_SSH_COMMAND="ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no"
echo "Building fluid-provider-sdk from source..."
SDK_DIR=$(mktemp -d)
git clone --depth 1 ${SDK_REPO} "${SDK_DIR}/fluid-provider-sdk" || {
echo "❌ Could not clone SDK repo from ${SDK_REPO}"
echo "Ensure the repo exists on your git server."
exit 1
}
cd "${SDK_DIR}/fluid-provider-sdk"
. ${WORKSPACE}/${PACKAGE_DIR}/.venv/bin/activate
python -m build
# Install SDK wheel directly into the build venv
pip install dist/fluid_provider_sdk-*.whl
# Save a copy of the wheel for the test venv later
mkdir -p ${WORKSPACE}/.sdk-wheels
cp dist/fluid_provider_sdk-*.whl ${WORKSPACE}/.sdk-wheels/
# Also upload to private PyPI (best-effort)
twine upload \
--repository-url ${PYPI_URL} \
-u "${PYPI_USER}" -p "${PYPI_PASS}" \
dist/*.whl dist/*.tar.gz || {
echo "⚠️ twine upload returned non-zero — package may already exist"
}
cd ${WORKSPACE}
rm -rf "${SDK_DIR}"
echo "✅ fluid-provider-sdk installed into venv and uploaded to ${PYPI_URL}"
'''
}
}
}
stage('Feature Status Check') {
steps {
echo "📋 Checking feature status for ${BUILD_PROFILE} profile"
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
# Set build profile
export FLUID_BUILD_PROFILE=${BUILD_PROFILE}
echo "═══════════════════════════════════════════════════════"
echo " Build Profile: ${BUILD_PROFILE}"
echo " Branch: ${GIT_BRANCH}"
echo "═══════════════════════════════════════════════════════"
# Show feature status
python scripts/check_features.py
# Export build metadata for later stages
cat > export_metadata.py << 'PYTHON_SCRIPT'
import fluid_build
import json
summary = fluid_build.get_features_summary()
print()
print("=== Build Summary ===")
print("Profile: {}".format(summary["profile"]))
print("Providers: {}".format(", ".join(summary["providers"])))
print("Provider Count: {}".format(summary["provider_count"]))
print("Command Count: {}".format(summary["command_count"]))
# Export to file for artifact metadata
with open('build_metadata.json', 'w') as f:
json.dump(summary, f, indent=2)
# Export to env file for Jenkins
with open('build_profile.env', 'w') as f:
f.write("PROFILE={}\\n".format(summary["profile"]))
f.write("PROVIDER_COUNT={}\\n".format(summary["provider_count"]))
f.write("COMMAND_COUNT={}\\n".format(summary["command_count"]))
f.write("PROVIDERS={}\\n".format(",".join(summary["providers"])))
PYTHON_SCRIPT
python export_metadata.py
rm export_metadata.py
# Show exported metadata
echo ""
echo "=== Exported Metadata ==="
cat build_profile.env
echo ""
'''
// Load metadata into environment variables
script {
def propsFile = readFile("build_profile.env").trim()
propsFile.split("\n").each { line ->
if (line.trim() && line.contains('=')) {
def parts = line.split('=', 2)
def key = parts[0].trim()
def value = parts[1].trim()
// Use individual assignments instead of env[key] which is blocked by sandbox
if (key == 'PROFILE') {
env.PROFILE = value
} else if (key == 'PROVIDER_COUNT') {
env.PROVIDER_COUNT = value
} else if (key == 'COMMAND_COUNT') {
env.COMMAND_COUNT = value
} else if (key == 'PROVIDERS') {
env.PROVIDERS = value
}
}
}
echo "✅ Loaded: ${env.PROVIDER_COUNT} providers (${env.PROVIDERS}), ${env.COMMAND_COUNT} commands"
}
}
}
stage('Provider Quality Assessment') {
steps {
echo "🔍 Assessing provider quality for ${BUILD_PROFILE} profile"
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
echo "════════════════════════════════════════════════════════════════════════"
echo " Provider Quality Assessment"
echo "════════════════════════════════════════════════════════════════════════"
# Get list of enabled providers for this build profile
export FLUID_BUILD_PROFILE=${BUILD_PROFILE}
ENABLED_PROVIDERS=$(python3 -c "
import fluid_build
providers = fluid_build.get_enabled_providers()
print(' '.join(providers))
")
echo "Enabled providers for ${BUILD_PROFILE}: $ENABLED_PROVIDERS"
echo ""
# Determine quality level based on build profile
case "${BUILD_PROFILE}" in
stable)
QUALITY_LEVEL="stable"
STRICT_MODE="--strict"
;;
beta)
QUALITY_LEVEL="beta"
STRICT_MODE=""
;;
alpha)
QUALITY_LEVEL="alpha"
STRICT_MODE=""
;;
*)
QUALITY_LEVEL="alpha"
STRICT_MODE=""
;;
esac
echo "Quality level: $QUALITY_LEVEL"
echo "Strict mode: ${STRICT_MODE:-disabled}"
echo ""
# Assess each enabled provider
ASSESSMENT_FAILED=0
for provider in $ENABLED_PROVIDERS; do
echo "\\n--- Assessing: $provider ---"
if python3 scripts/assess_provider.py --provider $provider --level $QUALITY_LEVEL $STRICT_MODE; then
echo "✅ $provider meets $QUALITY_LEVEL criteria"
else
echo "⚠️ $provider does not fully meet $QUALITY_LEVEL criteria"
if [ "${BUILD_PROFILE}" = "stable" ]; then
ASSESSMENT_FAILED=1
fi
fi
done
# Fail build if stable and any provider failed
if [ $ASSESSMENT_FAILED -eq 1 ]; then
echo "\\n❌ QUALITY GATE FAILED: One or more providers do not meet stable criteria"
exit 1
fi
echo "\\n✅ All provider quality checks passed for ${BUILD_PROFILE} profile"
'''
}
}
stage('Run Tests') {
steps {
echo "🧪 Running test suite with coverage analysis"
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
# Install package with test dependencies
pip install -e ".[dev,test]" pytest-cov pytest-json-report
# Run tests with coverage (if they exist)
if [ -d "tests" ]; then
echo "═══════════════════════════════════════════════════════"
echo " Running Tests with Coverage Analysis"
echo " Profile: ${BUILD_PROFILE}"
echo "═══════════════════════════════════════════════════════"
# Run ALL tests with coverage
# Provider coverage will be extracted from the overall coverage.json
pytest tests/ \
--cov=fluid_build \
--cov-report=term \
--cov-report=json:coverage.json \
--cov-report=html:htmlcov \
--json-report \
--json-report-file=test-report.json \
--maxfail=5 \
--disable-warnings \
-v || TEST_EXIT_CODE=$?
# Always show coverage summary
if [ -f "coverage.json" ]; then
echo ""
echo "═══════════════════════════════════════════════════════"
echo " Coverage Report"
echo "═══════════════════════════════════════════════════════"
python3 -c "
import json
with open('coverage.json') as f:
cov = json.load(f)
total_cov = cov['totals']['percent_covered']
print(f'Overall Coverage: {total_cov:.1f}%')
print()
print('Per-File Coverage:')
for file, data in sorted(cov['files'].items()):
if 'fluid_build' in file:
pct = data['summary']['percent_covered']
print(f' {file}: {pct:.1f}%')
"
fi
# Store test exit code for later quality gates
# Don't exit here - we want to generate reports even if tests fail
echo "${TEST_EXIT_CODE:-0}" > test-exit-code.txt
echo "Test exit code: ${TEST_EXIT_CODE:-0} (saved for quality gates)"
else
echo "⚠️ No tests found, skipping test execution..."
echo "WARNING: Building without test coverage data"
# Create empty coverage file for downstream stages
echo '{"totals": {"percent_covered": 0}, "files": {}}' > coverage.json
echo '{"summary": {"passed": 0, "failed": 0, "total": 0}}' > test-report.json
echo "0" > test-exit-code.txt
fi
'''
// Generate test report for risk assessment
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
echo ""
echo "═══════════════════════════════════════════════════════"
echo " Generating Test Coverage Report"
echo "═══════════════════════════════════════════════════════"
# Generate report for current profile
python scripts/generate_test_report.py ${BUILD_PROFILE}
# Display summary
if [ -f build-test-report.md ]; then
echo ""
echo "📊 Test Report Summary:"
head -n 30 build-test-report.md
fi
'''
// Parse test results and coverage using Python (readJSON not available)
sh '''
cd ${PACKAGE_DIR}
# Extract coverage percentage
if [ -f coverage.json ]; then
python3 -c "import json; data=json.load(open('coverage.json')); print(data['totals']['percent_covered'])" > coverage-pct.txt
echo "📊 Overall Test Coverage: $(cat coverage-pct.txt)%"
else
echo "0" > coverage-pct.txt
echo "⚠️ No coverage data available"
fi
# Extract test counts
# Note: pytest-json-report omits keys with 0 count, so use .get() with defaults
if [ -f test-report.json ]; then
python3 -c "import json; s=json.load(open('test-report.json')).get('summary',{}); print(s.get('passed',0))" > tests-passed.txt
python3 -c "import json; s=json.load(open('test-report.json')).get('summary',{}); print(s.get('failed',0))" > tests-failed.txt
python3 -c "import json; s=json.load(open('test-report.json')).get('summary',{}); print(s.get('total', s.get('collected',0)))" > tests-total.txt
echo "✅ Tests: $(cat tests-passed.txt)/$(cat tests-total.txt) passed"
else
echo "0" > tests-passed.txt
echo "0" > tests-failed.txt
echo "0" > tests-total.txt
fi
'''
script {
env.OVERALL_COVERAGE = readFile("coverage-pct.txt").trim()
env.TESTS_PASSED = readFile("tests-passed.txt").trim()
env.TESTS_FAILED = readFile("tests-failed.txt").trim()
env.TESTS_TOTAL = readFile("tests-total.txt").trim()
}
}
}
stage('Build Package') {
steps {
echo "🏗️ Building Python wheel with ${BUILD_PROFILE} profile"
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
# Set build profile environment variable
export FLUID_BUILD_PROFILE=${BUILD_PROFILE}
echo "═══════════════════════════════════════════════════════"
echo " Building with Profile: ${BUILD_PROFILE}"
echo " Providers: ${PROVIDER_COUNT}"
echo " Commands: ${COMMAND_COUNT}"
echo "═══════════════════════════════════════════════════════"
# CRITICAL: Uninstall any previously installed version
echo "🧹 Uninstalling any existing fluid-forge package..."
pip uninstall -y fluid-forge 2>/dev/null || echo "No previous installation found"
# FORCE CLEAN BUILD - remove ALL cached files
echo "🧹 Removing all cached build artifacts..."
rm -rf dist/ build/ *.egg-info
rm -rf fluid_build/*.pyc fluid_build/__pycache__
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
find . -type f -name '*.pyc' -delete 2>/dev/null || true
find . -type f -name '*.pyo' -delete 2>/dev/null || true
# Clear Python import cache
echo "🧹 Clearing Python import cache..."
python3 -c "import sys; sys.path.insert(0, '.'); import importlib; importlib.invalidate_caches()"
# Build wheel and source distribution
python -m build
# List created files
echo "=== Built Packages ==="
ls -lh dist/
# Verify wheel
twine check dist/*.whl
# Verify profile is correctly set
echo "\n=== Verifying Build Profile ==="
python3 -c "import fluid_build; assert fluid_build.get_build_profile() == '${BUILD_PROFILE}', 'Profile mismatch!'; print('✅ Profile verified: ${BUILD_PROFILE}')"
# CRITICAL: Save version info NOW before PyPI publishing overwrites dist/
# Extract version from the wheel we just built
WHEEL_FILE=$(ls dist/*.whl | head -1)
BUILT_VERSION=$(basename "$WHEEL_FILE" | sed 's/fluid_forge-//;s/-py3.*//')
echo "$BUILT_VERSION" > built-version.txt
echo "📦 Saved built version for Docker stage: $BUILT_VERSION"
'''
}
}
stage('Quality Gates') {
when {
expression { env.BUILD_PROFILE in ['stable', 'beta'] }
}
steps {
echo "🚦 Enforcing quality gates for ${BUILD_PROFILE} profile with test data"
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
echo "═══════════════════════════════════════════════════════"
echo " Quality Gate Validation: ${BUILD_PROFILE}"
echo "═══════════════════════════════════════════════════════"
# Validate with actual test results and coverage
python3 << "QUALITY_GATES_EOF"
import yaml
import sys
# Load build manifest (simple version)
manifest = yaml.safe_load(open('fluid_build/build-manifest.yaml'))
print('\\nBuild Manifest for ${BUILD_PROFILE}:')
build_config = manifest['builds']['${BUILD_PROFILE}']
print(f" Description: {build_config['description']}")
print(f" Commands: {len(build_config.get('commands', []))}")
print(f" Providers: {len(build_config.get('providers', []))}")
# Load actual test results
coverage_pct = float('${OVERALL_COVERAGE}' or '0')
tests_passed = int('${TESTS_PASSED}' or '0')
tests_failed = int('${TESTS_FAILED}' or '0')
tests_total = int('${TESTS_TOTAL}' or '0')
print(f'\\n📊 Actual Test Results:')
print(f' Tests: {tests_passed}/{tests_total} passed ({tests_failed} failed)')
print(f' Coverage: {coverage_pct:.1f}%')
# Check if tests actually failed (exit code != 0)
test_exit_code = 0
try:
with open('test-exit-code.txt') as f:
test_exit_code = int(f.read().strip())
except:
pass
if test_exit_code != 0:
print(f'\\n⚠️ Tests exited with code {test_exit_code}')
# Manifest-driven quality gates (no coverage thresholds)
# You control what's packaged via build-manifest.yaml
# This only checks: do tests pass?
if '${BUILD_PROFILE}' == 'stable':
print('\\n🔒 STABLE - Quality Check')
if tests_failed > 0:
print(f' ❌ FAILED: {tests_failed} tests failing')
sys.exit(1)
print(f' ✅ All {tests_total} tests passing')
print(f' ℹ️ Coverage: {coverage_pct:.1f}% (review build-test-report.md)')
elif '${BUILD_PROFILE}' == 'beta':
print('\\n⚠️ BETA - Quality Check')
if tests_failed > 0:
print(f' ❌ FAILED: {tests_failed} tests failing')
sys.exit(1)
print(f' ✅ All {tests_total} tests passing')
print(f' ℹ️ Coverage: {coverage_pct:.1f}% (review build-test-report.md)')
else:
# Alpha - just report
print('\\n🔧 ALPHA - Quality Check')
if tests_failed > 0:
print(f' ⚠️ {tests_failed} test failures (not blocking alpha)')
else:
print(f' ✅ All {tests_total} tests passing')
print(f' ℹ️ Coverage: {coverage_pct:.1f}% (review build-test-report.md)')
print('\\n✅ Quality checks complete for ${BUILD_PROFILE}')
QUALITY_GATES_EOF
# Test package installation
echo ""
echo "═══════════════════════════════════════════════════════"
echo " Package Installation Verification"
echo "═══════════════════════════════════════════════════════"
TEST_VENV=/tmp/test-fluid-${BUILD_NUMBER}
python3 -m venv $TEST_VENV
$TEST_VENV/bin/pip install --upgrade pip -q
$TEST_VENV/bin/pip install ${WORKSPACE}/.sdk-wheels/fluid_provider_sdk-*.whl -q
$TEST_VENV/bin/pip install dist/*.whl -q
# Verify installed package works
$TEST_VENV/bin/python3 -c "import fluid_build; print(f'✅ Version: {fluid_build.__version__}')"
$TEST_VENV/bin/python3 -c "import fluid_build; print(f'✅ Providers: {list(fluid_build.get_enabled_providers())}')"
# Cleanup
rm -rf $TEST_VENV
echo ""
echo "✅ All quality gates PASSED for ${BUILD_PROFILE}"
'''
}
}
stage('Determine Next Profile') {
steps {
script {
// Determine if we should build next profile
def currentProfile = env.BUILD_PROFILE
def profilesList = env.PROFILES_TO_BUILD.split(',')
def currentIndex = profilesList.findIndexOf { it == currentProfile }
echo "📍 Current profile: ${currentProfile} (index ${currentIndex} of ${profilesList.size()})"
if (currentIndex >= 0 && currentIndex < profilesList.size() - 1) {
def failed = (env.TESTS_FAILED ?: '0') as Integer
def nextProfile = profilesList[currentIndex + 1]
// Manifest-driven promotion: tests pass = cascade continues
// NO thresholds - you control risk via build-manifest.yaml
// Review build-test-report.md to decide what to include
if (failed == 0) {
env.BUILD_NEXT_PROFILE = nextProfile
echo "✅ ${currentProfile} tests pass → will build ${nextProfile} next"
echo " Review build-test-report.md for risk assessment"
} else {
env.BUILD_NEXT_PROFILE = 'none'
echo "❌ ${currentProfile} stopping cascade - ${failed} test failures"
echo " Fix tests before cascading to ${nextProfile}"
}
} else {
env.BUILD_NEXT_PROFILE = 'none'
echo "🏁 ${currentProfile} is the final profile"
}
}
}
}
stage('Version & Tag Build') {
steps {
script {
// Extract version from package
def version = sh(
script: """
cd ${PACKAGE_DIR}
python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])" 2>/dev/null || \
grep 'version' pyproject.toml | head -1 | cut -d'"' -f2
""",
returnStdout: true
).trim()
env.PACKAGE_VERSION = version
// Add profile suffix for non-stable builds
def profileSuffix = env.BUILD_PROFILE == 'stable' ? '' : "+${env.BUILD_PROFILE}"
env.BUILD_TAG = "${version}${profileSuffix}.build${BUILD_NUMBER}"
// Also set wheel filename for reference
env.WHEEL_FILE = "fluid_build-${version}-py3-none-any.whl"
env.GIT_COMMIT_SHORT = sh(
script: 'git rev-parse --short HEAD',
returnStdout: true
).trim()
echo "Package Version: ${PACKAGE_VERSION}"
echo "Build Profile: ${BUILD_PROFILE}"
echo "Build Tag: ${BUILD_TAG}"
echo "Git Commit: ${GIT_COMMIT_SHORT}"
echo "Providers: ${env.PROVIDERS}"
echo "Commands: ${env.COMMAND_COUNT}"
}
}
}
stage('Publish to PyPI') {
steps {
echo "� Multi-Profile PyPI Publishing (Alpha + Beta + Conditional Stable)"
echo "Publishing to private PyPI server: ${PYPI_URL}"
withCredentials([usernamePassword(credentialsId: 'pypi-server-credentials',
usernameVariable: 'PYPI_USER',
passwordVariable: 'PYPI_PASS')]) {
sh '''
cd ${PACKAGE_DIR}
. .venv/bin/activate
# Export credentials for publish script
export PYPI_USER="${PYPI_USER}"
export PYPI_PASS="${PYPI_PASS}"
# Run multi-profile publishing script
chmod +x fluid_build/publish-to-pypi.sh
echo "════════════════════════════════════════════════════════"
echo " Publishing All Build Profiles"
echo "════════════════════════════════════════════════════════"
cd fluid_build
./publish-to-pypi.sh all
echo ""
echo "✅ All profiles published to ${PYPI_URL}"
'''
}
}
}
stage('Build Docker Images') {
steps {
echo "🐳 Building Docker images for all build profiles"
withCredentials([usernamePassword(credentialsId: 'pypi-server-credentials',
usernameVariable: 'PYPI_USER',
passwordVariable: 'PYPI_PASS')]) {
sh '''
cd ${PACKAGE_DIR}
echo "════════════════════════════════════════════════════════"
echo " Building FLUID CLI Docker Images"
echo "════════════════════════════════════════════════════════"
# Make build script executable
chmod +x build-docker-image.sh
# Read version from saved file (created in Build Package stage)
# This is necessary because PyPI publishing overwrites dist/ directory
if [ ! -f built-version.txt ]; then
echo "ERROR: built-version.txt not found!"
echo "This file should be created in the Build Package stage"
exit 1
fi
BASE_VERSION=$(cat built-version.txt)
BUILD_NUM=${BUILD_NUMBER}
echo "📦 Using version from Build Package stage: ${BASE_VERSION}"
echo " (Read from built-version.txt)"
# Build Docker images with explicit versions for each profile
# Extract core version (strip any dev/alpha/beta suffix for base)
CORE_VERSION=$(echo "${BASE_VERSION}" | sed 's/\\.dev[0-9]*//;s/a[0-9]*//;s/b[0-9]*//')
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Building Docker image for profile: experimental"
echo " Version: ${CORE_VERSION}.dev${BUILD_NUM}"
echo " Registry: ${DOCKER_REGISTRY}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
./build-docker-image.sh \
--profile experimental \
--version "${CORE_VERSION}.dev${BUILD_NUM}" \
--registry ${DOCKER_REGISTRY} \
--pypi-url ${PYPI_SIMPLE_URL} \
--pypi-user "${PYPI_USER}" \
--pypi-pass "${PYPI_PASS}" \
--no-cache
# Also tag as experimental-latest
docker tag ${DOCKER_IMAGE}:${CORE_VERSION}.dev${BUILD_NUM} \
${DOCKER_IMAGE}:experimental-latest
docker push ${DOCKER_IMAGE}:experimental-latest
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Building Docker image for profile: alpha"
echo " Version: ${CORE_VERSION}a${BUILD_NUM}"
echo " Registry: ${DOCKER_REGISTRY}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
./build-docker-image.sh \
--profile alpha \
--version "${CORE_VERSION}a${BUILD_NUM}" \
--registry ${DOCKER_REGISTRY} \
--pypi-url ${PYPI_SIMPLE_URL} \
--pypi-user "${PYPI_USER}" \
--pypi-pass "${PYPI_PASS}" \
--no-cache
docker tag ${DOCKER_IMAGE}:${CORE_VERSION}a${BUILD_NUM} \
${DOCKER_IMAGE}:alpha-latest
docker push ${DOCKER_IMAGE}:alpha-latest
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Building Docker image for profile: beta"
echo " Version: ${CORE_VERSION}b${BUILD_NUM}"
echo " Registry: ${DOCKER_REGISTRY}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
./build-docker-image.sh \
--profile beta \
--version "${CORE_VERSION}b${BUILD_NUM}" \
--registry ${DOCKER_REGISTRY} \
--pypi-url ${PYPI_SIMPLE_URL} \
--pypi-user "${PYPI_USER}" \
--pypi-pass "${PYPI_PASS}" \
--no-cache
docker tag ${DOCKER_IMAGE}:${CORE_VERSION}b${BUILD_NUM} \
${DOCKER_IMAGE}:beta-latest
docker push ${DOCKER_IMAGE}:beta-latest
# ═══════════════════════════════════════════════════════════════
# STABLE BUILD - MATURITY GATE
# ═══════════════════════════════════════════════════════════════
# Stable builds require explicit approval via ALLOW_STABLE_BUILD
# This prevents accidentally publishing immature code as stable
# ═══════════════════════════════════════════════════════════════
if [ "${ALLOW_STABLE_BUILD}" = "true" ]; then
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " Building Docker image for profile: stable"
echo " Version: ${CORE_VERSION}"
echo " 🔒 STABLE BUILD APPROVED"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
./build-docker-image.sh \
--profile stable \
--version "${CORE_VERSION}" \
--registry ${DOCKER_REGISTRY} \
--pypi-url ${PYPI_SIMPLE_URL} \
--pypi-user "${PYPI_USER}" \
--pypi-pass "${PYPI_PASS}" \
--no-cache
docker tag ${DOCKER_IMAGE}:${CORE_VERSION} \
${DOCKER_IMAGE}:stable-latest
docker push ${DOCKER_IMAGE}:stable-latest
docker tag ${DOCKER_IMAGE}:${CORE_VERSION} \
${DOCKER_IMAGE}:latest
docker push ${DOCKER_IMAGE}:latest
echo "✅ Stable build completed and published"
else
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " ⚠️ SKIPPING STABLE BUILD"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Stable builds are DISABLED by default to prevent publishing"
echo "immature code. The codebase is not yet ready for stable release."
echo ""
echo "To build stable when ready:"
echo " 1. Ensure test coverage meets stable criteria"
echo " 2. Ensure all providers meet quality standards"
echo " 3. Run build with: ALLOW_STABLE_BUILD=true"
echo ""
echo "Current maturity status:"
echo " ✅ Experimental: Full feature set (kitchen sink)"
echo " ✅ Alpha: Bleeding edge features"
echo " ✅ Beta: Feature complete preview"
echo " ⏸️ Stable: BLOCKED - not yet production ready"
echo ""
echo "Continuing with experimental/alpha/beta only..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
fi
echo ""
echo "════════════════════════════════════════════════════════"
echo " Docker Build Summary"
echo "════════════════════════════════════════════════════════"
# List all built images
docker images ${DOCKER_IMAGE} --format "table {{.Repository}}:{{.Tag}}\\t{{.Size}}\\t{{.CreatedAt}}"
echo ""
echo "✅ All Docker images built and pushed to ${DOCKER_REGISTRY}"
'''
}
}
}
// ─────────────────────────────────────────────────────────────────────
// OPTIONAL: Upload to a separate git-based artifact repository.
// This stores .whl files + metadata JSON in a dedicated git repo
// for easy distribution (git clone → pip install).
//
// This stage is NOT required — PyPI + Docker + Jenkins archive
// already have the build artifacts. This is an extra convenience.
//
// To enable, you need:
// 1. A bare git repo on your server:
// ssh <user>@<host> "git init --bare /path/to/fluid-cli-builds.git"
// 2. A Jenkins SSH credential (ID: 'khyana-synology-git-ssh')
// containing the private key for the NAS_SSH_USER
// 3. The ARTIFACT_REPO env var above points to that repo
//
// If the repo doesn't exist or credentials are missing, this stage
// will warn and continue — it won't fail your build.
// ─────────────────────────────────────────────────────────────────────
stage('Upload to Artifact Storage') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE', message: 'Artifact upload skipped — see console for details') {
echo "Uploading to separate artifact repository: ${ARTIFACT_REPO}"
withCredentials([sshUserPrivateKey(credentialsId: 'khyana-synology-git-ssh', keyFileVariable: 'SSH_KEY')]) {
sh """#!/bin/bash
set -ex
# Configure Git to use SSH key
export GIT_SSH_COMMAND="ssh -i \${SSH_KEY} -o StrictHostKeyChecking=no"
# Clone artifact repository to temp location
TEMP_DIR=\$(mktemp -d)
git clone \${ARTIFACT_REPO} \${TEMP_DIR} || {
echo ""
echo "════════════════════════════════════════════════════════"
echo " ⚠️ ARTIFACT REPOSITORY NOT AVAILABLE"
echo "════════════════════════════════════════════════════════"
echo ""
echo " Could not clone: \${ARTIFACT_REPO}"
echo ""
echo " This is OPTIONAL — your build artifacts are already"
echo " available via PyPI, Docker, and Jenkins archive."
echo ""
echo " To set up the artifact repo (one-time):"
echo " ssh \${NAS_SSH_USER}@\${NAS_HOST} \\\\"
echo " \\"git init --bare /volume1/git-server/fluid-cli-builds.git\\""
echo ""
echo " Also ensure Jenkins credential 'khyana-synology-git-ssh'"
echo " contains a valid SSH private key for \${NAS_SSH_USER}@\${NAS_HOST}"
echo "════════════════════════════════════════════════════════"
echo ""
rm -rf \${TEMP_DIR}
exit 1
}
cd \${TEMP_DIR}
# Ensure builds directory exists
mkdir -p \${ARTIFACT_DIR}
# Copy wheel to artifact directory with build metadata
cp \${WORKSPACE}/\${PACKAGE_DIR}/dist/*.whl \${ARTIFACT_DIR}/
# Get wheel filename safely
WHEEL_FILE=\$(ls \${WORKSPACE}/\${PACKAGE_DIR}/dist/*.whl | xargs -n1 basename)
# Determine release type based on build profile
if [ "\${BUILD_PROFILE}" = "stable" ]; then
RELEASE_TYPE="production"
elif [ "\${BUILD_PROFILE}" = "beta" ]; then
RELEASE_TYPE="public-beta"
else
RELEASE_TYPE="development"
fi
# Create build metadata file with feature release info
cat > \${ARTIFACT_DIR}/\${PACKAGE_NAME}-\${BUILD_TAG}.json <<EOF_JSON
{
"version": "\${PACKAGE_VERSION}",
"build_number": "\${BUILD_NUMBER}",
"build_tag": "\${BUILD_TAG}",
"build_profile": "\${BUILD_PROFILE}",
"git_commit": "\${GIT_COMMIT_SHORT}",