summaryrefslogtreecommitdiff
path: root/python-odcs.spec
blob: 9247e59b068f25ba937776a5d1d1d8dc356755d2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
%global _empty_manifest_terminate_build 0
Name:		python-odcs
Version:	0.5.0
Release:	1
Summary:	On Demand Compose Service
License:	MIT
URL:		https://pagure.io/odcs/
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/aa/07/c317e85df91a6b22b1585ea2c5c577fdbba08d6ebde42d0e9591a5047b94/odcs-0.5.0.tar.gz
BuildArch:	noarch


%description
# On Demand Compose Service - ODCS

![logo of ODCS](https://pagure.io/odcs/raw/master/f/logo.png)

## What is ODCS

The main goal of ODCS is to allow generation of temporary composes using the REST API calls. By a compose, we mainly mean RPM repository with packages taken from different sources, but in the future, generation of other output types could be possible too.

ODCS can take RPMs for a compose from multiple sources like Koji tag, module built in Koji or external repository provided by Pulp tool.

## Using ODCS - client library

There is client library written in Python which allows easy access to REST API provided by ODCS server.

### Installing the ODCS client

On Fedora:

```
$ sudo dnf install odcs-client
```

If you want to install using `pip`, you can run following:

```
$ sudo pip install odcs[client]
```

In case you want your python project to depend on ODCS client library and add it to your `requirements.txt`, you can just use following to depend on ODCS client:

```
odcs[client]
```

### ODCS authentication system

ODCS server can be configured to authenticate using OpenIDC, Kerberos or SSL. Eventually it can be set in NoAuth mode to support anonymous access. Depending on the ODCS server configuration, you have to set your authentication method when creating ODCS class instance.

#### Using OpenIDC for authentication

To use OpenIDC, you have to provide the OpenIDC token to ODCS client class constructor. To obtain that OpenIDC token, you can either use `python-openidc-client`, or ask the OpenIDC provider for service token which does not have to be refreshed. Once you have the token, you can create the ODCS instance like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.OpenIDC,
            openidc_token="your_openidc_token")
```

Getting the `openidc_token` using `python-openidc-client` library can be done like this:

```
import openidc_client
staging = False

if staging:
    id_provider = 'https://id.stg.fedoraproject.org/openidc/'
else:
    id_provider = 'https://id.fedoraproject.org/openidc/'

# Get the auth token using the OpenID client.
oidc = openidc_client.OpenIDCClient(
    'odcs',
    id_provider,
    {'Token': 'Token', 'Authorization': 'Authorization'},
    'odcs-authorizer',
    'notsecret',
)

scopes = [
    'openid',
    'https://id.fedoraproject.org/scope/groups',
    'https://pagure.io/odcs/new-compose',
    'https://pagure.io/odcs/renew-compose',
    'https://pagure.io/odcs/delete-compose',
]
try:
    token = oidc.get_token(scopes, new_token=True)
    token = oidc.report_token_issue()
except requests.exceptions.HTTPError as e:
    print(e.response.text)
    raise
```

#### Using Kerberos for authentication

To use Kerberos, you have to have valid Kerberos ticket or you need to have the Kerberos keytab file. If you want to use ODCS client library with Kerberos keytab, you have to set the `KRB5_CLIENT_KTNAME` environment variable to full path to the keytab file you want to use. You can for example do it like this:

```
from odcs.client.odcs import ODCS, AuthMech
from os import environ
environ["KRB5_CLIENT_KTNAME"] = "/full/path/to/ketab"

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.Kerberos)
```

#### Using SSL for authentication

To use SSL, you have to have SSL client certificate and key files. You then have to choose SSL AuthMech and pass the paths to SSL client certificate and key like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.SSL,
            ssl_cert="/path/to/ssl-crt.pem",
            ssl_key="/path/to/ssl-key.pem")
```

### Requesting new compose

The general way how to request new ODCS compose is following:

```
compose = odcs.new_compose(sources, source_type)
```

Both `sources` and `source_type` are strings. Depending on `source_type` value, the `sources` have following meaning:

| `source_type` | `source` |
|---------------|----------|
| tag           | Name of Koji tag to take RPMs from. |
| module        | White-space separated NAME:STREAM or NAME:STREAM:VERSION of modules to include in compose. |
| pulp          | White-space separated list of content-sets or repository ids. Repositories will be included in a compose. |
| raw_config    | String in `name#commit` hash format. The `name` must match one of the raw config locations defined in ODCS server config as `raw_config_urls`. The `commit` is commit hash defining the version of raw config to use. This config is then used as input config for Pungi. |
| build         | Source should be omitted in the request. The list of Koji builds included in a compose is defined by `builds` attribute. |
| pungi_compose | URL to variant repository of external compose generated by the Pungi. For example https://kojipkgs.fedoraproject.org/compose/rawhide/latest-Fedora-Rawhide/compose/Server/. The generated compose will contain the same set of RPMs as the given external compose variant. The packages will be taken from the configured Koji instance. |

There are also additional optional attributes you can pass to `new_compose(...)` method:

- `seconds_to_live` - Number of seconds after which the generated compose should expire and will be removed.
- `packages` - List of packages which should be included in a compose. This is used only when `source_type` is set to `tag` or `build` to further limit the compose repository.
If the `packages` is not set, all packages in Koji tag or all packages in a `builds` list will be included in a final compose.
- `flags` - List of flags to further modify the compose output:
    - `no_deps` - For `tag` `source_type`, do not resolve dependencies between packages and include only packages listed in the `packages` in the compose. For `module` `source_type`, do not resolve dependencies between modules and include only the requested module in the compose.
    - `include_unpublished_pulp_repos` - For `pulp` `source_type`, include also unpublished repositories for input content-sets.
    - `check_deps` - When set, abort the compose when some package has broken dependencies.
    - `no_reuse` - When set, do not try to reuse old compose.
    - `ignore_absent_pulp_repos` - For `pulp` `source_type`, ignore any content set that does not exist in Pulp
    - `use_only_compatible_arch` - For `pulp` `source_type` only. When this flag is set, architecture hardcoded in URL returned from Pulp will be replaced with `$basearch` variable. The repository definition will also define `skip_if_unavailable = 1`. This could be useful when multiple content sets are included in the repofile to completly ignore packages from repositories for incompatible architectures.
