-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_project.go
1250 lines (1071 loc) · 33.3 KB
/
api_project.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 main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"github.com/gorilla/mux"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/db/cluster"
"github.com/lxc/lxd/lxd/db/operationtype"
"github.com/lxc/lxd/lxd/lifecycle"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/operations"
projecthelpers "github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/rbac"
"github.com/lxc/lxd/lxd/request"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/lxd/state"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/validate"
"github.com/lxc/lxd/shared/version"
)
var projectsCmd = APIEndpoint{
Path: "projects",
Get: APIEndpointAction{Handler: projectsGet, AccessHandler: allowAuthenticated},
Post: APIEndpointAction{Handler: projectsPost},
}
var projectCmd = APIEndpoint{
Path: "projects/{name}",
Delete: APIEndpointAction{Handler: projectDelete},
Get: APIEndpointAction{Handler: projectGet, AccessHandler: allowAuthenticated},
Patch: APIEndpointAction{Handler: projectPatch, AccessHandler: allowAuthenticated},
Post: APIEndpointAction{Handler: projectPost},
Put: APIEndpointAction{Handler: projectPut, AccessHandler: allowAuthenticated},
}
var projectStateCmd = APIEndpoint{
Path: "projects/{name}/state",
Get: APIEndpointAction{Handler: projectStateGet, AccessHandler: allowAuthenticated},
}
// swagger:operation GET /1.0/projects projects projects_get
//
// Get the projects
//
// Returns a list of projects (URLs).
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of endpoints
// items:
// type: string
// example: |-
// [
// "/1.0/projects/default",
// "/1.0/projects/foo"
// ]
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/projects?recursion=1 projects projects_get_recursion1
//
// Get the projects
//
// Returns a list of projects (structs).
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of projects
// items:
// $ref: "#/definitions/Project"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectsGet(d *Daemon, r *http.Request) response.Response {
recursion := util.IsRecursionRequest(r)
var result any
err := d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
projects, err := cluster.GetProjects(ctx, tx.Tx())
if err != nil {
return err
}
filtered := []api.Project{}
for _, project := range projects {
if !rbac.UserHasPermission(r, project.Name, "view") {
continue
}
apiProject, err := project.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
apiProject.UsedBy, err = projectUsedBy(ctx, tx, &project)
if err != nil {
return err
}
filtered = append(filtered, *apiProject)
}
if recursion {
result = filtered
} else {
urls := make([]string, len(filtered))
for i, p := range filtered {
urls[i] = p.URL(version.APIVersion).String()
}
result = urls
}
return nil
})
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, result)
}
// projectUsedBy returns a list of URLs for all instances, images, profiles,
// storage volumes, networks, and acls that use this project.
func projectUsedBy(ctx context.Context, tx *db.ClusterTx, project *cluster.Project) ([]string, error) {
usedBy := []string{}
instances, err := cluster.GetInstances(ctx, tx.Tx(), cluster.InstanceFilter{Project: &project.Name})
if err != nil {
return nil, err
}
profiles, err := cluster.GetProfiles(ctx, tx.Tx(), cluster.ProfileFilter{Project: &project.Name})
if err != nil {
return nil, err
}
images, err := cluster.GetImages(ctx, tx.Tx(), cluster.ImageFilter{Project: &project.Name})
if err != nil {
return nil, err
}
for _, instance := range instances {
apiInstance := api.Instance{Name: instance.Name}
usedBy = append(usedBy, apiInstance.URL(version.APIVersion, project.Name).String())
}
for _, profile := range profiles {
apiProfile := api.Profile{Name: profile.Name}
usedBy = append(usedBy, apiProfile.URL(version.APIVersion, project.Name).String())
}
for _, image := range images {
apiImage := api.Image{Fingerprint: image.Fingerprint}
usedBy = append(usedBy, apiImage.URL(version.APIVersion, project.Name).String())
}
volumes, err := tx.GetStorageVolumeURIs(ctx, project.Name)
if err != nil {
return nil, err
}
networks, err := tx.GetNetworkURIs(ctx, project.ID, project.Name)
if err != nil {
return nil, err
}
acls, err := tx.GetNetworkACLURIs(ctx, project.ID, project.Name)
if err != nil {
return nil, err
}
usedBy = append(usedBy, volumes...)
usedBy = append(usedBy, networks...)
usedBy = append(usedBy, acls...)
return usedBy, nil
}
// swagger:operation POST /1.0/projects projects projects_post
//
// Add a project
//
// Creates a new project.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: project
// description: Project
// required: true
// schema:
// $ref: "#/definitions/ProjectsPost"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectsPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
// Parse the request.
project := api.ProjectsPost{}
// Set default features.
if project.Config == nil {
project.Config = map[string]string{}
}
for featureName, featureInfo := range cluster.ProjectFeatures {
_, ok := project.Config[featureName]
if !ok && featureInfo.DefaultEnabled {
project.Config[featureName] = "true"
}
}
err := json.NewDecoder(r.Body).Decode(&project)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
err = projectValidateName(project.Name)
if err != nil {
return response.BadRequest(err)
}
// Validate the configuration.
err = projectValidateConfig(s, project.Config)
if err != nil {
return response.BadRequest(err)
}
var id int64
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
id, err = cluster.CreateProject(ctx, tx.Tx(), cluster.Project{Description: project.Description, Name: project.Name})
if err != nil {
return fmt.Errorf("Failed adding database record: %w", err)
}
err = cluster.CreateProjectConfig(ctx, tx.Tx(), id, project.Config)
if err != nil {
return fmt.Errorf("Unable to create project config for project %q: %w", project.Name, err)
}
if shared.IsTrue(project.Config["features.profiles"]) {
err = projectCreateDefaultProfile(tx, project.Name)
if err != nil {
return err
}
if project.Config["features.images"] == "false" {
err = cluster.InitProjectWithoutImages(ctx, tx.Tx(), project.Name)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
return response.SmartError(fmt.Errorf("Failed creating project %q: %w", project.Name, err))
}
if d.rbac != nil {
err = d.rbac.AddProject(id, project.Name)
if err != nil {
return response.SmartError(err)
}
}
requestor := request.CreateRequestor(r)
lc := lifecycle.ProjectCreated.Event(project.Name, requestor, nil)
s.Events.SendLifecycle(project.Name, lc)
return response.SyncResponseLocation(true, nil, lc.Source)
}
// Create the default profile of a project.
func projectCreateDefaultProfile(tx *db.ClusterTx, project string) error {
// Create a default profile
profile := cluster.Profile{}
profile.Project = project
profile.Name = projecthelpers.Default
profile.Description = fmt.Sprintf("Default LXD profile for project %s", project)
_, err := cluster.CreateProfile(context.TODO(), tx.Tx(), profile)
if err != nil {
return fmt.Errorf("Add default profile to database: %w", err)
}
return nil
}
// swagger:operation GET /1.0/projects/{name} projects project_get
//
// Get the project
//
// Gets a specific project.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Project
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Project"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectGet(d *Daemon, r *http.Request) response.Response {
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Check user permissions
if !rbac.UserHasPermission(r, name, "view") {
return response.Forbidden(nil)
}
// Get the database entry
var project *api.Project
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
dbProject, err := cluster.GetProject(ctx, tx.Tx(), name)
if err != nil {
return err
}
project, err = dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
project.UsedBy, err = projectUsedBy(ctx, tx, dbProject)
return err
})
if err != nil {
return response.SmartError(err)
}
etag := []any{
project.Description,
project.Config,
}
return response.SyncResponseETag(true, project, etag)
}
// swagger:operation PUT /1.0/projects/{name} projects project_put
//
// Update the project
//
// Updates the entire project configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: project
// description: Project configuration
// required: true
// schema:
// $ref: "#/definitions/ProjectPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func projectPut(d *Daemon, r *http.Request) response.Response {
s := d.State()
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Check user permissions
if !rbac.UserHasPermission(r, name, "manage-projects") {
return response.Forbidden(nil)
}
// Get the current data
var project *api.Project
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
dbProject, err := cluster.GetProject(ctx, tx.Tx(), name)
if err != nil {
return err
}
project, err = dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
project.UsedBy, err = projectUsedBy(ctx, tx, dbProject)
if err != nil {
return err
}
return err
})
if err != nil {
return response.SmartError(err)
}
// Validate ETag
etag := []any{
project.Description,
project.Config,
}
err = util.EtagCheck(r, etag)
if err != nil {
return response.PreconditionFailed(err)
}
// Parse the request
req := api.ProjectPut{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(project.Name, lifecycle.ProjectUpdated.Event(project.Name, requestor, nil))
return projectChange(d, project, req)
}
// swagger:operation PATCH /1.0/projects/{name} projects project_patch
//
// Partially update the project
//
// Updates a subset of the project configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: project
// description: Project configuration
// required: true
// schema:
// $ref: "#/definitions/ProjectPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func projectPatch(d *Daemon, r *http.Request) response.Response {
s := d.State()
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Check user permissions
if !rbac.UserHasPermission(r, name, "manage-projects") {
return response.Forbidden(nil)
}
// Get the current data
var project *api.Project
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
dbProject, err := cluster.GetProject(ctx, tx.Tx(), name)
if err != nil {
return err
}
project, err = dbProject.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
project.UsedBy, err = projectUsedBy(ctx, tx, dbProject)
if err != nil {
return err
}
return err
})
if err != nil {
return response.SmartError(err)
}
// Validate ETag
etag := []any{
project.Description,
project.Config,
}
err = util.EtagCheck(r, etag)
if err != nil {
return response.PreconditionFailed(err)
}
body, err := io.ReadAll(r.Body)
if err != nil {
return response.InternalError(err)
}
rdr1 := io.NopCloser(bytes.NewBuffer(body))
rdr2 := io.NopCloser(bytes.NewBuffer(body))
reqRaw := shared.Jmap{}
err = json.NewDecoder(rdr1).Decode(&reqRaw)
if err != nil {
return response.BadRequest(err)
}
req := api.ProjectPut{}
err = json.NewDecoder(rdr2).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Check what was actually set in the query
_, err = reqRaw.GetString("description")
if err != nil {
req.Description = project.Description
}
config, err := reqRaw.GetMap("config")
if err != nil {
req.Config = project.Config
} else {
for k, v := range project.Config {
_, ok := config[k]
if !ok {
config[k] = v
}
}
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(project.Name, lifecycle.ProjectUpdated.Event(project.Name, requestor, nil))
return projectChange(d, project, req)
}
// Common logic between PUT and PATCH.
func projectChange(d *Daemon, project *api.Project, req api.ProjectPut) response.Response {
s := d.State()
// Make a list of config keys that have changed.
configChanged := []string{}
for key := range project.Config {
if req.Config[key] != project.Config[key] {
configChanged = append(configChanged, key)
}
}
for key := range req.Config {
_, ok := project.Config[key]
if !ok {
configChanged = append(configChanged, key)
}
}
// Record which features have been changed.
var featuresChanged []string
for _, configKeyChanged := range configChanged {
_, isFeature := cluster.ProjectFeatures[configKeyChanged]
if isFeature {
featuresChanged = append(featuresChanged, configKeyChanged)
}
}
// Quick checks.
if len(featuresChanged) > 0 {
if project.Name == projecthelpers.Default {
return response.BadRequest(fmt.Errorf("You can't change the features of the default project"))
}
// Consider the project empty if it is only used by the default profile.
usedByLen := len(project.UsedBy)
projectInUse := usedByLen > 1 || (usedByLen == 1 && !strings.Contains(project.UsedBy[0], "/profiles/default"))
if projectInUse {
// Check if feature is allowed to be changed.
for _, featureChanged := range featuresChanged {
// If feature is currently enabled, and it is being changed in the request, it
// must be being disabled. So prevent it on non-empty projects.
if shared.IsTrue(project.Config[featureChanged]) {
return response.BadRequest(fmt.Errorf("Project feature %q cannot be disabled on non-empty projects", featureChanged))
}
// If feature is currently disabled, and it is being changed in the request, it
// must be being enabled. So check if feature can be enabled on non-empty projects.
if shared.IsFalse(project.Config[featureChanged]) && !cluster.ProjectFeatures[featureChanged].CanEnableNonEmpty {
return response.BadRequest(fmt.Errorf("Project feature %q cannot be enabled on non-empty projects", featureChanged))
}
}
}
}
// Validate the configuration.
err := projectValidateConfig(s, req.Config)
if err != nil {
return response.BadRequest(err)
}
// Update the database entry.
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err := projecthelpers.AllowProjectUpdate(tx, project.Name, req.Config, configChanged)
if err != nil {
return err
}
err = cluster.UpdateProject(ctx, tx.Tx(), project.Name, req)
if err != nil {
return fmt.Errorf("Persist profile changes: %w", err)
}
if shared.StringInSlice("features.profiles", configChanged) {
if shared.IsTrue(req.Config["features.profiles"]) {
err = projectCreateDefaultProfile(tx, project.Name)
if err != nil {
return err
}
} else {
// Delete the project-specific default profile.
err = cluster.DeleteProfile(ctx, tx.Tx(), project.Name, projecthelpers.Default)
if err != nil {
return fmt.Errorf("Delete project default profile: %w", err)
}
}
}
if shared.StringInSlice("features.images", configChanged) && shared.IsFalse(req.Config["features.images"]) && shared.IsTrue(req.Config["features.profiles"]) {
err = cluster.InitProjectWithoutImages(ctx, tx.Tx(), project.Name)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return response.SmartError(err)
}
return response.EmptySyncResponse
}
// swagger:operation POST /1.0/projects/{name} projects project_post
//
// Rename the project
//
// Renames an existing project.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: project
// description: Project rename request
// required: true
// schema:
// $ref: "#/definitions/ProjectPost"
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Parse the request.
req := api.ProjectPost{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if name == projecthelpers.Default {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be renamed"))
}
// Perform the rename.
run := func(op *operations.Operation) error {
var id int64
err := d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := cluster.GetProject(ctx, tx.Tx(), req.Name)
if err != nil && !response.IsNotFoundError(err) {
return fmt.Errorf("Failed checking if project %q exists: %w", req.Name, err)
}
if project != nil {
return fmt.Errorf("A project named %q already exists", req.Name)
}
project, err = cluster.GetProject(ctx, tx.Tx(), name)
if err != nil {
return fmt.Errorf("Failed loading project %q: %w", name, err)
}
empty, err := projectIsEmpty(ctx, project, tx)
if err != nil {
return err
}
if !empty {
return fmt.Errorf("Only empty projects can be renamed")
}
id, err = cluster.GetProjectID(ctx, tx.Tx(), name)
if err != nil {
return fmt.Errorf("Failed getting project ID for project %q: %w", name, err)
}
err = projectValidateName(req.Name)
if err != nil {
return err
}
return cluster.RenameProject(ctx, tx.Tx(), name, req.Name)
})
if err != nil {
return err
}
if d.rbac != nil {
err = d.rbac.RenameProject(id, req.Name)
if err != nil {
return err
}
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(req.Name, lifecycle.ProjectRenamed.Event(req.Name, requestor, logger.Ctx{"old_name": name}))
return nil
}
op, err := operations.OperationCreate(s, "", operations.OperationClassTask, operationtype.ProjectRename, nil, nil, run, nil, nil, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
// swagger:operation DELETE /1.0/projects/{name} projects project_delete
//
// Delete the project
//
// Removes the project.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectDelete(d *Daemon, r *http.Request) response.Response {
s := d.State()
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Quick checks.
if name == projecthelpers.Default {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be deleted"))
}
var id int64
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := cluster.GetProject(ctx, tx.Tx(), name)
if err != nil {
return fmt.Errorf("Fetch project %q: %w", name, err)
}
empty, err := projectIsEmpty(ctx, project, tx)
if err != nil {
return err
}
if !empty {
return fmt.Errorf("Only empty projects can be removed")
}
id, err = cluster.GetProjectID(ctx, tx.Tx(), name)
if err != nil {
return fmt.Errorf("Fetch project id %q: %w", name, err)
}
return cluster.DeleteProject(ctx, tx.Tx(), name)
})
if err != nil {
return response.SmartError(err)
}
if d.rbac != nil {
err = d.rbac.DeleteProject(id)
if err != nil {
return response.SmartError(err)
}
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(name, lifecycle.ProjectDeleted.Event(name, requestor, nil))
return response.EmptySyncResponse
}
// swagger:operation GET /1.0/projects/{name}/state projects project_state_get
//
// Get the project state
//
// Gets a specific project resource consumption information.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Project state
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/ProjectState"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func projectStateGet(d *Daemon, r *http.Request) response.Response {
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
// Check user permissions.
if !rbac.UserHasPermission(r, name, "view") {
return response.Forbidden(nil)
}
// Setup the state struct.
state := api.ProjectState{}
// Get current limits and usage.
err = d.db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
result, err := projecthelpers.GetCurrentAllocations(ctx, tx, name)
if err != nil {
return err
}
state.Resources = result
return nil
})
if err != nil {