azure-cli icon indicating copy to clipboard operation
azure-cli copied to clipboard

Incomplete round-trip serialization of timedelta

Open dragonfly91 opened this issue 9 years ago • 11 comments

Description

Thanks @DheerendraRathor for helping with the debugging of the issue.

Our service is returning the string 'PT34.8179112S' for duration. This is getting deserialized into the duration object correctly. Then we are trying to return this object back to IO stream where the duration object seems to be serialized to the string '0:00:34.817911'. Then we are passing this serialized string to the next command. Here we try to deserialize this string again and the code fails in isoduration.py in parsing. Essentially, we're not able to "deserialize - serialize - deserialize" the duration object.

This is an investigation by my colleague @DheerendraRathor about the issue:

  1. Autorest deserializes duration to python timedelta (It expects ISO 8601 due to Microsoft standards) https://github.com/Azure/msrest-for-python/blob/master/msrest/serialization.py#L1062 def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid. """ try: duration = isodate.parse_duration(attr) except(ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise_with_traceback(DeserializationError, msg, err) else: return duration

            isodate.parse_duration returns python datetime.timedelta
    
  2. Now as Anudeep pointed out timedelta is directly converted to str during todict conversion: https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py#L166 During this conversion ISO 8601 format of duration is lost as Python str conversion of timedelta is “x days, h:mm:ss”

str(timedelta(days=2, weeks=1, hours=2)) '9 days, 2:00:00' str(timedelta(hours=1, minutes=10)) '1:10:00'

  1. Now as Anudeep is trying to deserialize it again, it will fail as python str(timedelta) is not ISO 8601 and msrest deserializers expects ISO 8601 format.

Possible solution:

  • Use isodate.duration_isoformat method to retain ISO 8601 format for duration while creating dictionary.
  • Leverage msrest Serializer for dictionary conversion https://github.com/Azure/msrest-for-python/blob/master/msrest/serialization.py#L614 Which is internally using isodate.duration_isoformat

Environment summary

Install Method: How did you install the CLI? (e.g. pip, interactive script, apt-get, Docker, MSI, nightly)
Cloned the git repo

CLI Version: What version of the CLI and modules are installed? (Use az --version)
Answer here:

OS Version: What OS and version are you using?
Windows 10

Shell Type: What shell are you using? (e.g. bash, cmd.exe, Bash on Windows)
cmd.exe

dragonfly91 avatar Aug 03 '17 19:08 dragonfly91

@tjprescott @derekbekoe replace:

    elif isinstance(obj, timedelta):
        return str(obj)

by

    elif isinstance(obj, timedelta):
        return msrest.serialization.Serializer.serialize_duration(obj)

to be sure you are consistent with msrest for serialisation/deserialisation.

Of course, I can't ensure this will be the expected format if underlying SDK does not come from Autorest...

lmazuel avatar Aug 03 '17 20:08 lmazuel

This is now a part of the common core (knack) and as such, relying on msrest is probably not what we want to do (@derekbekoe, thoughts?)

What command module is this for? What is the scenario? Are you trying to PUT the output of a GET? What format do you expect for your create/update command in the CLI? I would assume something more user friendly than 'PT34.8179112S'.

If this only affects this command, then the most direct fix (that is guaranteed not to impact or regress anything that currently exists) would be to use an output transformer to control the string format of the duration object, and then ensure that the input format for that argument on the create/update side matches using a type kwarg or validator.

tjprescott avatar Aug 03 '17 20:08 tjprescott

As part of looking at this, we should also make sure that we support round-tripping of the to/from strings for all types that AutoRest supports. In this case, it looks like we missed duration.

johanste avatar Aug 03 '17 20:08 johanste

@tjprescott note that msrest is not Azure specific (msrestazure is), but I understand if you want knack msrest agnostic :) This msrest method uses internally:

isodate.duration_isoformat(attr)

This will be you a ISO8601 string, which I think is better anyway than a simple str call on timedelta.

lmazuel avatar Aug 03 '17 20:08 lmazuel

@johanste I'm not sure what you mean here. Date/time formats in the CLI almost always (or just plain always) have a custom type or a validator that is used to convert a user-friendly string format (whatever the command author chooses) into the usually obtuse formats required by anything with ISO in front of it. 😀 So the "round-trippiness" of the parameter would be the responsibility of the command author.

tjprescott avatar Aug 03 '17 20:08 tjprescott

Since we own the conversion to string, we should also provide a core from string callable that can be used for the type parameter.

johanste avatar Aug 03 '17 20:08 johanste

Hi, any update on this?

dragonfly91 avatar Aug 08 '17 09:08 dragonfly91

Hi @dragonfly91 there's no progress as far as any changes to core are concerned, as doing so would change the output format of many commands and (were we to simply preserve the ISO format) degrade the UX by outputting something that is not human friendly.

You can use the type kwarg to supply a callable that converts the human-readable string into ISO format (or the actual duration object). get_datetime_type is an example in the storage module's _params.py file for how to do this.

tjprescott avatar Aug 08 '17 16:08 tjprescott

add to S165.

yonzhan avatar Dec 23 '19 07:12 yonzhan

Hi @dragonfly91 , have you tried the proposal provided by @tjprescott , is there any update?

qianwens avatar Feb 17 '20 04:02 qianwens

Close this issue since there is no response. Please help create a new issue if you still have questions.

qianwens avatar Feb 28 '20 08:02 qianwens