- `sigkeys` - List of signature keys IDs. Only packages signed by one of these keys will be included in a compose. If there is no signed version of a package, compose will fail. It is also possible to pass an empty-string in a list meaning unsigned packages are allowed. For example if you want to prefer packages signed by key with ID `123` and also allow unsigned packages to appear in a compose, you can do it by setting sigkeys to `["123", ""]`.
- `results` - List of additional results which will be generated as part of a compose. Valid keys are:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `boot.iso` - Generates `images/boot.iso` file which is needed to build base container images from resulting compose.
- `arches` - List of additional Koji arches to build this compose for. By default, the compose is built only for "x86_64" arch.
- `multilib_arches` - Subset of `arches` for which the multilib should be enabled. For each architecture in the `multilib_arches` list, ODCS will include also packages from other compatible architectures in a compose. For example when "x86_64" is included `multilib_arches`, ODCS will include also "i686" packages in a compose. The set of packages included in a composes is influenced by `multilib_method` list.
- `multilib_method` - List defining the method used to determine whether consider package as multilib. Defaults to empty list. The list can have following values:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `runtime` - Packages whose name ends with "-devel" or "-static" suffix will be considered as multilib.
    - `devel` - Packages that install some shared object file "*.so.*" will be considered as multilib.
    - `all` - All pakages will be considered as multilib.
- `builds` - List of NVRs defining the Koji builds to include in a compose. Only valid for `tag` and `build` source types. For `tag` source type, the NVRs will be considered
for inclusion in a compose on top of Koji tag defined by `source`. For `build` source type, only the Koji builds defined by the NVRs will be considered for inclusion. The `packages` still need to be set to include particular packages from the Koji builds in a compose.
- `lookaside_repos` - List of URLs pointing to RPM repositories with packages which will be used by internal dependency resolver to resolve dependencies. Packages from these repositories will not appear in the resulting ODCS compose, but they are considered while checking whether the RPM dependencies are satisfied in the resulting compose when `check_deps` ODCS flag.
- `module_defaults_url` - List with URL to git repository with Module defaults data and the branch name or commit hash. For example ["https://pagure.io/releng/fedora-module-defaults.git", "master"]. This is used only when creating modular compose including non-modular RPMs.
- `modular_koji_tags` - List of Koji tags in which the modular Koji Content Generator builds are tagged. Such builds will be included in a compose.

The `new_compose` method returns `dict` object describing the compose, for example:

```
{
    "arches": "x86_64 ppc64",
    "flags": [
        "no_deps"
    ],
    "id": 1,
    "owner": "jkaluza",
    "packages": "gofer-package",
    "removed_by": null,
    "result_repo": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary",
    "result_repofile": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary/odcs-1.repo",
    "results": [
        "repository"
    ],
    "sigkeys": "",
    "source": "f26",
    "source_type": 1,
    "state": 3,
    "state_name": "wait",
    "time_done": "2017-10-13T17:03:13Z",
    "time_removed": "2017-10-14T17:00:00Z",
    "time_submitted": "2017-10-13T16:59:51Z",
    "time_to_expire": "2017-10-14T16:59:51Z"
}
```

The most useful data there is `result_repofile`, which points to the .repo file with URLs for generated compose. Another very important data there is the `state` and `state_name` field. There are following states of a compose:

| `state` | `state_name` | Description |
|---------|--------------|-------------|
| 0       | wait         | Compose is waiting in a queue to be generated |
| 1       | generating   | Compose is being generated |
| 2       | done         | Compose is generated - done |
| 3       | removed      | Compose has expired and is removed |
| 4       | failed       | Compose generation has failed |

As you can see in our example, compose is in `wait` state and therefore we have to wait until the ODCS generates the compose.

### Waiting until the compose is generated

There are two ways how to wait for the compose generation. The preferred one is listening on Fedora messaging bus for `odcs.state.change` message with `done` or `failed` state and another one is using HTTP polling implemented in `wait_for_compose(...)` method.

If your application does not allow listening on the bus for some reason, you can use `wait_for_compose(...)` method like this:

```
compose = odcs.new_compose(sources, source_type)

# Blocks until the compose is ready, but maximally for 600 seconds.
compose = odcs.wait_for_compose(compose["id"], timeout=600)

if compose["state_name"] == "done":
    print "Compose done, URL with repo file", compose["result_repofile"]
else:
    print "Failed to generate compose"
```

### Checking the state of existing ODCS compose

Once you have the compose ready, you might want to check its state later. This can be done using the `get_compose(...)` method like this:

```
compose = odcs.get_compose(compose["id"])
```

### Renewing the compose

If the `time_to_expire` for your compose is getting closer and you know you want to continue using the compose, you can increase the `time_to_expire` using the `renew_compose(...)` method. You can also use this method to regenerate an expired compose in the `removed` state. Such compose will have the same versions of packages as the original compose.

```
compose = odcs.renew_compose(compose["id"])
```

## Development

### Code Convention

The code must be well formatted via ``black`` and pass ``flake8`` checking.

Run ``tox -e black,flake8`` to do the check.

### Unit-testing

Install packages required by pip to compile some python packages:

```
$ sudo dnf install -y gcc swig redhat-rpm-config python-devel openssl-devel openldap-devel \
    zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel tk-devel \
    git python3-cairo-devel cairo-gobject-devel gobject-introspection-devel
```

