Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion examples/cronjob_crud.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import json
import time
Expand Down
1 change: 0 additions & 1 deletion examples/duration-gep2257.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python3
# -*- coding:utf-8 -*-

"""
This example uses kubernetes.utils.duration to parse and display
Expand Down
3 changes: 1 addition & 2 deletions examples/pod_portforward.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
import select
import socket
import time

import six.moves.urllib.request as urllib_request
from urllib import request as urllib_request

from kubernetes import config
from kubernetes.client import Configuration
Expand Down
2 changes: 1 addition & 1 deletion kubernetes/base/config/exec_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from .config_exception import ConfigException


class ExecProvider(object):
class ExecProvider:
"""
Implementation of the proposal for out-of-tree client
authentication providers as described here --
Expand Down
2 changes: 1 addition & 1 deletion kubernetes/base/config/incluster_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def _join_host_port(host, port):
return template % (host, port)


class InClusterConfigLoader(object):
class InClusterConfigLoader:
def __init__(self,
token_filename,
cert_filename,
Expand Down
32 changes: 10 additions & 22 deletions kubernetes/base/config/kube_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,12 @@
import platform
import subprocess
import tempfile
import time
from collections import namedtuple

import oauthlib.oauth2
import urllib3
import yaml
from requests_oauthlib import OAuth2Session
from six import PY3

from kubernetes.client import ApiClient, Configuration
from kubernetes.config.exec_provider import ExecProvider
Expand Down Expand Up @@ -85,7 +83,7 @@ def _is_expired(expiry):
datetime.datetime.now(tz=UTC))


class FileOrData(object):
class FileOrData:
"""Utility class to read content of obj[%data_key_name] or file's
content of obj[%file_key_name] and represent it as file or data.
Note that the data is preferred. The obj[%file_key_name] will be used iff
Expand Down Expand Up @@ -151,7 +149,7 @@ def _write_file(self, force_rewrite=False):
self._data, self._temp_file_path, force_recreate=force_rewrite)


class CommandTokenSource(object):
class CommandTokenSource:
def __init__(self, cmd, args, tokenKey, expiryKey):
self._cmd = cmd
self._args = args
Expand Down Expand Up @@ -191,7 +189,7 @@ def token(self):
expiry=parse_rfc3339(data['credential']['token_expiry']))


class KubeConfigLoader(object):
class KubeConfigLoader:

def __init__(self, config_dict, active_context=None,
get_google_credentials=None,
Expand Down Expand Up @@ -363,14 +361,9 @@ def _load_oid_token(self, provider):
# https://tools.ietf.org/html/rfc7515#appendix-C
return

if PY3:
jwt_attributes = json.loads(
base64.urlsafe_b64decode(parts[1] + padding).decode('utf-8')
)
else:
jwt_attributes = json.loads(
base64.b64decode(parts[1] + padding)
)
jwt_attributes = json.loads(
base64.urlsafe_b64decode(parts[1] + padding).decode('utf-8')
)

expire = jwt_attributes.get('exp')

Expand All @@ -392,14 +385,9 @@ def _refresh_oidc(self, provider):
if 'idp-certificate-authority-data' in provider['config']:
ca_cert = tempfile.NamedTemporaryFile(delete=True)

if PY3:
cert = base64.b64decode(
provider['config']['idp-certificate-authority-data']
).decode('utf-8')
else:
cert = base64.b64decode(
provider['config']['idp-certificate-authority-data'] + "=="
)
cert = base64.b64decode(
provider['config']['idp-certificate-authority-data']
).decode('utf-8')

with open(ca_cert.name, 'w') as fh:
fh.write(cert)
Expand Down Expand Up @@ -565,7 +553,7 @@ def current_context(self):
return self._current_context.value


class ConfigNode(object):
class ConfigNode:
"""Remembers each config key's path and construct a relevant exception
message in case of missing keys. The assumption is all access keys are
present in a well-formed kube-config."""
Expand Down
11 changes: 3 additions & 8 deletions kubernetes/base/config/kube_config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

from unittest import mock
import yaml
from six import PY3, next

from kubernetes.client import Configuration

Expand Down Expand Up @@ -300,7 +299,7 @@ class TestConfigNode(BaseTestCase):
]}

def setUp(self):
super(TestConfigNode, self).setUp()
super().setUp()
self.node = ConfigNode("test_obj", self.test_obj)

def test_normal_map_array_operations(self):
Expand Down Expand Up @@ -1274,12 +1273,8 @@ def test_list_kube_config_contexts(self):
config_file=config_file)
self.assertDictEqual(self.TEST_KUBE_CONFIG['contexts'][0],
active_context)
if PY3:
self.assertCountEqual(self.TEST_KUBE_CONFIG['contexts'],
contexts)
else:
self.assertItemsEqual(self.TEST_KUBE_CONFIG['contexts'],
contexts)
self.assertCountEqual(self.TEST_KUBE_CONFIG['contexts'],
contexts)

def test_new_client_from_config(self):
config_file = self._create_temp_file(
Expand Down
9 changes: 2 additions & 7 deletions kubernetes/base/dynamic/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import six
import json

from kubernetes import watch
Expand Down Expand Up @@ -57,19 +56,15 @@ def inner(self, *args, **kwargs):
raise api_exception(e)
if serialize_response:
try:
if six.PY2:
return serializer(self, json.loads(resp.data))
return serializer(self, json.loads(resp.data.decode('utf8')))
except ValueError:
if six.PY2:
return resp.data
return resp.data.decode('utf8')
return resp

return inner


class DynamicClient(object):
class DynamicClient:
""" A kubernetes client that dynamically discovers and interacts with
the kubernetes API
"""
Expand Down Expand Up @@ -258,7 +253,7 @@ def request(self, method, path, body=None, **params):
local_var_files = {}

# Checking Accept header.
new_header_params = dict((key.lower(), value) for key, value in header_params.items())
new_header_params = {key.lower(): value for key, value in header_params.items()}
if not 'accept' in new_header_params:
header_params['Accept'] = self.client.select_header_accept([
'application/json',
Expand Down
13 changes: 5 additions & 8 deletions kubernetes/base/dynamic/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

import os
import six
import json
import logging
import hashlib
Expand All @@ -33,7 +32,7 @@
DISCOVERY_PREFIX = 'apis'


class Discoverer(object):
class Discoverer:
"""
A convenient container for storing discovered API resources. Allows
easy searching and retrieval of specific resources.
Expand All @@ -43,9 +42,7 @@ class Discoverer(object):

