File: _proxy.py

package info (click to toggle)
python-openstacksdk 4.4.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,352 kB
  • sloc: python: 122,960; sh: 153; makefile: 23
file content (1273 lines) | stat: -rw-r--r-- 49,315 bytes parent folder | download
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
1267
1268
1269
1270
1271
1272
1273
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from calendar import timegm
import collections
import functools
from hashlib import sha1
import hmac
import json
import os
import time
import typing as ty
from urllib import parse

from openstack import _log
from openstack.cloud import _utils
from openstack import exceptions
from openstack.object_store.v1 import account as _account
from openstack.object_store.v1 import container as _container
from openstack.object_store.v1 import info as _info
from openstack.object_store.v1 import obj as _obj
from openstack import proxy
from openstack import resource
from openstack import utils

DEFAULT_OBJECT_SEGMENT_SIZE = 1073741824  # 1GB
DEFAULT_MAX_FILE_SIZE = (5 * 1024 * 1024 * 1024 + 2) / 2
EXPIRES_ISO8601_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
SHORT_EXPIRES_ISO8601_FORMAT = '%Y-%m-%d'


def _get_expiration(expiration):
    return int(time.time() + expiration)


class Proxy(proxy.Proxy):
    _resource_registry = {
        "account": _account.Account,
        "container": _container.Container,
        "info": _info.Info,
        "object": _obj.Object,
    }

    skip_discovery = True

    Account = _account.Account
    Container = _container.Container
    Object = _obj.Object

    log = _log.setup_logging('openstack')

    @functools.lru_cache(maxsize=256)
    def _extract_name(self, url, service_type=None, project_id=None):
        url_path = parse.urlparse(url).path.strip()
        # Remove / from the beginning to keep the list indexes of interesting
        # things consistent
        if url_path.startswith('/'):
            url_path = url_path[1:]

        # Split url into parts and exclude potential project_id in some urls
        url_parts = [
            x
            for x in url_path.split('/')
            if (
                x != project_id
                and (
                    not project_id
                    or (project_id and x != 'AUTH_' + project_id)
                )
            )
        ]
        # Strip leading version piece so that
        # GET /v1/AUTH_xxx
        # returns ['AUTH_xxx']
        if (
            url_parts[0]
            and url_parts[0][0] == 'v'
            and url_parts[0][1]
            and url_parts[0][1].isdigit()
        ):
            url_parts = url_parts[1:]

        # Strip out anything that's empty or None
        parts = [part for part in url_parts if part]

        # Getting the root of an endpoint is doing version discovery
        if not parts:
            return ['account']

        if len(parts) == 1:
            if 'endpoints' in parts:
                return ['endpoints']
            else:
                return ['container']
        else:
            return ['object']

    def get_account_metadata(self):
        """Get metadata for this account.

        :rtype:
            :class:`~openstack.object_store.v1.account.Account`
        """
        return self._head(_account.Account)

    def set_account_metadata(self, **metadata):
        """Set metadata for this account.

        :param kwargs metadata: Key/value pairs to be set as metadata on the
            container. Custom metadata can be set. Custom metadata are keys and
            values defined by the user.
        """
        account = self._get_resource(_account.Account, None)
        account.set_metadata(self, metadata)

    def delete_account_metadata(self, keys):
        """Delete metadata for this account.

        :param keys: The keys of metadata to be deleted.
        """
        account = self._get_resource(_account.Account, None)
        account.delete_metadata(self, keys)

    def containers(self, **query):
        """Obtain Container objects for this account.

        :param kwargs query: Optional query parameters to be sent to limit
            the resources being returned.

        :rtype: A generator of
            :class:`~openstack.object_store.v1.container.Container` objects.
        """
        return self._list(_container.Container, paginated=True, **query)

    def create_container(self, name, **attrs):
        """Create a new container from attributes

        :param container: Name of the container to create.
        :param dict attrs: Keyword arguments which will be used to create
            a :class:`~openstack.object_store.v1.container.Container`,
            comprised of the properties on the Container class.

        :returns: The results of container creation
        :rtype: :class:`~openstack.object_store.v1.container.Container`
        """
        return self._create(_container.Container, name=name, **attrs)

    def delete_container(self, container, ignore_missing=True):
        """Delete a container

        :param container: The value can be either the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param bool ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be raised when
            the container does not exist. When set to ``True``, no exception
            will be set when attempting to delete a nonexistent server.

        :returns: ``None``
        """
        self._delete(
            _container.Container, container, ignore_missing=ignore_missing
        )

    def get_container_metadata(self, container):
        """Get metadata for a container

        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.

        :returns: One :class:`~openstack.object_store.v1.container.Container`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        return self._head(_container.Container, container)

    def set_container_metadata(self, container, refresh=True, **metadata):
        """Set metadata for a container.

        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container`
            instance.
        :param refresh: Flag to trigger refresh of container object re-fetch.
        :param kwargs metadata: Key/value pairs to be set as metadata on the
            container. Both custom and system metadata can be set. Custom
            metadata are keys and values defined by the user. System metadata
            are keys defined by the Object Store and values defined by the
            user. The system metadata keys are:

            - `content_type`
            - `is_content_type_detected`
            - `versions_location`
            - `read_ACL`
            - `write_ACL`
            - `sync_to`
            - `sync_key`
        """
        res = self._get_resource(_container.Container, container)
        res.set_metadata(self, metadata, refresh=refresh)
        return res

    def delete_container_metadata(self, container, keys):
        """Delete metadata for a container.

        :param container: The value can be the ID of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param keys: The keys of metadata to be deleted.
        """
        res = self._get_resource(_container.Container, container)
        res.delete_metadata(self, keys)
        return res

    def objects(self, container, **query):
        """Return a generator that yields the Container's objects.

        :param container: A container object or the name of a container
            that you want to retrieve objects from.
        :type container:
            :class:`~openstack.object_store.v1.container.Container`
        :param kwargs query: Optional query parameters to be sent to limit
            the resources being returned.

        :rtype: A generator of
            :class:`~openstack.object_store.v1.obj.Object` objects.
        """
        container = self._get_container_name(container=container)

        for obj in self._list(
            _obj.Object,
            container=container,
            paginated=True,
            format='json',
            **query,
        ):
            obj.container = container
            yield obj

    def _get_container_name(self, obj=None, container=None):
        if obj is not None:
            obj = self._get_resource(_obj.Object, obj)
            if obj.container is not None:
                return obj.container
        if container is not None:
            container = self._get_resource(_container.Container, container)
            return container.name

        raise ValueError("container must be specified")

    def get_object(
        self,
        obj,
        container=None,
        resp_chunk_size=1024,
        outfile=None,
        remember_content=False,
    ):
        """Get the data associated with an object

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param int resp_chunk_size: chunk size of data to read. Only used if
            the results are being written to a file or stream is True.
            (optional, defaults to 1k)
        :param outfile: Write the object to a file instead of returning the
            contents. If this option is given, body in the return tuple will be
            None. outfile can either be a file path given as a string, or a
            File like object.
        :param bool remember_content: Flag whether object data should be saved
            as `data` property of the Object. When left as `false` and
            `outfile` is not defined data will not be saved and need to be
            fetched separately.

        :returns: Instance of the
            :class:`~openstack.object_store.v1.obj.Object` objects.
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        container_name = self._get_container_name(obj=obj, container=container)

        _object = self._get_resource(
            _obj.Object, obj, container=container_name
        )
        request = _object._prepare_request()

        get_stream = outfile is not None

        response = self.get(
            request.url, headers=request.headers, stream=get_stream
        )
        exceptions.raise_from_response(response)
        _object._translate_response(response, has_body=False)

        if outfile:
            if isinstance(outfile, str):
                outfile_handle = open(outfile, 'wb')
            else:
                outfile_handle = outfile
            for chunk in response.iter_content(
                resp_chunk_size, decode_unicode=False
            ):
                outfile_handle.write(chunk)
            if isinstance(outfile, str):
                outfile_handle.close()
            else:
                outfile_handle.flush()
        elif remember_content:
            _object.data = response.text

        return _object

    def download_object(self, obj, container=None, **attrs):
        """Download the data contained inside an object.

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.

        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        container_name = self._get_container_name(obj=obj, container=container)
        obj = self._get_resource(
            _obj.Object, obj, container=container_name, **attrs
        )
        return obj.download(self)

    def stream_object(self, obj, container=None, chunk_size=1024, **attrs):
        """Stream the data contained inside an object.

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.

        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        :returns: An iterator that iterates over chunk_size bytes
        """
        container_name = self._get_container_name(obj=obj, container=container)
        obj = self._get_resource(
            _obj.Object, obj, container=container_name, **attrs
        )
        return obj.stream(self, chunk_size=chunk_size)

    def create_object(
        self,
        container,
        name,
        filename=None,
        md5=None,
        sha256=None,
        segment_size=None,
        use_slo=True,
        metadata=None,
        generate_checksums=None,
        data=None,
        **headers,
    ):
        """Create a file object.

        Automatically uses large-object segments if needed.

        :param container: The name of the container to store the file in.
            This container will be created if it does not exist already.
        :param name: Name for the object within the container.
        :param filename: The path to the local file whose contents will be
            uploaded. Mutually exclusive with data.
        :param data: The content to upload to the object. Mutually exclusive
            with filename.
        :param md5: A hexadecimal md5 of the file. (Optional), if it is known
            and can be passed here, it will save repeating the expensive md5
            process. It is assumed to be accurate.
        :param sha256: A hexadecimal sha256 of the file. (Optional) See md5.
        :param segment_size: Break the uploaded object into segments of this
            many bytes. (Optional) SDK will attempt to discover the maximum
            value for this from the server if it is not specified, or will use
            a reasonable default.
        :param headers: These will be passed through to the object creation
            API as HTTP Headers.
        :param use_slo: If the object is large enough to need to be a Large
            Object, use a static rather than dynamic object. Static Objects
            will delete segment objects when the manifest object is deleted.
            (optional, defaults to True)
        :param generate_checksums: Whether to generate checksums on the client
            side that get added to headers for later prevention of double
            uploads of identical data. (optional, defaults to True)
        :param metadata: This dict will get changed into headers that set
            metadata of the object

        :raises: ``:class:`~openstack.exceptions.SDKException``` on operation
            error.
        """
        if data is not None and filename:
            raise ValueError(
                "Both filename and data given. Please choose one."
            )
        if data is not None and not name:
            raise ValueError("name is a required parameter when data is given")
        if data is not None and generate_checksums:
            raise ValueError(
                "checksums cannot be generated with data parameter"
            )
        if generate_checksums is None:
            if data is not None:
                generate_checksums = False
            else:
                generate_checksums = True

        if not metadata:
            metadata = {}

        if not filename and data is None:
            filename = name

        if generate_checksums and (md5 is None or sha256 is None):
            (md5, sha256) = utils._get_file_hashes(filename)
        if md5:
            metadata[self._connection._OBJECT_MD5_KEY] = md5
        if sha256:
            metadata[self._connection._OBJECT_SHA256_KEY] = sha256

        container_name = self._get_container_name(container=container)
        endpoint = f'{container_name}/{name}'

        if data is not None:
            self.log.debug(
                "swift uploading data to %(endpoint)s", {'endpoint': endpoint}
            )
            return self._create(
                _obj.Object,
                container=container_name,
                name=name,
                data=data,
                metadata=metadata,
                **headers,
            )

        # segment_size gets used as a step value in a range call, so needs
        # to be an int
        if segment_size:
            segment_size = int(segment_size)
        segment_size = self.get_object_segment_size(segment_size)
        file_size = os.path.getsize(filename)

        if self.is_object_stale(container_name, name, filename, md5, sha256):
            self._connection.log.debug(
                "swift uploading %(filename)s to %(endpoint)s",
                {'filename': filename, 'endpoint': endpoint},
            )

            if metadata is not None:
                # Rely on the class headers calculation for requested metadata
                meta_headers = _obj.Object()._calculate_headers(metadata)
                headers.update(meta_headers)

            if file_size <= segment_size:
                self._upload_object(endpoint, filename, headers)

            else:
                self._upload_large_object(
                    endpoint,
                    filename,
                    headers,
                    file_size,
                    segment_size,
                    use_slo,
                )

    # Backwards compat
    upload_object = create_object

    def copy_object(self):
        """Copy an object."""
        raise NotImplementedError

    def delete_object(self, obj, ignore_missing=True, container=None):
        """Delete an object

        :param obj: The value can be either the name of an object or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param container: The value can be the ID of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param bool ignore_missing: When set to ``False``
            :class:`~openstack.exceptions.NotFoundException` will be raised when
            the object does not exist.  When set to ``True``, no exception will
            be set when attempting to delete a nonexistent server.

        :returns: ``None``
        """
        container_name = self._get_container_name(obj, container)

        self._delete(
            _obj.Object,
            obj,
            ignore_missing=ignore_missing,
            container=container_name,
        )

    def get_object_metadata(self, obj, container=None):
        """Get metadata for an object.

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the ID of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.

        :returns: One :class:`~openstack.object_store.v1.obj.Object`
        :raises: :class:`~openstack.exceptions.NotFoundException`
            when no resource can be found.
        """
        container_name = self._get_container_name(obj, container)

        return self._head(_obj.Object, obj, container=container_name)

    def set_object_metadata(self, obj, container=None, **metadata):
        """Set metadata for an object.

        Note: This method will do an extra HEAD call.

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param kwargs metadata: Key/value pairs to be set as metadata
            on the container. Both custom and system metadata can be set.
            Custom metadata are keys and values defined by the user. System
            metadata are keys defined by the Object Store and values defined by
            the user. The system metadata keys are:

            - `content_type`
            - `content_encoding`
            - `content_disposition`
            - `delete_after`
            - `delete_at`
            - `is_content_type_detected`
        """
        container_name = self._get_container_name(obj, container)
        res = self._get_resource(_obj.Object, obj, container=container_name)
        res.set_metadata(self, metadata)
        return res

    def delete_object_metadata(self, obj, container=None, keys=None):
        """Delete metadata for an object.

        :param obj: The value can be the name of an object or a
            :class:`~openstack.object_store.v1.obj.Object` instance.
        :param container: The value can be the ID of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param keys: The keys of metadata to be deleted.
        """
        container_name = self._get_container_name(obj, container)
        res = self._get_resource(_obj.Object, obj, container=container_name)
        res.delete_metadata(self, keys)
        return res

    def is_object_stale(
        self, container, name, filename, file_md5=None, file_sha256=None
    ):
        """Check to see if an object matches the hashes of a file.

        :param container: Name of the container.
        :param name: Name of the object.
        :param filename: Path to the file.
        :param file_md5: Pre-calculated md5 of the file contents. Defaults to
            None which means calculate locally.
        :param file_sha256: Pre-calculated sha256 of the file contents.
            Defaults to None which means calculate locally.
        """
        try:
            metadata = self.get_object_metadata(name, container).metadata
        except exceptions.NotFoundException:
            self._connection.log.debug(
                f"swift stale check, no object: {container}/{name}"
            )
            return True

        if not (file_md5 or file_sha256):
            (file_md5, file_sha256) = utils._get_file_hashes(filename)
        md5_key = metadata.get(
            self._connection._OBJECT_MD5_KEY,
            metadata.get(self._connection._SHADE_OBJECT_MD5_KEY, ''),
        )
        sha256_key = metadata.get(
            self._connection._OBJECT_SHA256_KEY,
            metadata.get(self._connection._SHADE_OBJECT_SHA256_KEY, ''),
        )
        up_to_date = utils._hashes_up_to_date(
            md5=file_md5,
            sha256=file_sha256,
            md5_key=md5_key,
            sha256_key=sha256_key,
        )

        if not up_to_date:
            self._connection.log.debug(
                "swift checksum mismatch: "
                "%(filename)s!=%(container)s/%(name)s",
                {'filename': filename, 'container': container, 'name': name},
            )
            return True

        self._connection.log.debug(
            "swift object up to date: %(container)s/%(name)s",
            {'container': container, 'name': name},
        )
        return False

    def _upload_large_object(
        self, endpoint, filename, headers, file_size, segment_size, use_slo
    ):
        # If the object is big, we need to break it up into segments that
        # are no larger than segment_size, upload each of them individually
        # and then upload a manifest object. The segments can be uploaded in
        # parallel, so we'll use the async feature of the TaskManager.

        segment_futures = []
        segment_results = []
        retry_results = []
        retry_futures = []
        manifest = []

        # Get an OrderedDict with keys being the swift location for the
        # segment, the value a FileSegment file-like object that is a
        # slice of the data for the segment.
        segments = self._get_file_segments(
            endpoint, filename, file_size, segment_size
        )

        # Schedule the segments for upload
        for name, segment in segments.items():
            # Async call to put - schedules execution and returns a future
            segment_future = self._connection._pool_executor.submit(
                self.put, name, headers=headers, data=segment, raise_exc=False
            )
            segment_futures.append(segment_future)
            # TODO(mordred) Collect etags from results to add to this manifest
            # dict. Then sort the list of dicts by path.
            manifest.append(
                dict(
                    # While Object Storage usually expects the name to be
                    # urlencoded in most requests, the SLO manifest requires
                    # plain object names instead.
                    path=f'/{parse.unquote(name)}',
                    size_bytes=segment.length,
                )
            )

        # Try once and collect failed results to retry
        segment_results, retry_results = self._connection._wait_for_futures(
            segment_futures, raise_on_error=False
        )

        self._add_etag_to_manifest(segment_results, manifest)

        for result in retry_results:
            # Grab the FileSegment for the failed upload so we can retry
            name = self._object_name_from_url(result.url)
            segment = segments[name]
            segment.seek(0)
            # Async call to put - schedules execution and returns a future
            segment_future = self._connection._pool_executor.submit(
                self.put, name, headers=headers, data=segment
            )
            # TODO(mordred) Collect etags from results to add to this manifest
            # dict. Then sort the list of dicts by path.
            retry_futures.append(segment_future)

        # If any segments fail the second time, just throw the error
        segment_results, retry_results = self._connection._wait_for_futures(
            retry_futures, raise_on_error=True
        )

        self._add_etag_to_manifest(segment_results, manifest)

        try:
            if use_slo:
                return self._finish_large_object_slo(
                    endpoint, headers, manifest
                )
            else:
                return self._finish_large_object_dlo(endpoint, headers)
        except Exception:
            try:
                segment_prefix = endpoint.split('/')[-1]
                self.log.debug(
                    "Failed to upload large object manifest for %s. "
                    "Removing segment uploads.",
                    segment_prefix,
                )
                self._delete_autocreated_image_objects(
                    segment_prefix=segment_prefix
                )
            except Exception:
                self.log.exception(
                    "Failed to cleanup image objects for %s:", segment_prefix
                )
            raise

    def _finish_large_object_slo(self, endpoint, headers, manifest):
        # TODO(mordred) send an etag of the manifest, which is the md5sum
        # of the concatenation of the etags of the results
        headers = headers.copy()
        retries = 3
        while True:
            try:
                return exceptions.raise_from_response(
                    self.put(
                        endpoint,
                        params={'multipart-manifest': 'put'},
                        headers=headers,
                        data=json.dumps(manifest),
                    )
                )
            except Exception:
                retries -= 1
                if retries == 0:
                    raise

    def _finish_large_object_dlo(self, endpoint, headers):
        headers = headers.copy()
        headers['X-Object-Manifest'] = endpoint
        retries = 3
        while True:
            try:
                return exceptions.raise_from_response(
                    self.put(endpoint, headers=headers)
                )
            except Exception:
                retries -= 1
                if retries == 0:
                    raise

    def _upload_object(self, endpoint, filename, headers):
        with open(filename, 'rb') as dt:
            return self.put(endpoint, headers=headers, data=dt)

    def _get_file_segments(self, endpoint, filename, file_size, segment_size):
        # Use an ordered dict here so that testing can replicate things
        segments = collections.OrderedDict()
        for index, offset in enumerate(range(0, file_size, segment_size)):
            remaining = file_size - (index * segment_size)
            segment = _utils.FileSegment(
                filename,
                offset,
                segment_size if segment_size < remaining else remaining,
            )
            name = f'{endpoint}/{index:0>6}'
            segments[name] = segment
        return segments

    def get_object_segment_size(self, segment_size):
        """Get a segment size that will work given capabilities"""
        if segment_size is None:
            segment_size = DEFAULT_OBJECT_SEGMENT_SIZE
        min_segment_size = 0
        try:
            # caps = self.get_object_capabilities()
            caps = self.get_info()
        except (
            exceptions.NotFoundException,
            exceptions.PreconditionFailedException,
        ):
            server_max_file_size = DEFAULT_MAX_FILE_SIZE
            self._connection.log.info(
                "Swift capabilities not supported. "
                "Using default max file size."
            )
        except exceptions.SDKException:
            raise
        else:
            server_max_file_size = caps.swift.get('max_file_size', 0)
            min_segment_size = caps.slo.get('min_segment_size', 0)

        if segment_size > server_max_file_size:
            return server_max_file_size
        if segment_size < min_segment_size:
            return min_segment_size
        return segment_size

    def _object_name_from_url(self, url):
        '''Get container_name/object_name from the full URL called.

        Remove the Swift endpoint from the front of the URL, and remove
        the leaving / that will leave behind.'''
        endpoint = self.get_endpoint()
        object_name = url.replace(endpoint, '')
        if object_name.startswith('/'):
            object_name = object_name[1:]
        return object_name

    def _add_etag_to_manifest(self, segment_results, manifest):
        for result in segment_results:
            if 'Etag' not in result.headers:
                continue
            name = self._object_name_from_url(result.url)
            for entry in manifest:
                if entry['path'] == f'/{parse.unquote(name)}':
                    entry['etag'] = result.headers['Etag']

    def get_info(self):
        """Get infomation about the object-storage service

        The object-storage service publishes a set of capabilities that
        include metadata about maximum values and thresholds.
        """
        return self._get(_info.Info)

    def set_account_temp_url_key(self, key, secondary=False):
        """Set the temporary URL key for the account.

        :param key: Text of the key to use.
        :param bool secondary: Whether this should set the secondary key.
            (defaults to False)
        """
        account = self._get_resource(_account.Account, None)
        account.set_temp_url_key(self, key, secondary)

    def set_container_temp_url_key(self, container, key, secondary=False):
        """Set the temporary URL key for a container.

        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param key: Text of the key to use.
        :param bool secondary: Whether this should set the secondary key.
            (defaults to False)
        """
        res = self._get_resource(_container.Container, container)
        res.set_temp_url_key(self, key, secondary)

    def get_temp_url_key(self, container=None):
        """Get the best temporary url key for a given container.

        Will first try to return Temp-URL-Key-2 then Temp-URL-Key for the
        container, and if neither exist, will attempt to return Temp-URL-Key-2
        then Temp-URL-Key for the account. If neither exist, will return None.

        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        """
        temp_url_key = None
        if container:
            container_meta = self.get_container_metadata(container)
            temp_url_key = (
                container_meta.meta_temp_url_key_2
                or container_meta.meta_temp_url_key
            )
        if not temp_url_key:
            account_meta = self.get_account_metadata()
            temp_url_key = (
                account_meta.meta_temp_url_key_2
                or account_meta.meta_temp_url_key
            )
        if temp_url_key and not isinstance(temp_url_key, bytes):
            temp_url_key = temp_url_key.encode('utf8')
        return temp_url_key

    def _check_temp_url_key(self, container=None, temp_url_key=None):
        if temp_url_key:
            if not isinstance(temp_url_key, bytes):
                temp_url_key = temp_url_key.encode('utf8')
        else:
            temp_url_key = self.get_temp_url_key(container)
        if not temp_url_key:
            raise exceptions.SDKException(
                'temp_url_key was not given, nor was a temporary url key '
                'found for the account or the container.'
            )
        return temp_url_key

    def generate_form_signature(
        self,
        container,
        object_prefix,
        redirect_url,
        max_file_size,
        max_upload_count,
        timeout,
        temp_url_key=None,
    ):
        """Generate a signature for a FormPost upload.

        :param container: The value can be the name of a container or a
            :class:`~openstack.object_store.v1.container.Container` instance.
        :param object_prefix: Prefix to apply to limit all object names
            created using this signature.
        :param redirect_url: The URL to redirect the browser to after the
            uploads have completed.
        :param max_file_size: The maximum file size per file uploaded.
        :param max_upload_count: The maximum number of uploaded files allowed.
        :param timeout: The number of seconds from now to allow the form
            post to begin.
        :param temp_url_key: The X-Account-Meta-Temp-URL-Key for the account.
            Optional, if omitted, the key will be fetched from the container
            or the account.
        """
        max_file_size = int(max_file_size)
        if max_file_size < 1:
            raise exceptions.SDKException(
                'Please use a positive max_file_size value.'
            )
        max_upload_count = int(max_upload_count)
        if max_upload_count < 1:
            raise exceptions.SDKException(
                'Please use a positive max_upload_count value.'
            )
        if timeout < 1:
            raise exceptions.SDKException(
                'Please use a positive <timeout> value.'
            )
        expires = _get_expiration(timeout)

        temp_url_key = self._check_temp_url_key(
            container=container, temp_url_key=temp_url_key
        )

        res = self._get_resource(_container.Container, container)
        endpoint = parse.urlparse(self.get_endpoint())
        if isinstance(endpoint.path, bytes):
            # To keep mypy happy: the output type will be the same as the input
            # type
            path = endpoint.path.decode()
        else:
            path = endpoint.path
        path = '/'.join([path, res.name, object_prefix])

        data = f'{path}\n{redirect_url}\n{max_file_size}\n{max_upload_count}\n{expires}'
        sig = hmac.new(temp_url_key, data.encode(), sha1).hexdigest()

        return (expires, sig)

    def generate_temp_url(
        self,
        path,
        seconds,
        method,
        absolute=False,
        prefix=False,
        iso8601=False,
        ip_range=None,
        temp_url_key=None,
    ):
        """Generates a temporary URL that gives unauthenticated access to the
        Swift object.

        :param path: The full path to the Swift object or prefix if
            a prefix-based temporary URL should be generated. Example:
            /v1/AUTH_account/c/o or /v1/AUTH_account/c/prefix.
        :param seconds: time in seconds or ISO 8601 timestamp.
            If absolute is False and this is the string representation of an
            integer, then this specifies the amount of time in seconds for
            which the temporary URL will be valid.  If absolute is True then
            this specifies an absolute time at which the temporary URL will
            expire.
        :param method: A HTTP method, typically either GET or PUT, to allow
            for this temporary URL.
        :param absolute: if True then the seconds parameter is interpreted as a
            Unix timestamp, if seconds represents an integer.
        :param prefix: if True then a prefix-based temporary URL will be
            generated.
        :param iso8601: if True, a URL containing an ISO 8601 UTC timestamp
            instead of a UNIX timestamp will be created.
        :param ip_range: if a valid ip range, restricts the temporary URL to
            the range of ips.
        :param temp_url_key: The X-Account-Meta-Temp-URL-Key for the account.
            Optional, if omitted, the key will be fetched from the container or
            the account.
        :raises ValueError: if timestamp or path is not in valid format.
        :return: the path portion of a temporary URL
        """
        try:
            try:
                timestamp = float(seconds)
            except ValueError:
                formats = (
                    EXPIRES_ISO8601_FORMAT,
                    EXPIRES_ISO8601_FORMAT[:-1],
                    SHORT_EXPIRES_ISO8601_FORMAT,
                )
                for f in formats:
                    try:
                        t = time.strptime(seconds, f)
                    except ValueError:
                        continue

                    if f == EXPIRES_ISO8601_FORMAT:
                        timestamp = timegm(t)
                    else:
                        # Use local time if UTC designator is missing.
                        timestamp = int(time.mktime(t))

                    absolute = True
                    break
                else:
                    raise ValueError()
            else:
                if not timestamp.is_integer():
                    raise ValueError()
                timestamp = int(timestamp)
                if timestamp < 0:
                    raise ValueError()
        except ValueError:
            raise ValueError(
                'time must either be a whole number '
                'or in specific ISO 8601 format.'
            )

        if isinstance(path, bytes):
            try:
                path_for_body = path.decode('utf-8')
            except UnicodeDecodeError:
                raise ValueError('path must be representable as UTF-8')
        else:
            path_for_body = path

        parts = path_for_body.split('/', 4)
        if (
            len(parts) != 5
            or parts[0]
            or not all(parts[1 : (4 if prefix else 5)])
        ):
            if prefix:
                raise ValueError('path must at least contain /v1/a/c/')
            else:
                raise ValueError(
                    'path must be full path to an object e.g. /v1/a/c/o'
                )

        standard_methods = ['GET', 'PUT', 'HEAD', 'POST', 'DELETE']
        if method.upper() not in standard_methods:
            self.log.warning(
                'Non default HTTP method %s for tempurl '
                'specified, possibly an error',
                method.upper(),
            )

        expiration: ty.Union[float, int]
        if not absolute:
            expiration = _get_expiration(timestamp)
        else:
            expiration = timestamp

        hmac_parts = [
            method.upper(),
            str(expiration),
            ('prefix:' if prefix else '') + path_for_body,
        ]

        if ip_range:
            if isinstance(ip_range, bytes):
                try:
                    ip_range = ip_range.decode('utf-8')
                except UnicodeDecodeError:
                    raise ValueError('ip_range must be representable as UTF-8')
            hmac_parts.insert(0, f"ip={ip_range}")

        hmac_body = '\n'.join(hmac_parts)

        temp_url_key = self._check_temp_url_key(temp_url_key=temp_url_key)

        sig = hmac.new(
            temp_url_key, hmac_body.encode('utf-8'), sha1
        ).hexdigest()

        if iso8601:
            exp = time.strftime(
                EXPIRES_ISO8601_FORMAT, time.gmtime(expiration)
            )
        else:
            exp = str(expiration)

        temp_url = f'{path_for_body}?temp_url_sig={sig}&temp_url_expires={exp}'

        if ip_range:
            temp_url += f'&temp_url_ip_range={ip_range}'

        if prefix:
            temp_url += f'&temp_url_prefix={parts[4]}'
        # Have return type match path from caller
        if isinstance(path, bytes):
            return temp_url.encode('utf-8')
        else:
            return temp_url

    def _delete_autocreated_image_objects(
        self, container=None, segment_prefix=None
    ):
        """Delete all objects autocreated for image uploads.

        This method should generally not be needed, as shade should clean up
        the objects it uses for object-based image creation. If something goes
        wrong and it is found that there are leaked objects, this method can be
        used to delete any objects that shade has created on the user's behalf
        in service of image uploads.

        :param str container: Name of the container. Defaults to 'images'.
        :param str segment_prefix: Prefix for the image segment names to
            delete. If not given, all image upload segments present are
            deleted.
        :returns: True if deletion was succesful, else False.
        """
        if container is None:
            container = self._connection._OBJECT_AUTOCREATE_CONTAINER
        # This method only makes sense on clouds that use tasks
        if not self._connection.image_api_use_tasks:
            return False

        deleted = False
        for obj in self.objects(container, prefix=segment_prefix):
            meta = self.get_object_metadata(obj).metadata
            if meta.get(self._connection._OBJECT_AUTOCREATE_KEY) == 'true':
                self.delete_object(obj, ignore_missing=True)
                deleted = True
        return deleted

    # ========== Utilities ==========

    def wait_for_status(
        self,
        res: resource.ResourceT,
        status: str,
        failures: ty.Optional[list[str]] = None,
        interval: ty.Union[int, float, None] = 2,
        wait: ty.Optional[int] = None,
        attribute: str = 'status',
        callback: ty.Optional[ty.Callable[[int], None]] = None,
    ) -> resource.ResourceT:
        """Wait for the resource to be in a particular status.

        :param session: The session to use for making this request.
        :param resource: The resource to wait on to reach the status. The
            resource must have a status attribute specified via ``attribute``.
        :param status: Desired status of the resource.
        :param failures: Statuses that would indicate the transition
            failed such as 'ERROR'. Defaults to ['ERROR'].
        :param interval: Number of seconds to wait between checks.
        :param wait: Maximum number of seconds to wait for transition.
            Set to ``None`` to wait forever.
        :param attribute: Name of the resource attribute that contains the
            status.
        :param callback: A callback function. This will be called with a single
            value, progress. This is API specific but is generally a percentage
            value from 0-100.

        :return: The updated resource.
        :raises: :class:`~openstack.exceptions.ResourceTimeout` if the
            transition to status failed to occur in ``wait`` seconds.
        :raises: :class:`~openstack.exceptions.ResourceFailure` if the resource
            transitioned to one of the states in ``failures``.
        :raises: :class:`~AttributeError` if the resource does not have a
            ``status`` attribute
        """
        return resource.wait_for_status(
            self, res, status, failures, interval, wait, attribute, callback
        )

    def wait_for_delete(
        self,
        res: resource.ResourceT,
        interval: int = 2,
        wait: int = 120,
        callback: ty.Optional[ty.Callable[[int], None]] = None,
    ) -> resource.ResourceT:
        """Wait for a resource to be deleted.

        :param res: The resource to wait on to be deleted.
        :param interval: Number of seconds to wait before to consecutive
            checks.
        :param wait: Maximum number of seconds to wait before the change.
        :param callback: A callback function. This will be called with a single
            value, progress, which is a percentage value from 0-100.

        :returns: The resource is returned on success.
        :raises: :class:`~openstack.exceptions.ResourceTimeout` if transition
            to delete failed to occur in the specified seconds.
        """
        return resource.wait_for_delete(self, res, interval, wait, callback)

    # ========== Project Cleanup ==========
    def _get_cleanup_dependencies(self):
        return {'object_store': {'before': []}}

    def _service_cleanup(
        self,
        dry_run=True,
        client_status_queue=None,
        identified_resources=None,
        filters=None,
        resource_evaluation_fn=None,
        skip_resources=None,
    ):
        if self.should_skip_resource_cleanup(
            "container", skip_resources
        ) or self.should_skip_resource_cleanup("object", skip_resources):
            return

        is_bulk_delete_supported = False
        bulk_delete_max_per_request = 1
        try:
            caps = self.get_info()
        except exceptions.SDKException:
            pass
        else:
            bulk_delete = caps.get("bulk_delete")
            if bulk_delete is not None:
                is_bulk_delete_supported = True
                bulk_delete_max_per_request = bulk_delete.get(
                    "max_deletes_per_request", 10000
                )

        elements = []
        for cont in self.containers():
            # Iterate over objects inside container
            objects_remaining = False
            for obj in self.objects(cont):
                need_delete = self._service_cleanup_del_res(
                    self.delete_object,
                    obj,
                    dry_run=True,
                    client_status_queue=client_status_queue,
                    identified_resources=identified_resources,
                    filters=filters,
                    resource_evaluation_fn=resource_evaluation_fn,
                )
                if need_delete:
                    if dry_run:
                        continue
                    elif is_bulk_delete_supported:
                        elements.append(f"{cont.name}/{obj.name}")
                        if len(elements) >= bulk_delete_max_per_request:
                            self._bulk_delete(elements)
                            elements.clear()
                    else:
                        self.delete_object(obj, cont)
                else:
                    objects_remaining = True

            if len(elements) > 0:
                self._bulk_delete(elements)
                elements.clear()

            # Eventually delete container itself
            if not objects_remaining:
                self._service_cleanup_del_res(
                    self.delete_container,
                    cont,
                    dry_run=dry_run,
                    client_status_queue=client_status_queue,
                    identified_resources=identified_resources,
                    filters=filters,
                    resource_evaluation_fn=resource_evaluation_fn,
                )

    def _bulk_delete(self, elements):
        data = "\n".join([parse.quote(x) for x in elements])
        self.delete(
            "?bulk-delete",
            data=data,
            headers={
                'Content-Type': 'text/plain',
                'Accept': 'application/json',
            },
        )