A lot of these dependencies come from the module
[pygobject](https://pygobject.readthedocs.io/en/latest/devguide/dev_environ.html#fedora-dep).

Run the tests:

```
$ make check
```

### Testing local composes from plain RPM repositories

You can test ODCS by generating compose from the `./server/tests/repo` repository using following commands:

```
$ ./create_sqlite_db
$ ./start_odcs_from_here
```

Before executing the command `start_odcs_from_here`, a messaging broker supporting AMQP protocol is required to run locally as well in order to run asynchronous tasks to generate composes. Here is an example to run a RabbitMQ broker:

```
sudo dnf install -y rabbitmq-server
sudo systemctl start rabbitmq-server
```

Add the `repo` source type to the server configuration in `./server/odcs/server/config.py`. (This will cause some tests to fail, so it needs to be reverted back after you are done with your changes!)

And in another terminal, submit a request to frontend:

```
$ ./submit_test_compose repo `pwd`/server/tests/repo ed
{
  "id": 1,
  "owner": "Unknown",
  "result_repo": null,
  "source": "/home/hanzz/code/fedora-modularization/odcs/tests/repo",
  "source_type": 3,
  "state": 0,
  "state_name": "wait",
  "time_done": null,
  "time_removed": null,
  "time_submitted": "2017-06-12T14:18:19Z"
}
```

You should then see the backend process generating the compose and once it's done, the resulting compose in `./test_composes/latest-Unknown-1/compose/Temporary` directory.

### Using docker-compose for creating a local setup

You can create test setup for ODCS with the docker-compose file. This yaml file creates docker container for the backend and frontend setup of ODCS and run multiple services together. These services are;

* **rabbitmq** (Handles the communication between backend and frontend)
* **postgres** (Creates the database where the localy generated composes are stored)
* **backend** (Backend service of ODCS)
* **frontend** (Frontend service of ODCS that handles the REST API)
* **static** (Apache service for making storage available)
* **beat** (Cronjob for backend to check the service status)

In addition to these, there are also three docker volumes (`odcs_odcs-composes`, `odcs_odcs-postgres` and `odcs_rabbitmq`) are created. These are providing persistent storage for the services.

This yaml file requires also an **.env** file that specified some enviroment variables for the configuration of frontend and backend. Such an **.env** file should be in the same path with the **docker-compose.yml** file and here are the necessary variables that need to be specified in this file;
```
# Pyhton path
PYTHONPATH=/src/common:/src/server:/src/client

# POSTGRES
POSTGRES_USER=odcs
POSTGRES_PASSWORD=password

# PULP CONFIGURATION
PULP_SERVER_URL=<URL of the pulp server>
PULP_USERNAME=<Username for the pulp server>
PULP_PASSWORD=<Credentials for the pulp server>
RAW_CONFIG_URLS=<Raw config settings in JSON format>

# ODCS CONFIGURATION
ODCS_CONFIG_SECTION=DevConfiguration
ODCS_CONFIG_FILE=/src/server/conf/config.py
ODCS_CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/
ODCS_DB_URL=postgresql+psycopg2://odcs:password@postgres/odcs
# Directory where the generated composes are stored. This hast to match
# location where odcs-composes volume is mounted in frontend and backend
# containers.
ODCS_TARGET_DIR=/mnt/odcs
TARGET_DIR_URL=http://localhost:8080

# FLASK SETTINGS
# Force flask to reload application on change of source files.
FLASK_ENV=development
```

The services can be start with `sudo docker-compose up` command. If you have face an error or something that does not work correctly please use the following steps;

1. Check whether there is already created docker volume.


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME


    If the output is like above, it means there isn't any volume yet and it is sufficient to run `sudo docker-compose up` and then `sudo docker-compose down` command. This creates the volumes and if you run the above command again the output becomes as follows;


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME
        local       odcs_odcs-composes
        local       odcs_odcs-postgres
        local       odcs_odcs-rabbitmq


2. After this point we need to set the correct permission to `ocds_odcs-composes` volume. In order to find where is the actual location of the volume type the following


        $ sudo docker volume inspect odcs_odcs-composes
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        [
            {
                "Name": "odcs_odcs-composes",
                "Driver": "local",
                "Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data",
                "CreatedAt": "2021-10-04T13:19:36.478636851+02:00",
                "Labels": {
                    "io.podman.compose.project": "odcs"
                },
                "Scope": "local",
                "Options": {}
            }
        ]

    `"Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data"` shows the exact location of the corresponding volume.

    Add group write permission to the Mountpoint by


        $ sudo chmod 775 /var/lib/containers/storage/volumes/odcs_odcs-composes/_data


3. In this step it is sufficient to run `sudo docker-compose up` command to start the services properly.

Here are some REST calls for checking the ODCS.

* `$ curl -s http://localhost:5000/api/1/composes/ | jq .` This call shows all the composes in db.
* `$ odcs --server http://localhost:5000/ create-pulp <Pulp content set>` This call starts a pulp compose that match the given pulp content set
* `$ odcs --server http://localhost:5000/ create-raw-config --compose-type test my_raw_config master` This call starts a compose with the configuration defined as my_raw_config


%package -n python3-odcs
Summary:	On Demand Compose Service
Provides:	python-odcs
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-odcs
# On Demand Compose Service - ODCS

![logo of ODCS](https://pagure.io/odcs/raw/master/f/logo.png)

## What is ODCS

The main goal of ODCS is to allow generation of temporary composes using the REST API calls. By a compose, we mainly mean RPM repository with packages taken from different sources, but in the future, generation of other output types could be possible too.

ODCS can take RPMs for a compose from multiple sources like Koji tag, module built in Koji or external repository provided by Pulp tool.

## Using ODCS - client library

There is client library written in Python which allows easy access to REST API provided by ODCS server.

### Installing the ODCS client

On Fedora:

```
$ sudo dnf install odcs-client
```

If you want to install using `pip`, you can run following:

```
$ sudo pip install odcs[client]
```

In case you want your python project to depend on ODCS client library and add it to your `requirements.txt`, you can just use following to depend on ODCS client:

```
odcs[client]
```

### ODCS authentication system

ODCS server can be configured to authenticate using OpenIDC, Kerberos or SSL. Eventually it can be set in NoAuth mode to support anonymous access. Depending on the ODCS server configuration, you have to set your authentication method when creating ODCS class instance.

#### Using OpenIDC for authentication

To use OpenIDC, you have to provide the OpenIDC token to ODCS client class constructor. To obtain that OpenIDC token, you can either use `python-openidc-client`, or ask the OpenIDC provider for service token which does not have to be refreshed. Once you have the token, you can create the ODCS instance like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.OpenIDC,
            openidc_token="your_openidc_token")
```

Getting the `openidc_token` using `python-openidc-client` library can be done like this:

```
import openidc_client
staging = False

if staging:
    id_provider = 'https://id.stg.fedoraproject.org/openidc/'
else:
    id_provider = 'https://id.fedoraproject.org/openidc/'

# Get the auth token using the OpenID client.
oidc = openidc_client.OpenIDCClient(
    'odcs',
    id_provider,
    {'Token': 'Token', 'Authorization': 'Authorization'},
    'odcs-authorizer',
    'notsecret',
)

scopes = [
    'openid',
    'https://id.fedoraproject.org/scope/groups',
    'https://pagure.io/odcs/new-compose',
    'https://pagure.io/odcs/renew-compose',
    'https://pagure.io/odcs/delete-compose',
]
try:
    token = oidc.get_token(scopes, new_token=True)
    token = oidc.report_token_issue()
except requests.exceptions.HTTPError as e:
    print(e.response.text)
    raise
```

#### Using Kerberos for authentication

To use Kerberos, you have to have valid Kerberos ticket or you need to have the Kerberos keytab file. If you want to use ODCS client library with Kerberos keytab, you have to set the `KRB5_CLIENT_KTNAME` environment variable to full path to the keytab file you want to use. You can for example do it like this:

```
from odcs.client.odcs import ODCS, AuthMech
from os import environ
environ["KRB5_CLIENT_KTNAME"] = "/full/path/to/ketab"

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.Kerberos)
```

#### Using SSL for authentication

To use SSL, you have to have SSL client certificate and key files. You then have to choose SSL AuthMech and pass the paths to SSL client certificate and key like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.SSL,
            ssl_cert="/path/to/ssl-crt.pem",
            ssl_key="/path/to/ssl-key.pem")
```