def __init__(self, client, cache_file):
self.client = client
default_cache_id = self.client.configuration.host
if six.PY3:
default_cache_id = default_cache_id.encode('utf-8')
default_cache_id = self.client.configuration.host.encode('utf-8')
try:
default_cachefile_name = 'osrcp-{0}.json'.format(hashlib.md5(default_cache_id, usedforsecurity=False).hexdigest())
except TypeError:
Expand All @@ -60,7 +57,7 @@ def __init_cache(self, refresh=False):
refresh = True
else:
try:
with open(self.__cache_file, 'r') as f:
with open(self.__cache_file) as f:
self._cache = json.load(f, cls=partial(CacheDecoder, self.client))
if self._cache.get('library_version') != __version__:
# Version mismatch, need to refresh cache
Expand Down Expand Up @@ -313,7 +310,7 @@ def __iter__(self):
prefix, group, version, rg.preferred)
self._cache['resources'][prefix][group][version] = rg
self.__update_cache = True
for _, resource in six.iteritems(rg.resources):
for _, resource in rg.resources.items():
yield resource
self.__maybe_write_cache()

Expand Down Expand Up @@ -397,7 +394,7 @@ def __iter__(self):
yield resource


class ResourceGroup(object):
class ResourceGroup:
"""Helper class for Discoverer container"""
def __init__(self, preferred, resources=None):
self.preferred = preferred
Expand Down
15 changes: 7 additions & 8 deletions kubernetes/base/dynamic/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pprint import pformat


class Resource(object):
class Resource:
""" Represents an API resource type, containing the information required to build urls for requests """

