/
api.go
3724 lines (3241 loc) · 106 KB
/
api.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
package weldr
import (
"archive/tar"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
errors_package "errors"
"fmt"
"io"
"log"
"math"
"math/big"
"net"
"net/http"
"net/url"
"os"
"path"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/gobwas/glob"
"github.com/google/uuid"
"github.com/julienschmidt/httprouter"
"github.com/osbuild/osbuild-composer/pkg/jobqueue"
"github.com/osbuild/images/pkg/arch"
"github.com/osbuild/images/pkg/container"
"github.com/osbuild/images/pkg/distro"
"github.com/osbuild/images/pkg/distrofactory"
"github.com/osbuild/images/pkg/distroidparser"
"github.com/osbuild/images/pkg/dnfjson"
"github.com/osbuild/images/pkg/osbuild"
"github.com/osbuild/images/pkg/ostree"
"github.com/osbuild/images/pkg/reporegistry"
"github.com/osbuild/images/pkg/rhsm/facts"
"github.com/osbuild/images/pkg/rpmmd"
"github.com/osbuild/osbuild-composer/internal/blueprint"
"github.com/osbuild/osbuild-composer/internal/common"
"github.com/osbuild/osbuild-composer/internal/store"
"github.com/osbuild/osbuild-composer/internal/target"
"github.com/osbuild/osbuild-composer/internal/worker"
)
type API struct {
store *store.Store
workers *worker.Server
solver *dnfjson.BaseSolver
hostArch string
repoRegistry *reporegistry.RepoRegistry
logger *log.Logger
router *httprouter.Router
server http.Server
compatOutputDir string
hostDistroName string // Name of the host distro
distroFactory *distrofactory.Factory // Available distros
// List of ImageType names, which should not be exposed by the API
distrosImageTypeDenylist map[string][]string
}
type ComposeState int
const (
ComposeWaiting ComposeState = iota
ComposeRunning
ComposeFinished
ComposeFailed
)
// ToString converts ImageBuildState into a human readable string
func (cs ComposeState) ToString() string {
switch cs {
case ComposeWaiting:
return "WAITING"
case ComposeRunning:
return "RUNNING"
case ComposeFinished:
return "FINISHED"
case ComposeFailed:
return "FAILED"
default:
panic("invalid ComposeState value")
}
}
// systemRepoNames returns a list of the system repos
// NOTE: The system repos have no concept of id vs. name so the id is returned
func (api *API) systemRepoNames() (names []string) {
repos, err := api.repoRegistry.ReposByArchName(api.hostDistroName, api.hostArch, false)
if err == nil {
for _, repo := range repos {
names = append(names, repo.Name)
}
}
return names
}
// validDistros returns a sorted list of distributions that also have
// repositories defined for the given architecture
func (api *API) validDistros(arch string) []string {
distros := []string{}
for _, distroName := range api.repoRegistry.ListDistros() {
distro := api.distroFactory.GetDistro(distroName)
if distro == nil {
if api.logger != nil {
api.logger.Printf("Distro %s has repositories defined, but it's not supported. Skipping.", distroName)
}
continue
}
_, err := api.repoRegistry.DistroHasRepos(distroName, arch)
if err == nil {
distros = append(distros, distroName)
} else {
if api.logger != nil {
api.logger.Printf("Distro %s has no repositories defined for %s architecture, skipping.", distroName, arch)
}
}
}
sort.Strings(distros)
return distros
}
var ValidBlueprintName = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
// NewTestAPI is used for the test framework, sets up a single distro
func NewTestAPI(solver *dnfjson.BaseSolver, rr *reporegistry.RepoRegistry,
logger *log.Logger, storeFixture *store.Fixture, workers *worker.Server,
compatOutputDir string, distrosImageTypeDenylist map[string][]string) *API {
api := &API{
store: storeFixture.Store,
workers: workers,
solver: solver,
hostArch: storeFixture.HostArchName,
repoRegistry: rr,
logger: logger,
compatOutputDir: compatOutputDir,
hostDistroName: storeFixture.HostDistroName,
distroFactory: storeFixture.Factory,
distrosImageTypeDenylist: distrosImageTypeDenylist,
}
return setupRouter(api)
}
func New(rr *reporegistry.RepoRegistry, stateDir string, solver *dnfjson.BaseSolver, df *distrofactory.Factory,
logger *log.Logger, workers *worker.Server, distrosImageTypeDenylist map[string][]string) (*API, error) {
if logger == nil {
logger = log.New(os.Stdout, "", 0)
}
hostDistroName, err := distro.GetHostDistroName()
if err != nil {
return nil, fmt.Errorf("failed to read host distro information")
}
hostArch := arch.Current().String()
hostDistro := df.GetDistro(hostDistroName)
if hostDistro != nil {
// get canonical distro name if the host distro is supported
hostDistroName = hostDistro.Name()
_, err = hostDistro.GetArch(hostArch)
if err != nil {
return nil, fmt.Errorf("Host distro does not support host architecture: %v", err)
}
// Check if repositories for the host distro and arch were loaded
_, err = rr.ReposByArchName(hostDistroName, hostArch, false)
if err != nil {
log.Printf("loaded repository definitions don't contain any for the host distro/arch: %v", err)
}
} else {
log.Printf("host distro %q is not supported: only cross-distro builds are available", hostDistroName)
}
store := store.New(&stateDir, df, logger)
compatOutputDir := path.Join(stateDir, "outputs")
api := &API{
store: store,
workers: workers,
solver: solver,
hostArch: hostArch,
repoRegistry: rr,
logger: logger,
compatOutputDir: compatOutputDir,
hostDistroName: hostDistroName,
distroFactory: df,
distrosImageTypeDenylist: distrosImageTypeDenylist,
}
return setupRouter(api), nil
}
func setupRouter(api *API) *API {
api.router = httprouter.New()
api.router.RedirectTrailingSlash = false
api.router.RedirectFixedPath = false
api.router.MethodNotAllowed = http.HandlerFunc(methodNotAllowedHandler)
api.router.NotFound = http.HandlerFunc(notFoundHandler)
api.router.GET("/api/status", api.statusHandler)
api.router.GET("/api/v:version/projects/source/list", api.sourceListHandler)
api.router.GET("/api/v:version/projects/source/info/", api.sourceEmptyInfoHandler)
api.router.GET("/api/v:version/projects/source/info/:sources", api.sourceInfoHandler)
api.router.POST("/api/v:version/projects/source/new", api.sourceNewHandler)
api.router.DELETE("/api/v:version/projects/source/delete/*source", api.sourceDeleteHandler)
api.router.GET("/api/v:version/projects/depsolve", api.projectsDepsolveHandler)
api.router.GET("/api/v:version/projects/depsolve/*projects", api.projectsDepsolveHandler)
api.router.GET("/api/v:version/modules/list", api.modulesListHandler)
api.router.GET("/api/v:version/modules/list/*modules", api.modulesListHandler)
api.router.GET("/api/v:version/projects/list", api.projectsListHandler)
api.router.GET("/api/v:version/projects/list/", api.projectsListHandler)
// these are the same, except that modules/info also includes dependencies
api.router.GET("/api/v:version/modules/info", api.modulesInfoHandler)
api.router.GET("/api/v:version/modules/info/*modules", api.modulesInfoHandler)
api.router.GET("/api/v:version/projects/info", api.modulesInfoHandler)
api.router.GET("/api/v:version/projects/info/*modules", api.modulesInfoHandler)
api.router.GET("/api/v:version/blueprints/list", api.blueprintsListHandler)
api.router.GET("/api/v:version/blueprints/info/*blueprints", api.blueprintsInfoHandler)
api.router.GET("/api/v:version/blueprints/depsolve/*blueprints", api.blueprintsDepsolveHandler)
api.router.GET("/api/v:version/blueprints/freeze/*blueprints", api.blueprintsFreezeHandler)
api.router.GET("/api/v:version/blueprints/diff/:blueprint/:from/:to", api.blueprintsDiffHandler)
api.router.GET("/api/v:version/blueprints/change/:blueprint/:commit", api.blueprintsChangeHandler)
api.router.GET("/api/v:version/blueprints/changes/*blueprints", api.blueprintsChangesHandler)
api.router.POST("/api/v:version/blueprints/new", api.blueprintsNewHandler)
api.router.POST("/api/v:version/blueprints/workspace", api.blueprintsWorkspaceHandler)
api.router.POST("/api/v:version/blueprints/undo/:blueprint/:commit", api.blueprintUndoHandler)
api.router.POST("/api/v:version/blueprints/tag/:blueprint", api.blueprintsTagHandler)
api.router.DELETE("/api/v:version/blueprints/delete/:blueprint", api.blueprintDeleteHandler)
api.router.DELETE("/api/v:version/blueprints/workspace/:blueprint", api.blueprintDeleteWorkspaceHandler)
api.router.POST("/api/v:version/compose", api.composeHandler)
api.router.DELETE("/api/v:version/compose/delete/:uuids", api.composeDeleteHandler)
api.router.GET("/api/v:version/compose/types", api.composeTypesHandler)
api.router.GET("/api/v:version/compose/queue", api.composeQueueHandler)
api.router.GET("/api/v:version/compose/status/:uuids", api.composeStatusHandler)
api.router.GET("/api/v:version/compose/info/:uuid", api.composeInfoHandler)
api.router.GET("/api/v:version/compose/finished", api.composeFinishedHandler)
api.router.GET("/api/v:version/compose/failed", api.composeFailedHandler)
api.router.GET("/api/v:version/compose/image/:uuid", api.composeImageHandler)
api.router.GET("/api/v:version/compose/metadata/:uuid", api.composeMetadataHandler)
api.router.GET("/api/v:version/compose/results/:uuid", api.composeResultsHandler)
api.router.GET("/api/v:version/compose/logs/:uuid", api.composeLogsHandler)
api.router.GET("/api/v:version/compose/log/:uuid", api.composeLogHandler)
api.router.POST("/api/v:version/compose/uploads/schedule/:uuid", api.uploadsScheduleHandler)
api.router.DELETE("/api/v:version/compose/cancel/:uuid", api.composeCancelHandler)
api.router.DELETE("/api/v:version/upload/delete/:uuid", api.uploadsDeleteHandler)
api.router.GET("/api/v:version/upload/info/:uuid", api.uploadsInfoHandler)
api.router.GET("/api/v:version/upload/log/:uuid", api.uploadsLogHandler)
api.router.POST("/api/v:version/upload/reset/:uuid", api.uploadsResetHandler)
api.router.DELETE("/api/v:version/upload/cancel/:uuid", api.uploadsCancelHandler)
api.router.GET("/api/v:version/upload/providers", api.providersHandler)
api.router.POST("/api/v:version/upload/providers/save", api.providersSaveHandler)
api.router.DELETE("/api/v:version/upload/providers/delete/:provider/:profile", api.providersDeleteHandler)
api.router.GET("/api/v:version/distros/list", api.distrosListHandler)
return api
}
func (api *API) Serve(listener net.Listener) error {
api.server = http.Server{
Handler: api,
ReadHeaderTimeout: 5 * time.Second,
}
err := api.server.Serve(listener)
if err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
func (api *API) Shutdown(ctx context.Context) error {
return api.server.Shutdown(ctx)
}
func (api *API) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if api.logger != nil {
log.Println(request.Method, request.URL.Path)
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
api.router.ServeHTTP(writer, request)
}
// PreloadMetadata loads the metadata for all supported distros
// This starts a background depsolve for all known distros in order to preload the
// metadata.
func (api *API) PreloadMetadata() {
log.Printf("Starting metadata preload goroutines")
for _, distro := range api.validDistros(api.hostArch) {
go func(distro string) {
startTime := time.Now()
d := api.getDistro(distro, api.hostArch)
if d == nil {
log.Printf("GetDistro - unknown distribution: %s", distro)
return
}
repos, err := api.allRepositories(distro, api.hostArch)
if err != nil {
log.Printf("Error getting repositories for distro %s: %s", distro, err)
return
}
solver := api.solver.NewWithConfig(d.ModulePlatformID(), d.Releasever(), api.hostArch, d.Name())
_, _, err = solver.Depsolve([]rpmmd.PackageSet{{Include: []string{"filesystem"}, Repositories: repos}})
if err != nil {
log.Printf("Problem preloading distro metadata for %s: %s", distro, err)
}
log.Printf("Finished preload of %s in %v", distro, time.Since(startTime))
}(distro)
}
}
type composeStatus struct {
State ComposeState
Queued time.Time
Started time.Time
Finished time.Time
Result *osbuild.Result
}
func composeStateFromJobStatus(js *worker.JobStatus, result *worker.OSBuildJobResult) ComposeState {
if js.Canceled {
return ComposeFailed
}
if js.Started.IsZero() {
return ComposeWaiting
}
if js.Finished.IsZero() {
return ComposeRunning
}
if result.Success {
return ComposeFinished
}
return ComposeFailed
}
// Returns the state of the image in `compose` and the times the job was
// queued, started, and finished. Assumes that there's only one image in the
// compose.
func (api *API) getComposeStatus(compose store.Compose) (*composeStatus, error) {
jobId := compose.ImageBuild.JobID
// backwards compatibility: composes that were around before splitting
// the job queue from the store still contain their valid status and
// times. Return those here as a fallback.
if jobId == uuid.Nil {
var state ComposeState
switch compose.ImageBuild.QueueStatus {
case common.IBWaiting:
state = ComposeWaiting
case common.IBRunning:
state = ComposeRunning
case common.IBFinished:
state = ComposeFinished
case common.IBFailed:
state = ComposeFailed
}
return &composeStatus{
State: state,
Queued: compose.ImageBuild.JobCreated,
Started: compose.ImageBuild.JobStarted,
Finished: compose.ImageBuild.JobFinished,
Result: &osbuild.Result{},
}, nil
}
// All jobs are "osbuild" jobs.
var result worker.OSBuildJobResult
jobInfo, err := api.workers.OSBuildJobInfo(jobId, &result)
if err != nil {
return nil, err
}
return &composeStatus{
State: composeStateFromJobStatus(jobInfo.JobStatus, &result),
Queued: jobInfo.JobStatus.Queued,
Started: jobInfo.JobStatus.Started,
Finished: jobInfo.JobStatus.Finished,
Result: result.OSBuildOutput,
}, nil
}
// Opens the image file for `compose`. This asks the worker server for the
// artifact first, and then falls back to looking in
// `{outputs}/{composeId}/{imageBuildId}` for backwards compatibility.
func (api *API) openImageFile(composeId uuid.UUID, compose store.Compose) (io.Reader, int64, error) {
name := compose.ImageBuild.ImageType.Filename()
reader, size, err := api.workers.JobArtifact(compose.ImageBuild.JobID, name)
if err != nil {
if api.compatOutputDir == "" || err != jobqueue.ErrNotExist {
return nil, 0, err
}
p := path.Join(api.compatOutputDir, composeId.String(), "0", name)
f, err := os.Open(p)
if err != nil {
return nil, 0, err
}
info, err := f.Stat()
if err != nil {
return nil, 0, err
}
reader = f
size = info.Size()
}
return reader, size, nil
}
// isImageTypeAllowed checks the given ImageType and Distro names against
// the distro-specific ImageType Denylist provided to the API from configuration.
// If the given ImageType is not allowed the method returns an `false`.
// Otherwise `true` is returned.
func (api *API) isImageTypeAllowed(distroName, imageType string) (bool, error) {
for deniedDistro, deniedImgTypes := range api.distrosImageTypeDenylist {
deniedDistroPattern, err := glob.Compile(deniedDistro)
if err != nil {
// the bool return value here does not have any real meaning
return true, err
}
if deniedDistroPattern.Match(distroName) {
for _, deniedImgType := range deniedImgTypes {
deniedImageTypePattern, err := glob.Compile(deniedImgType)
if err != nil {
// the bool return value here does not have any real meaning
return true, err
}
if deniedImageTypePattern.Match(imageType) {
return false, nil
}
}
}
}
return true, nil
}
// getImageType returns the ImageType for the selected distro
// This is necessary because different distros support different image types, and the image
// type may have a different package set than other distros.
func (api *API) getImageType(distroName, imageType, archName string) (distro.ImageType, error) {
imgAllowed, err := api.isImageTypeAllowed(distroName, imageType)
if err != nil {
return nil, fmt.Errorf("error while checking if image type is allowed: %v", err)
}
if !imgAllowed {
return nil, fmt.Errorf("image type %q for distro %q is denied by configuration", imageType, distroName)
}
distro := api.getDistro(distroName, archName)
if distro == nil {
return nil, fmt.Errorf("GetDistro - unknown distribution: %s", distroName)
}
arch, err := distro.GetArch(archName)
if err != nil {
return nil, err
}
return arch.GetImageType(imageType)
}
func (api *API) parseDistro(query url.Values, arch string) (string, error) {
if distro := query.Get("distro"); distro != "" {
if common.IsStringInSortedSlice(api.validDistros(arch), distro) {
return distro, nil
}
return "", errors_package.New("Invalid distro: " + distro)
}
return api.hostDistroName, nil
}
// getDistro returns the named distro or nil
// It excludes unsupported distros by first checking the api.distros list
func (api *API) getDistro(name, arch string) distro.Distro {
if !common.IsStringInSortedSlice(api.validDistros(arch), name) {
return nil
}
return api.distroFactory.GetDistro(name)
}
func verifyRequestVersion(writer http.ResponseWriter, params httprouter.Params, minVersion uint) bool {
versionString := params.ByName("version")
version, err := strconv.ParseUint(versionString, 10, 0)
var MaxApiVersion uint = 1
if err != nil || uint(version) < minVersion || uint(version) > MaxApiVersion {
notFoundHandler(writer, nil)
return false
}
return true
}
func isRequestVersionAtLeast(params httprouter.Params, minVersion uint) bool {
versionString := params.ByName("version")
version, err := strconv.ParseUint(versionString, 10, 0)
common.PanicOnError(err)
return uint(version) >= minVersion
}
func methodNotAllowedHandler(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusMethodNotAllowed)
}
func notFoundHandler(writer http.ResponseWriter, request *http.Request) {
errors := responseError{
Code: http.StatusNotFound,
ID: "HTTPError",
Msg: "Not Found",
}
statusResponseError(writer, http.StatusNotFound, errors)
}
func notImplementedHandler(writer http.ResponseWriter, httpRequest *http.Request, _ httprouter.Params) {
writer.WriteHeader(http.StatusNotImplemented)
}
func statusResponseOK(writer http.ResponseWriter) {
type reply struct {
Status bool `json:"status"`
}
writer.WriteHeader(http.StatusOK)
err := json.NewEncoder(writer).Encode(reply{true})
common.PanicOnError(err)
}
type responseError struct {
Code int `json:"code,omitempty"`
ID string `json:"id"`
Msg string `json:"msg"`
}
// verifyStringsWithRegex checks a slice of strings against a regex of allowed characters
// it writes the InvalidChars error to the writer and returns false if any of them fail the check
// It will also return an error if the string is empty
func verifyStringsWithRegex(writer http.ResponseWriter, strings []string, re *regexp.Regexp) bool {
for _, s := range strings {
if len(s) > 0 && re.MatchString(s) {
continue
}
errors := responseError{
ID: "InvalidChars",
Msg: "Invalid characters in API path",
}
statusResponseError(writer, http.StatusBadRequest, errors)
return false
}
return true
}
func statusResponseError(writer http.ResponseWriter, code int, errors ...responseError) {
type reply struct {
Status bool `json:"status"`
Errors []responseError `json:"errors,omitempty"`
}
writer.WriteHeader(code)
err := json.NewEncoder(writer).Encode(reply{false, errors})
common.PanicOnError(err)
}
func (api *API) statusHandler(writer http.ResponseWriter, request *http.Request, _ httprouter.Params) {
type reply struct {
API string `json:"api"`
DBSupported bool `json:"db_supported"`
DBVersion string `json:"db_version"`
SchemaVersion string `json:"schema_version"`
Backend string `json:"backend"`
Build string `json:"build"`
Messages []string `json:"msgs"`
}
err := json.NewEncoder(writer).Encode(reply{
API: "1",
DBSupported: true,
DBVersion: "0",
SchemaVersion: "0",
Backend: "osbuild-composer",
Build: common.BuildVersion(),
Messages: make([]string, 0),
})
common.PanicOnError(err)
}
func (api *API) sourceListHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
if !verifyRequestVersion(writer, params, 0) {
return
}
type reply struct {
Sources []string `json:"sources"`
}
// The v0 API used the repo Name, a descriptive string, as the key
// In the v1 API this was changed to separate the Name and the Id (a short identifier)
var names []string
if isRequestVersionAtLeast(params, 1) {
names = api.store.ListSourcesById()
} else {
names = api.store.ListSourcesByName()
}
names = append(names, api.systemRepoNames()...)
err := json.NewEncoder(writer).Encode(reply{
Sources: names,
})
common.PanicOnError(err)
}
func (api *API) sourceEmptyInfoHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
if !verifyRequestVersion(writer, params, 0) {
return
}
errors := responseError{
Code: http.StatusNotFound,
ID: "HTTPError",
Msg: "Not Found",
}
statusResponseError(writer, http.StatusNotFound, errors)
}
// getSourceConfigs retrieves the list of sources from the system repos an store
// Returning a list of store.SourceConfig entries indexed by the id of the source
func (api *API) getSourceConfigs(params httprouter.Params) (map[string]store.SourceConfig, []responseError) {
names := params.ByName("sources")
sources := map[string]store.SourceConfig{}
errors := []responseError{}
repos, err := api.repoRegistry.ReposByArchName(api.hostDistroName, api.hostArch, false)
if err != nil {
error := responseError{
ID: "InternalError",
Msg: fmt.Sprintf("error while getting system repos: %v", err),
}
errors = append(errors, error)
}
// if names is "*" we want all sources
if names == "*" {
sources = api.store.GetAllSourcesByID()
for _, repo := range repos {
sources[repo.Name] = store.NewSourceConfig(repo, true)
}
} else {
for _, name := range strings.Split(names, ",") {
// check if the source is one of the base repos
found := false
for _, repo := range repos {
if name == repo.Name {
sources[repo.Name] = store.NewSourceConfig(repo, true)
found = true
break
}
}
if found {
continue
}
// check if the source is in the store
if source := api.store.GetSource(name); source != nil {
sources[name] = *source
} else {
error := responseError{
ID: "UnknownSource",
Msg: fmt.Sprintf("%s is not a valid source", name),
}
errors = append(errors, error)
}
}
}
return sources, errors
}
// sourceInfoHandler routes the call to the correct API version handler
func (api *API) sourceInfoHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
versionString := params.ByName("version")
version, err := strconv.ParseUint(versionString, 10, 0)
if err != nil {
notFoundHandler(writer, nil)
return
}
switch version {
case 0:
api.sourceInfoHandlerV0(writer, request, params)
case 1:
api.sourceInfoHandlerV1(writer, request, params)
default:
notFoundHandler(writer, nil)
}
}
// sourceInfoHandlerV0 handles the API v0 response
func (api *API) sourceInfoHandlerV0(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
sources, errors := api.getSourceConfigs(params)
// V0 responses use the source name as the key
v0Sources := make(map[string]SourceConfigV0, len(sources))
for _, s := range sources {
v0Sources[s.Name] = NewSourceConfigV0(s)
}
q, err := url.ParseQuery(request.URL.RawQuery)
if err != nil {
errors := responseError{
ID: "InvalidChars",
Msg: fmt.Sprintf("invalid query string: %v", err),
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
format := q.Get("format")
if format == "json" || format == "" {
err := json.NewEncoder(writer).Encode(SourceInfoResponseV0{
Sources: v0Sources,
Errors: errors,
})
common.PanicOnError(err)
} else if format == "toml" {
encoder := toml.NewEncoder(writer)
encoder.Indent = ""
err := encoder.Encode(sources)
common.PanicOnError(err)
} else {
errors := responseError{
ID: "InvalidChars",
Msg: fmt.Sprintf("invalid format parameter: %s", format),
}
statusResponseError(writer, http.StatusBadRequest, errors)
}
}
// sourceInfoHandlerV1 handles the API v0 response
func (api *API) sourceInfoHandlerV1(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
sources, errors := api.getSourceConfigs(params)
// V1 responses use the source id as the key
v1Sources := make(map[string]SourceConfigV1, len(sources))
for id, s := range sources {
v1Sources[id] = NewSourceConfigV1(id, s)
}
q, err := url.ParseQuery(request.URL.RawQuery)
if err != nil {
errors := responseError{
ID: "InvalidChars",
Msg: fmt.Sprintf("invalid query string: %v", err),
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
format := q.Get("format")
if format == "json" || format == "" {
err := json.NewEncoder(writer).Encode(SourceInfoResponseV1{
Sources: v1Sources,
Errors: errors,
})
common.PanicOnError(err)
} else if format == "toml" {
encoder := toml.NewEncoder(writer)
encoder.Indent = ""
err := encoder.Encode(sources)
common.PanicOnError(err)
} else {
errors := responseError{
ID: "InvalidChars",
Msg: fmt.Sprintf("invalid format parameter: %s", format),
}
statusResponseError(writer, http.StatusBadRequest, errors)
}
}
// DecodeSourceConfigV0 parses a request.Body into a SourceConfigV0
func DecodeSourceConfigV0(body io.Reader, contentType string) (source SourceConfigV0, err error) {
if contentType == "application/json" {
err = json.NewDecoder(body).Decode(&source)
} else if contentType == "text/x-toml" {
// Read all of body in case it needs to be parsed twice
var data []byte
data, err = io.ReadAll(body)
if err != nil {
return source, err
}
// First try to parse [ID]\n...SOURCE... form
var srcMap map[string]SourceConfigV0
err = toml.Unmarshal(data, &srcMap)
if err != nil {
// Failed, parse it again without [ID] mapping
err = toml.Unmarshal(data, &source)
} else {
// It is possible more than 1 source could be posted. We only use the first, after sorting
keys := make([]string, 0, len(srcMap))
for k := range srcMap {
keys = append(keys, k)
}
sort.Strings(keys)
source = srcMap[keys[0]]
}
} else {
err = errors_package.New("blueprint must be in json or toml format")
}
return source, err
}
// DecodeSourceConfigV1 parses a request.Body into a SourceConfigV1
func DecodeSourceConfigV1(body io.Reader, contentType string) (source SourceConfigV1, err error) {
if contentType == "application/json" {
err = json.NewDecoder(body).Decode(&source)
} else if contentType == "text/x-toml" {
// Read all of body in case it needs to be parsed twice
var data []byte
data, err = io.ReadAll(body)
if err != nil {
return source, err
}
// First try to parse [ID]\n...SOURCE... form
var srcMap map[string]SourceConfigV1
err = toml.Unmarshal(data, &srcMap)
if err != nil {
// Failed, parse it without [ID]
err = toml.Unmarshal(data, &source)
} else {
// It is possible more than 1 source could be posted. We only use the first, after sorting
keys := make([]string, 0, len(srcMap))
for k := range srcMap {
keys = append(keys, k)
}
sort.Strings(keys)
source = srcMap[keys[0]]
// If no id was set, use the ID from the map
if len(source.ID) == 0 {
source.ID = keys[0]
}
}
} else {
err = errors_package.New("blueprint must be in json or toml format")
}
if err == nil && len(source.GetKey()) == 0 {
err = errors_package.New("'id' field is missing from request")
}
return source, err
}
func (api *API) sourceNewHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
if !verifyRequestVersion(writer, params, 0) { // TODO: version 1 API
return
}
contentType := request.Header["Content-Type"]
if len(contentType) == 0 {
errors := responseError{
ID: "HTTPError",
Msg: "malformed Content-Type header",
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
if request.ContentLength == 0 {
errors := responseError{
ID: "ProjectsError",
Msg: "Missing source",
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
var source SourceConfig
var err error
if isRequestVersionAtLeast(params, 1) {
source, err = DecodeSourceConfigV1(request.Body, contentType[0])
} else {
source, err = DecodeSourceConfigV0(request.Body, contentType[0])
}
// Basic check of the source, should at least have a name and type
if err == nil {
if len(source.GetName()) == 0 {
err = errors_package.New("'name' field is missing from request")
} else if len(source.GetType()) == 0 {
err = errors_package.New("'type' field is missing from request")
} else if len(source.SourceConfig().URL) == 0 {
err = errors_package.New("'url' field is missing from request")
}
}
if err != nil {
errors := responseError{
ID: "ProjectsError",
Msg: "Problem parsing POST body: " + err.Error(),
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
// If there is a list of distros, check to make sure they are valid
invalid := []string{}
for _, d := range source.SourceConfig().Distros {
if !common.IsStringInSortedSlice(api.validDistros(api.hostArch), d) {
invalid = append(invalid, d)
}
}
if len(invalid) > 0 {
errors := responseError{
ID: "ProjectsError",
Msg: "Invalid distributions: " + strings.Join(invalid, ","),
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
// Is there an existing System Repo using this id?
for _, n := range api.systemRepoNames() {
if n == source.GetKey() {
// Users cannot replace system repos
errors := responseError{
ID: "SystemSource",
Msg: fmt.Sprintf("%s is a system source, it cannot be changed.", source.GetKey()),
}
statusResponseError(writer, http.StatusBadRequest, errors)
return
}
}
api.store.PushSource(source.GetKey(), source.SourceConfig())
statusResponseOK(writer)
}
func (api *API) sourceDeleteHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
if !verifyRequestVersion(writer, params, 0) {
return
}
name := strings.Split(params.ByName("source"), ",")
if name[0] == "/" {
errors := responseError{
Code: http.StatusNotFound,
ID: "HTTPError",
Msg: "Not Found",
}
statusResponseError(writer, http.StatusNotFound, errors)
return
}
// Check for system repos and return an error
for _, id := range api.systemRepoNames() {
if id == name[0][1:] {
errors := responseError{
ID: "SystemSource",
Msg: id + " is a system source, it cannot be deleted.",
}
statusResponseError(writer, http.StatusBadRequest, errors)