### Requesting new compose

The general way how to request new ODCS compose is following:

```
compose = odcs.new_compose(sources, source_type)
```

Both `sources` and `source_type` are strings. Depending on `source_type` value, the `sources` have following meaning:

| `source_type` | `source` |
|---------------|----------|
| tag           | Name of Koji tag to take RPMs from. |
| module        | White-space separated NAME:STREAM or NAME:STREAM:VERSION of modules to include in compose. |
| pulp          | White-space separated list of content-sets or repository ids. Repositories will be included in a compose. |
| raw_config    | String in `name#commit` hash format. The `name` must match one of the raw config locations defined in ODCS server config as `raw_config_urls`. The `commit` is commit hash defining the version of raw config to use. This config is then used as input config for Pungi. |
| build         | Source should be omitted in the request. The list of Koji builds included in a compose is defined by `builds` attribute. |
| pungi_compose | URL to variant repository of external compose generated by the Pungi. For example https://kojipkgs.fedoraproject.org/compose/rawhide/latest-Fedora-Rawhide/compose/Server/. The generated compose will contain the same set of RPMs as the given external compose variant. The packages will be taken from the configured Koji instance. |

There are also additional optional attributes you can pass to `new_compose(...)` method:

- `seconds_to_live` - Number of seconds after which the generated compose should expire and will be removed.
- `packages` - List of packages which should be included in a compose. This is used only when `source_type` is set to `tag` or `build` to further limit the compose repository.
If the `packages` is not set, all packages in Koji tag or all packages in a `builds` list will be included in a final compose.
- `flags` - List of flags to further modify the compose output:
    - `no_deps` - For `tag` `source_type`, do not resolve dependencies between packages and include only packages listed in the `packages` in the compose. For `module` `source_type`, do not resolve dependencies between modules and include only the requested module in the compose.
    - `include_unpublished_pulp_repos` - For `pulp` `source_type`, include also unpublished repositories for input content-sets.
    - `check_deps` - When set, abort the compose when some package has broken dependencies.
    - `no_reuse` - When set, do not try to reuse old compose.
    - `ignore_absent_pulp_repos` - For `pulp` `source_type`, ignore any content set that does not exist in Pulp
    - `use_only_compatible_arch` - For `pulp` `source_type` only. When this flag is set, architecture hardcoded in URL returned from Pulp will be replaced with `$basearch` variable. The repository definition will also define `skip_if_unavailable = 1`. This could be useful when multiple content sets are included in the repofile to completly ignore packages from repositories for incompatible architectures.
- `sigkeys` - List of signature keys IDs. Only packages signed by one of these keys will be included in a compose. If there is no signed version of a package, compose will fail. It is also possible to pass an empty-string in a list meaning unsigned packages are allowed. For example if you want to prefer packages signed by key with ID `123` and also allow unsigned packages to appear in a compose, you can do it by setting sigkeys to `["123", ""]`.
- `results` - List of additional results which will be generated as part of a compose. Valid keys are:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `boot.iso` - Generates `images/boot.iso` file which is needed to build base container images from resulting compose.
- `arches` - List of additional Koji arches to build this compose for. By default, the compose is built only for "x86_64" arch.
- `multilib_arches` - Subset of `arches` for which the multilib should be enabled. For each architecture in the `multilib_arches` list, ODCS will include also packages from other compatible architectures in a compose. For example when "x86_64" is included `multilib_arches`, ODCS will include also "i686" packages in a compose. The set of packages included in a composes is influenced by `multilib_method` list.
- `multilib_method` - List defining the method used to determine whether consider package as multilib. Defaults to empty list. The list can have following values:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `runtime` - Packages whose name ends with "-devel" or "-static" suffix will be considered as multilib.
    - `devel` - Packages that install some shared object file "*.so.*" will be considered as multilib.
    - `all` - All pakages will be considered as multilib.
- `builds` - List of NVRs defining the Koji builds to include in a compose. Only valid for `tag` and `build` source types. For `tag` source type, the NVRs will be considered
for inclusion in a compose on top of Koji tag defined by `source`. For `build` source type, only the Koji builds defined by the NVRs will be considered for inclusion. The `packages` still need to be set to include particular packages from the Koji builds in a compose.
- `lookaside_repos` - List of URLs pointing to RPM repositories with packages which will be used by internal dependency resolver to resolve dependencies. Packages from these repositories will not appear in the resulting ODCS compose, but they are considered while checking whether the RPM dependencies are satisfied in the resulting compose when `check_deps` ODCS flag.
- `module_defaults_url` - List with URL to git repository with Module defaults data and the branch name or commit hash. For example ["https://pagure.io/releng/fedora-module-defaults.git", "master"]. This is used only when creating modular compose including non-modular RPMs.
- `modular_koji_tags` - List of Koji tags in which the modular Koji Content Generator builds are tagged. Such builds will be included in a compose.

The `new_compose` method returns `dict` object describing the compose, for example:

```
{
    "arches": "x86_64 ppc64",
    "flags": [
        "no_deps"
    ],
    "id": 1,
    "owner": "jkaluza",
    "packages": "gofer-package",
    "removed_by": null,
    "result_repo": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary",
    "result_repofile": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary/odcs-1.repo",
    "results": [
        "repository"
    ],
    "sigkeys": "",
    "source": "f26",
    "source_type": 1,
    "state": 3,
    "state_name": "wait",
    "time_done": "2017-10-13T17:03:13Z",
    "time_removed": "2017-10-14T17:00:00Z",
    "time_submitted": "2017-10-13T16:59:51Z",
    "time_to_expire": "2017-10-14T16:59:51Z"
}
```

The most useful data there is `result_repofile`, which points to the .repo file with URLs for generated compose. Another very important data there is the `state` and `state_name` field. There are following states of a compose:

| `state` | `state_name` | Description |
|---------|--------------|-------------|
| 0       | wait         | Compose is waiting in a queue to be generated |
| 1       | generating   | Compose is being generated |
| 2       | done         | Compose is generated - done |
| 3       | removed      | Compose has expired and is removed |
| 4       | failed       | Compose generation has failed |

As you can see in our example, compose is in `wait` state and therefore we have to wait until the ODCS generates the compose.

### Waiting until the compose is generated

There are two ways how to wait for the compose generation. The preferred one is listening on Fedora messaging bus for `odcs.state.change` message with `done` or `failed` state and another one is using HTTP polling implemented in `wait_for_compose(...)` method.

If your application does not allow listening on the bus for some reason, you can use `wait_for_compose(...)` method like this:

```
compose = odcs.new_compose(sources, source_type)

# Blocks until the compose is ready, but maximally for 600 seconds.
compose = odcs.wait_for_compose(compose["id"], timeout=600)

if compose["state_name"] == "done":
    print "Compose done, URL with repo file", compose["result_repofile"]
else:
    print "Failed to generate compose"
```

### Checking the state of existing ODCS compose

Once you have the compose ready, you might want to check its state later. This can be done using the `get_compose(...)` method like this:

```
compose = odcs.get_compose(compose["id"])
```

### Renewing the compose

If the `time_to_expire` for your compose is getting closer and you know you want to continue using the compose, you can increase the `time_to_expire` using the `renew_compose(...)` method. You can also use this method to regenerate an expired compose in the `removed` state. Such compose will have the same versions of packages as the original compose.

```
compose = odcs.renew_compose(compose["id"])
```

## Development

### Code Convention

The code must be well formatted via ``black`` and pass ``flake8`` checking.

Run ``tox -e black,flake8`` to do the check.

### Unit-testing

Install packages required by pip to compile some python packages:

```
$ sudo dnf install -y gcc swig redhat-rpm-config python-devel openssl-devel openldap-devel \
    zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel tk-devel \
    git python3-cairo-devel cairo-gobject-devel gobject-introspection-devel
```

