Skip to content
This repository has been archived by the owner on Mar 13, 2022. It is now read-only.

Commit

Permalink
Implement rfc3339 balanced formatter/parser for kube-config use
Browse files Browse the repository at this point in the history
  • Loading branch information
mbohlool committed Jul 25, 2017
1 parent 253d937 commit 5d0b367
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 311 deletions.
80 changes: 80 additions & 0 deletions config/dateutil.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Copyright 2017 The Kubernetes Authors.
#
# 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.

import datetime
import math
import re


class TimezoneInfo(datetime.tzinfo):
def __init__(self, h, m):
self._name = "UTC"
if h != 0 and m != 0:
self._name += "%+03d:%2d" % (h, m)
self._delta = datetime.timedelta(hours=h, minutes=math.copysign(m, h))

def utcoffset(self, dt):
return self._delta

def tzname(self, dt):
return self._name

def dst(self, dt):
return datetime.timedelta(0)


UTC = TimezoneInfo(0, 0)

# ref https://www.ietf.org/rfc/rfc3339.txt
_re_rfc3339 = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)" # Full time
r"[ Tt]" # Separator
r"(\d\d):(\d\d):(\d\d)([.,]\d+)?" # partial-time
r"([zZ ]|[-+]\d\d?:\d\d)?", # time-offset
re.VERBOSE + re.IGNORECASE)
_re_timezone = re.compile(r"([-+])(\d\d?):?(\d\d)?")


def parse_rfc3339(s):
if type(s) == datetime.datetime:
# no need to parse it, just make sure it has a timezone.
if not s.tzinfo:
return s.replace(tzinfo=UTC)
return s
groups = _re_rfc3339.search(s).groups()
dt = [0] * 7
for x in range(6):
dt[x] = int(groups[x])
if groups[6] is not None:
dt[6] = int(groups[6])
tz = UTC
if groups[7] is not None and groups[7] != 'Z' and groups[7] != 'z':
tz_groups = _re_timezone.search(groups[7]).groups()
hour = int(tz_groups[1])
minute = 0
if tz_groups[0] == "-":
hour *= -1
if tz_groups[2]:
minute = int(tz_groups[2])
tz = TimezoneInfo(hour, minute)
return datetime.datetime(
year=dt[0], month=dt[1], day=dt[2],
hour=dt[3], minute=dt[4], second=dt[5],
microsecond=dt[6], tzinfo=tz)


def format_rfc3339(date_time):
if date_time.tzinfo is None:
date_time = date_time.replace(tzinfo=UTC)
date_time = date_time.astimezone(UTC)
return date_time.strftime('%Y-%m-%dT%H:%M:%SZ')
23 changes: 8 additions & 15 deletions config/kube_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,17 @@
import datetime
import os
import tempfile
import time

import google.auth
import google.auth.transport.requests
import urllib3
import yaml

from kubernetes.client import ApiClient, ConfigurationObject, configuration

from .dateutil import parse_rfc3339, format_rfc3339, UTC
from .config_exception import ConfigException
from .rfc3339 import tf_from_timestamp, timestamp_from_tf

EXPIRY_SKEW_PREVENTION_DELAY_S = 600
EXPIRY_SKEW_PREVENTION_DELAY = datetime.timedelta(minutes=5)
KUBE_CONFIG_DEFAULT_LOCATION = os.environ.get('KUBECONFIG', '~/.kube/config')
_temp_files = {}

Expand Down Expand Up @@ -60,14 +58,8 @@ def _create_temp_file_with_content(content):


def _is_expired(expiry):
tf = tf_from_timestamp(expiry)
n = time.time()
return tf + EXPIRY_SKEW_PREVENTION_DELAY_S <= n


def _datetime_to_rfc3339(dt):
tf = (dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
return timestamp_from_tf(tf, time_offset="Z")
return ((parse_rfc3339(expiry) + EXPIRY_SKEW_PREVENTION_DELAY) <=
datetime.datetime.utcnow().replace(tzinfo=UTC))


class FileOrData(object):
Expand Down Expand Up @@ -200,6 +192,7 @@ def _load_gcp_token(self):
('expiry' in provider['config'] and
_is_expired(provider['config']['expiry']))):
# token is not available or expired, refresh it
print "Refreshing gcp token"
self._refresh_gcp_token()

self.token = "Bearer %s" % provider['config']['access-token']
Expand All @@ -211,7 +204,7 @@ def _refresh_gcp_token(self):
provider = self._user['auth-provider']['config']
credentials = self._get_google_credentials()
provider.value['access-token'] = credentials.token
provider.value['expiry'] = _datetime_to_rfc3339(credentials.expiry)
provider.value['expiry'] = format_rfc3339(credentials.expiry)
if self._config_persister:
self._config_persister(self._config.value)

Expand Down Expand Up @@ -353,8 +346,8 @@ def load_kube_config(config_file=None, context=None,
from config file will be used.
:param client_configuration: The kubernetes.client.ConfigurationObject to
set configs to.
:param persist_config: If True and config changed (e.g. GCP token refresh)
the provided config file will be updated.
:param persist_config: IF True, config file will be updated when changed
(e.g GCP token refresh).
"""

if config_file is None:
Expand Down
1 change: 0 additions & 1 deletion config/rfc3339.MD

This file was deleted.

Loading

0 comments on commit 5d0b367

Please sign in to comment.