def __init__(self, prefix=None, group=None, api_version=None, kind=None,
Expand Down Expand Up @@ -278,7 +278,7 @@ def to_dict(self):
return d


class ResourceInstance(object):
class ResourceInstance:
""" A parsed instance of an API resource. It exists solely to
ease interaction with API objects by allowing attributes to
be accessed with '.' notation.
Expand Down Expand Up @@ -338,14 +338,14 @@ def __repr__(self):

def __getattr__(self, name):
if not '_ResourceInstance__initialised' in self.__dict__:
return super(ResourceInstance, self).__getattr__(name)
return super().__getattr__(name)
return getattr(self.attributes, name)

def __setattr__(self, name, value):
if not '_ResourceInstance__initialised' in self.__dict__:
return super(ResourceInstance, self).__setattr__(name, value)
return super().__setattr__(name, value)
elif name in self.__dict__:
return super(ResourceInstance, self).__setattr__(name, value)
return super().__setattr__(name, value)
else:
self.attributes[name] = value

Expand All @@ -359,7 +359,7 @@ def __dir__(self):
return dir(type(self)) + list(self.attributes.__dict__.keys())


class ResourceField(object):
class ResourceField:
""" A parsed instance of an API resource attribute. It exists
solely to ease interaction with API objects by allowing
attributes to be accessed with '.' notation
Expand Down Expand Up @@ -389,8 +389,7 @@ def __dir__(self):
return dir(type(self)) + list(self.__dict__.keys())

def __iter__(self):
for k, v in self.__dict__.items():
yield (k, v)
yield from self.__dict__.items()

def to_dict(self):
return self.__serialize(self)
Expand Down
7 changes: 3 additions & 4 deletions kubernetes/base/hack/boilerplate/boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import argparse
import datetime
Expand Down Expand Up @@ -60,7 +59,7 @@ def get_refs():
args.boilerplate_dir, "boilerplate.*.txt")):
extension = os.path.basename(path).split(".")[1]

ref_file = open(path, 'r')
ref_file = open(path)
ref = ref_file.read().splitlines()
ref_file.close()
refs[extension] = ref
Expand All @@ -70,7 +69,7 @@ def get_refs():

def file_passes(filename, refs, regexs):
try:
f = open(filename, 'r')
f = open(filename)
except Exception as exc:
print("Unable to open %s: %s" % (filename, exc), file=verbose_out)
return False
Expand Down Expand Up @@ -172,7 +171,7 @@ def get_files(extensions):

def get_dates():
years = datetime.datetime.now().year
return '(%s)' % '|'.join((str(year) for year in range(2014, years+1)))
return '(%s)' % '|'.join(str(year) for year in range(2014, years+1))


def get_regexs():
Expand Down
27 changes: 10 additions & 17 deletions kubernetes/base/leaderelection/leaderelection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,13 @@
import threading
from .leaderelectionrecord import LeaderElectionRecord
import logging
# if condition to be removed when support for python2 will be removed
if sys.version_info > (3, 0):
from http import HTTPStatus
else:
import httplib
from http import HTTPStatus

logger = logging.getLogger("leaderelection")

"""
This package implements leader election using an annotation in a Kubernetes object.
The onstarted_leading function is run in a thread and when it returns, if it does
The onstarted_leading function is run in a thread and when it returns, if it does
it might not be safe to run it again in a process.

At first all candidates are considered followers. The one to create a lock or update
Expand Down Expand Up @@ -118,17 +115,13 @@ def try_acquire_or_renew(self):

# A lock is not created with that name, try to create one
if not lock_status:
# To be removed when support for python2 will be removed
if sys.version_info > (3, 0):
if json.loads(old_election_record.body)['code'] != HTTPStatus.NOT_FOUND:
logger.info("Error retrieving resource lock {} as {}".format(self.election_config.lock.name,
old_election_record.reason))
return False
else:
if json.loads(old_election_record.body)['code'] != httplib.NOT_FOUND:
logger.info("Error retrieving resource lock {} as {}".format(self.election_config.lock.name,
old_election_record.reason))
return False
if json.loads(old_election_record.body)[
'code'] != HTTPStatus.NOT_FOUND:
logger.info(
"Error retrieving resource lock {} as {}".format(
self.election_config.lock.name,
old_election_record.reason))
return False

logger.info("{} is trying to create a lock".format(leader_election_record.holder_identity))
create_status = self.election_config.lock.create(name=self.election_config.lock.name,
Expand Down
Loading