A lot of these dependencies come from the module
[pygobject](https://pygobject.readthedocs.io/en/latest/devguide/dev_environ.html#fedora-dep).

Run the tests:

```
$ make check
```

### Testing local composes from plain RPM repositories

You can test ODCS by generating compose from the `./server/tests/repo` repository using following commands:

```
$ ./create_sqlite_db
$ ./start_odcs_from_here
```

Before executing the command `start_odcs_from_here`, a messaging broker supporting AMQP protocol is required to run locally as well in order to run asynchronous tasks to generate composes. Here is an example to run a RabbitMQ broker:

```
sudo dnf install -y rabbitmq-server
sudo systemctl start rabbitmq-server
```

Add the `repo` source type to the server configuration in `./server/odcs/server/config.py`. (This will cause some tests to fail, so it needs to be reverted back after you are done with your changes!)

And in another terminal, submit a request to frontend:

```
$ ./submit_test_compose repo `pwd`/server/tests/repo ed
{
  "id": 1,
  "owner": "Unknown",
  "result_repo": null,
  "source": "/home/hanzz/code/fedora-modularization/odcs/tests/repo",
  "source_type": 3,
  "state": 0,
  "state_name": "wait",
  "time_done": null,
  "time_removed": null,
  "time_submitted": "2017-06-12T14:18:19Z"
}
```

You should then see the backend process generating the compose and once it's done, the resulting compose in `./test_composes/latest-Unknown-1/compose/Temporary` directory.

### Using docker-compose for creating a local setup

You can create test setup for ODCS with the docker-compose file. This yaml file creates docker container for the backend and frontend setup of ODCS and run multiple services together. These services are;

* **rabbitmq** (Handles the communication between backend and frontend)
* **postgres** (Creates the database where the localy generated composes are stored)
* **backend** (Backend service of ODCS)
* **frontend** (Frontend service of ODCS that handles the REST API)
* **static** (Apache service for making storage available)
* **beat** (Cronjob for backend to check the service status)

In addition to these, there are also three docker volumes (`odcs_odcs-composes`, `odcs_odcs-postgres` and `odcs_rabbitmq`) are created. These are providing persistent storage for the services.

This yaml file requires also an **.env** file that specified some enviroment variables for the configuration of frontend and backend. Such an **.env** file should be in the same path with the **docker-compose.yml** file and here are the necessary variables that need to be specified in this file;
```
# Pyhton path
PYTHONPATH=/src/common:/src/server:/src/client

# POSTGRES
POSTGRES_USER=odcs
POSTGRES_PASSWORD=password

# PULP CONFIGURATION
PULP_SERVER_URL=<URL of the pulp server>
PULP_USERNAME=<Username for the pulp server>
PULP_PASSWORD=<Credentials for the pulp server>
RAW_CONFIG_URLS=<Raw config settings in JSON format>

# ODCS CONFIGURATION
ODCS_CONFIG_SECTION=DevConfiguration
ODCS_CONFIG_FILE=/src/server/conf/config.py
ODCS_CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/
ODCS_DB_URL=postgresql+psycopg2://odcs:password@postgres/odcs
# Directory where the generated composes are stored. This hast to match
# location where odcs-composes volume is mounted in frontend and backend
# containers.
ODCS_TARGET_DIR=/mnt/odcs
TARGET_DIR_URL=http://localhost:8080

# FLASK SETTINGS
# Force flask to reload application on change of source files.
FLASK_ENV=development
```

The services can be start with `sudo docker-compose up` command. If you have face an error or something that does not work correctly please use the following steps;

1. Check whether there is already created docker volume.


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME


    If the output is like above, it means there isn't any volume yet and it is sufficient to run `sudo docker-compose up` and then `sudo docker-compose down` command. This creates the volumes and if you run the above command again the output becomes as follows;


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME
        local       odcs_odcs-composes
        local       odcs_odcs-postgres
        local       odcs_odcs-rabbitmq


2. After this point we need to set the correct permission to `ocds_odcs-composes` volume. In order to find where is the actual location of the volume type the following


        $ sudo docker volume inspect odcs_odcs-composes
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        [
            {
                "Name": "odcs_odcs-composes",
                "Driver": "local",
                "Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data",
                "CreatedAt": "2021-10-04T13:19:36.478636851+02:00",
                "Labels": {
                    "io.podman.compose.project": "odcs"
                },
                "Scope": "local",
                "Options": {}
            }
        ]

    `"Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data"` shows the exact location of the corresponding volume.

    Add group write permission to the Mountpoint by


        $ sudo chmod 775 /var/lib/containers/storage/volumes/odcs_odcs-composes/_data


3. In this step it is sufficient to run `sudo docker-compose up` command to start the services properly.

Here are some REST calls for checking the ODCS.

* `$ curl -s http://localhost:5000/api/1/composes/ | jq .` This call shows all the composes in db.
* `$ odcs --server http://localhost:5000/ create-pulp <Pulp content set>` This call starts a pulp compose that match the given pulp content set
* `$ odcs --server http://localhost:5000/ create-raw-config --compose-type test my_raw_config master` This call starts a compose with the configuration defined as my_raw_config


%package help
Summary:	Development documents and examples for odcs
Provides:	python3-odcs-doc
%description help
# On Demand Compose Service - ODCS

![logo of ODCS](https://pagure.io/odcs/raw/master/f/logo.png)

## What is ODCS

The main goal of ODCS is to allow generation of temporary composes using the REST API calls. By a compose, we mainly mean RPM repository with packages taken from different sources, but in the future, generation of other output types could be possible too.

ODCS can take RPMs for a compose from multiple sources like Koji tag, module built in Koji or external repository provided by Pulp tool.

## Using ODCS - client library

There is client library written in Python which allows easy access to REST API provided by ODCS server.

### Installing the ODCS client

On Fedora:

```
$ sudo dnf install odcs-client
```

If you want to install using `pip`, you can run following:

```
$ sudo pip install odcs[client]
```

In case you want your python project to depend on ODCS client library and add it to your `requirements.txt`, you can just use following to depend on ODCS client:

```
odcs[client]
```

### ODCS authentication system

ODCS server can be configured to authenticate using OpenIDC, Kerberos or SSL. Eventually it can be set in NoAuth mode to support anonymous access. Depending on the ODCS server configuration, you have to set your authentication method when creating ODCS class instance.

#### Using OpenIDC for authentication

To use OpenIDC, you have to provide the OpenIDC token to ODCS client class constructor. To obtain that OpenIDC token, you can either use `python-openidc-client`, or ask the OpenIDC provider for service token which does not have to be refreshed. Once you have the token, you can create the ODCS instance like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.OpenIDC,
            openidc_token="your_openidc_token")
```

Getting the `openidc_token` using `python-openidc-client` library can be done like this:

```
import openidc_client
staging = False

if staging:
    id_provider = 'https://id.stg.fedoraproject.org/openidc/'
else:
    id_provider = 'https://id.fedoraproject.org/openidc/'

# Get the auth token using the OpenID client.
oidc = openidc_client.OpenIDCClient(
    'odcs',
    id_provider,
    {'Token': 'Token', 'Authorization': 'Authorization'},
    'odcs-authorizer',
    'notsecret',
)

scopes = [
    'openid',
    'https://id.fedoraproject.org/scope/groups',
    'https://pagure.io/odcs/new-compose',
    'https://pagure.io/odcs/renew-compose',
    'https://pagure.io/odcs/delete-compose',
]
try:
    token = oidc.get_token(scopes, new_token=True)
    token = oidc.report_token_issue()
except requests.exceptions.HTTPError as e:
    print(e.response.text)
    raise
```

#### Using Kerberos for authentication

To use Kerberos, you have to have valid Kerberos ticket or you need to have the Kerberos keytab file. If you want to use ODCS client library with Kerberos keytab, you have to set the `KRB5_CLIENT_KTNAME` environment variable to full path to the keytab file you want to use. You can for example do it like this:

```
from odcs.client.odcs import ODCS, AuthMech
from os import environ
environ["KRB5_CLIENT_KTNAME"] = "/full/path/to/ketab"

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.Kerberos)
```

#### Using SSL for authentication

To use SSL, you have to have SSL client certificate and key files. You then have to choose SSL AuthMech and pass the paths to SSL client certificate and key like this:

```
from odcs.client.odcs import ODCS, AuthMech

odcs = ODCS("https://odcs.fedoraproject.org",
            auth_mech=AuthMech.SSL,
            ssl_cert="/path/to/ssl-crt.pem",
            ssl_key="/path/to/ssl-key.pem")
```

### Requesting new compose

The general way how to request new ODCS compose is following:

```
compose = odcs.new_compose(sources, source_type)
```

Both `sources` and `source_type` are strings. Depending on `source_type` value, the `sources` have following meaning:

| `source_type` | `source` |
|---------------|----------|
| tag           | Name of Koji tag to take RPMs from. |
| module        | White-space separated NAME:STREAM or NAME:STREAM:VERSION of modules to include in compose. |
| pulp          | White-space separated list of content-sets or repository ids. Repositories will be included in a compose. |
| raw_config    | String in `name#commit` hash format. The `name` must match one of the raw config locations defined in ODCS server config as `raw_config_urls`. The `commit` is commit hash defining the version of raw config to use. This config is then used as input config for Pungi. |
| build         | Source should be omitted in the request. The list of Koji builds included in a compose is defined by `builds` attribute. |
| pungi_compose | URL to variant repository of external compose generated by the Pungi. For example https://kojipkgs.fedoraproject.org/compose/rawhide/latest-Fedora-Rawhide/compose/Server/. The generated compose will contain the same set of RPMs as the given external compose variant. The packages will be taken from the configured Koji instance. |

There are also additional optional attributes you can pass to `new_compose(...)` method:

- `seconds_to_live` - Number of seconds after which the generated compose should expire and will be removed.
- `packages` - List of packages which should be included in a compose. This is used only when `source_type` is set to `tag` or `build` to further limit the compose repository.
If the `packages` is not set, all packages in Koji tag or all packages in a `builds` list will be included in a final compose.
- `flags` - List of flags to further modify the compose output:
    - `no_deps` - For `tag` `source_type`, do not resolve dependencies between packages and include only packages listed in the `packages` in the compose. For `module` `source_type`, do not resolve dependencies between modules and include only the requested module in the compose.
    - `include_unpublished_pulp_repos` - For `pulp` `source_type`, include also unpublished repositories for input content-sets.
    - `check_deps` - When set, abort the compose when some package has broken dependencies.
    - `no_reuse` - When set, do not try to reuse old compose.
    - `ignore_absent_pulp_repos` - For `pulp` `source_type`, ignore any content set that does not exist in Pulp
    - `use_only_compatible_arch` - For `pulp` `source_type` only. When this flag is set, architecture hardcoded in URL returned from Pulp will be replaced with `$basearch` variable. The repository definition will also define `skip_if_unavailable = 1`. This could be useful when multiple content sets are included in the repofile to completly ignore packages from repositories for incompatible architectures.
- `sigkeys` - List of signature keys IDs. Only packages signed by one of these keys will be included in a compose. If there is no signed version of a package, compose will fail. It is also possible to pass an empty-string in a list meaning unsigned packages are allowed. For example if you want to prefer packages signed by key with ID `123` and also allow unsigned packages to appear in a compose, you can do it by setting sigkeys to `["123", ""]`.
- `results` - List of additional results which will be generated as part of a compose. Valid keys are:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `boot.iso` - Generates `images/boot.iso` file which is needed to build base container images from resulting compose.
- `arches` - List of additional Koji arches to build this compose for. By default, the compose is built only for "x86_64" arch.
- `multilib_arches` - Subset of `arches` for which the multilib should be enabled. For each architecture in the `multilib_arches` list, ODCS will include also packages from other compatible architectures in a compose. For example when "x86_64" is included `multilib_arches`, ODCS will include also "i686" packages in a compose. The set of packages included in a composes is influenced by `multilib_method` list.
- `multilib_method` - List defining the method used to determine whether consider package as multilib. Defaults to empty list. The list can have following values:
    - `iso` - Generates non-installable ISO files with RPMs from a compose.
    - `runtime` - Packages whose name ends with "-devel" or "-static" suffix will be considered as multilib.
    - `devel` - Packages that install some shared object file "*.so.*" will be considered as multilib.
    - `all` - All pakages will be considered as multilib.
- `builds` - List of NVRs defining the Koji builds to include in a compose. Only valid for `tag` and `build` source types. For `tag` source type, the NVRs will be considered
for inclusion in a compose on top of Koji tag defined by `source`. For `build` source type, only the Koji builds defined by the NVRs will be considered for inclusion. The `packages` still need to be set to include particular packages from the Koji builds in a compose.
- `lookaside_repos` - List of URLs pointing to RPM repositories with packages which will be used by internal dependency resolver to resolve dependencies. Packages from these repositories will not appear in the resulting ODCS compose, but they are considered while checking whether the RPM dependencies are satisfied in the resulting compose when `check_deps` ODCS flag.
- `module_defaults_url` - List with URL to git repository with Module defaults data and the branch name or commit hash. For example ["https://pagure.io/releng/fedora-module-defaults.git", "master"]. This is used only when creating modular compose including non-modular RPMs.
- `modular_koji_tags` - List of Koji tags in which the modular Koji Content Generator builds are tagged. Such builds will be included in a compose.

The `new_compose` method returns `dict` object describing the compose, for example:

```
{
    "arches": "x86_64 ppc64",
    "flags": [
        "no_deps"
    ],
    "id": 1,
    "owner": "jkaluza",
    "packages": "gofer-package",
    "removed_by": null,
    "result_repo": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary",
    "result_repofile": "https://odcs.fedoraproject.org/composes/latest-odcs-1-1/compose/Temporary/odcs-1.repo",
    "results": [
        "repository"
    ],
    "sigkeys": "",
    "source": "f26",
    "source_type": 1,
    "state": 3,
    "state_name": "wait",
    "time_done": "2017-10-13T17:03:13Z",
    "time_removed": "2017-10-14T17:00:00Z",
    "time_submitted": "2017-10-13T16:59:51Z",
    "time_to_expire": "2017-10-14T16:59:51Z"
}
```

The most useful data there is `result_repofile`, which points to the .repo file with URLs for generated compose. Another very important data there is the `state` and `state_name` field. There are following states of a compose:

| `state` | `state_name` | Description |
|---------|--------------|-------------|
| 0       | wait         | Compose is waiting in a queue to be generated |
| 1       | generating   | Compose is being generated |
| 2       | done         | Compose is generated - done |
| 3       | removed      | Compose has expired and is removed |
| 4       | failed       | Compose generation has failed |

As you can see in our example, compose is in `wait` state and therefore we have to wait until the ODCS generates the compose.

### Waiting until the compose is generated

There are two ways how to wait for the compose generation. The preferred one is listening on Fedora messaging bus for `odcs.state.change` message with `done` or `failed` state and another one is using HTTP polling implemented in `wait_for_compose(...)` method.

If your application does not allow listening on the bus for some reason, you can use `wait_for_compose(...)` method like this:

```
compose = odcs.new_compose(sources, source_type)

# Blocks until the compose is ready, but maximally for 600 seconds.
compose = odcs.wait_for_compose(compose["id"], timeout=600)

if compose["state_name"] == "done":
    print "Compose done, URL with repo file", compose["result_repofile"]
else:
    print "Failed to generate compose"
```

### Checking the state of existing ODCS compose

Once you have the compose ready, you might want to check its state later. This can be done using the `get_compose(...)` method like this:

```
compose = odcs.get_compose(compose["id"])
```

### Renewing the compose

If the `time_to_expire` for your compose is getting closer and you know you want to continue using the compose, you can increase the `time_to_expire` using the `renew_compose(...)` method. You can also use this method to regenerate an expired compose in the `removed` state. Such compose will have the same versions of packages as the original compose.

```
compose = odcs.renew_compose(compose["id"])
```

## Development

### Code Convention

The code must be well formatted via ``black`` and pass ``flake8`` checking.

Run ``tox -e black,flake8`` to do the check.

### Unit-testing

Install packages required by pip to compile some python packages:

```
$ sudo dnf install -y gcc swig redhat-rpm-config python-devel openssl-devel openldap-devel \
    zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel tk-devel \
    git python3-cairo-devel cairo-gobject-devel gobject-introspection-devel
```

A lot of these dependencies come from the module
[pygobject](https://pygobject.readthedocs.io/en/latest/devguide/dev_environ.html#fedora-dep).

Run the tests:

```
$ make check
```

### Testing local composes from plain RPM repositories

You can test ODCS by generating compose from the `./server/tests/repo` repository using following commands:

```
$ ./create_sqlite_db
$ ./start_odcs_from_here
```

Before executing the command `start_odcs_from_here`, a messaging broker supporting AMQP protocol is required to run locally as well in order to run asynchronous tasks to generate composes. Here is an example to run a RabbitMQ broker:

```
sudo dnf install -y rabbitmq-server
sudo systemctl start rabbitmq-server
```

Add the `repo` source type to the server configuration in `./server/odcs/server/config.py`. (This will cause some tests to fail, so it needs to be reverted back after you are done with your changes!)

And in another terminal, submit a request to frontend:

```
$ ./submit_test_compose repo `pwd`/server/tests/repo ed
{
  "id": 1,
  "owner": "Unknown",
  "result_repo": null,
  "source": "/home/hanzz/code/fedora-modularization/odcs/tests/repo",
  "source_type": 3,
  "state": 0,
  "state_name": "wait",
  "time_done": null,
  "time_removed": null,
  "time_submitted": "2017-06-12T14:18:19Z"
}
```

You should then see the backend process generating the compose and once it's done, the resulting compose in `./test_composes/latest-Unknown-1/compose/Temporary` directory.

### Using docker-compose for creating a local setup

You can create test setup for ODCS with the docker-compose file. This yaml file creates docker container for the backend and frontend setup of ODCS and run multiple services together. These services are;

* **rabbitmq** (Handles the communication between backend and frontend)
* **postgres** (Creates the database where the localy generated composes are stored)
* **backend** (Backend service of ODCS)
* **frontend** (Frontend service of ODCS that handles the REST API)
* **static** (Apache service for making storage available)
* **beat** (Cronjob for backend to check the service status)

In addition to these, there are also three docker volumes (`odcs_odcs-composes`, `odcs_odcs-postgres` and `odcs_rabbitmq`) are created. These are providing persistent storage for the services.

This yaml file requires also an **.env** file that specified some enviroment variables for the configuration of frontend and backend. Such an **.env** file should be in the same path with the **docker-compose.yml** file and here are the necessary variables that need to be specified in this file;
```
# Pyhton path
PYTHONPATH=/src/common:/src/server:/src/client

# POSTGRES
POSTGRES_USER=odcs
POSTGRES_PASSWORD=password

# PULP CONFIGURATION
PULP_SERVER_URL=<URL of the pulp server>
PULP_USERNAME=<Username for the pulp server>
PULP_PASSWORD=<Credentials for the pulp server>
RAW_CONFIG_URLS=<Raw config settings in JSON format>

# ODCS CONFIGURATION
ODCS_CONFIG_SECTION=DevConfiguration
ODCS_CONFIG_FILE=/src/server/conf/config.py
ODCS_CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/
ODCS_DB_URL=postgresql+psycopg2://odcs:password@postgres/odcs
# Directory where the generated composes are stored. This hast to match
# location where odcs-composes volume is mounted in frontend and backend
# containers.
ODCS_TARGET_DIR=/mnt/odcs
TARGET_DIR_URL=http://localhost:8080

# FLASK SETTINGS
# Force flask to reload application on change of source files.
FLASK_ENV=development
```

The services can be start with `sudo docker-compose up` command. If you have face an error or something that does not work correctly please use the following steps;

1. Check whether there is already created docker volume.


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME


    If the output is like above, it means there isn't any volume yet and it is sufficient to run `sudo docker-compose up` and then `sudo docker-compose down` command. This creates the volumes and if you run the above command again the output becomes as follows;


        $ sudo docker volume ls
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        DRIVER      VOLUME NAME
        local       odcs_odcs-composes
        local       odcs_odcs-postgres
        local       odcs_odcs-rabbitmq


2. After this point we need to set the correct permission to `ocds_odcs-composes` volume. In order to find where is the actual location of the volume type the following


        $ sudo docker volume inspect odcs_odcs-composes
        Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg.
        [
            {
                "Name": "odcs_odcs-composes",
                "Driver": "local",
                "Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data",
                "CreatedAt": "2021-10-04T13:19:36.478636851+02:00",
                "Labels": {
                    "io.podman.compose.project": "odcs"
                },
                "Scope": "local",
                "Options": {}
            }
        ]

    `"Mountpoint": "/var/lib/containers/storage/volumes/odcs_odcs-composes/_data"` shows the exact location of the corresponding volume.

    Add group write permission to the Mountpoint by


        $ sudo chmod 775 /var/lib/containers/storage/volumes/odcs_odcs-composes/_data


3. In this step it is sufficient to run `sudo docker-compose up` command to start the services properly.

Here are some REST calls for checking the ODCS.

* `$ curl -s http://localhost:5000/api/1/composes/ | jq .` This call shows all the composes in db.
* `$ odcs --server http://localhost:5000/ create-pulp <Pulp content set>` This call starts a pulp compose that match the given pulp content set
* `$ odcs --server http://localhost:5000/ create-raw-config --compose-type test my_raw_config master` This call starts a compose with the configuration defined as my_raw_config


%prep
%autosetup -n odcs-0.5.0

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-odcs -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Mon May 15 2023 Python_Bot <Python_Bot@openeuler.org> - 0.5.0-1
- Package Spec generated