Merge pull request #586 from tobegit3hub/add_harbor_py

Add harbor-py project
This commit is contained in:
Daniel Jiang 2016-07-26 18:12:19 +08:00 committed by GitHub
commit 1c9dd6cc75
30 changed files with 1179 additions and 0 deletions

94
contrib/sdk/harbor-py/.gitignore vendored Normal file
View File

@ -0,0 +1,94 @@
# Temporary files
files.txt
*.swp
*~
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View File

@ -0,0 +1,69 @@
## Introduction
[harbor](https://github.com/vmware/harbor) is the enterprise-class registry server for docker distribution.
[harbor-py](https://github.com/tobegit3hub/harbor-py) is the native and compatible python SDK for harbor. The supported APIs are list below.
- [x] Projects APIs
- [x] [Get projects](./examples/get_projects.py)
- [x] [Create project](./examples/create_project.py)
- [x] [Check project exist](./examples/check_project_exist.py)
- [x] [Set project publicity](./examples/set_project_publicity.py)
- [x] [Get project id from name](./examples/get_project_id_from_name.py)
- [ ] Get project access logs
- [ ] Get project member
- [ ] Get project and user member
- [x] Users APIs
- [x] [Get users](./examples/get_users.py)
- [x] [Create user](./examples/create_user.py)
- [x] [Update user profile](./examples/update_user_profile.py)
- [x] [Delete user](./examples/delete_user.py)
- [x] [Change password](./examples/change_password.py)
- [x] [Promote as admin](./examples/promote_as_admin.py)
- [x] Repositories APIs
- [x] [Get repositories](./examples/get_repositories.py)
- [x] [Delete repository](./examples/delete_repository.py)
- [x] [Get repository tags](./examples/get_repository_tags.py)
- [x] [Get repository manifests](./examples/get_repository_manifests.py)
- [x] Others APIs
- [x] [Search](./examples/search.py)
- [x] [Get statistics](./examples/get_statistics.py)
- [x] [Get top accessed repositories](./examples/get_top_accessed_repositories.py)
- [x] [Get logs](./examples/get_logs.py)
## Installation
```
pip install harbor-py
```
## Usage
```
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
client.get_projects()
client.get_users()
client.get_statistics()
client.get_top_accessed_repositories()
client.search("library")
```
For more usage, please refer to the [examples](./examples/).
## Contribution
If you have any suggestion, feel free to submit [issues](https://github.com/tobegit3hub/harbor-py/issues) or send [pull-requests](https://github.com/tobegit3hub/harbor-py/pulls) for `harbor-py`.
Publish `harbor-py` package to [pypi](https://pypi.python.org/pypi/harbor-py/) server with the following commands.
```
python setup.py register -r pypi
python setup.py sdist upload -r pypi
```

View File

@ -0,0 +1,18 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Change password
user_id = 2
old_password = "test-password"
new_password = "new-password"
client.change_password(user_id, old_password, new_password)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Check if project exists
project_name = "test-project"
print(client.check_project_exist(project_name))

View File

@ -0,0 +1,17 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Create project
project_name = "test-project"
is_public = True
client.create_project(project_name, is_public)

View File

@ -0,0 +1,20 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Create user
username = "test-username"
email = "test-email@gmail.com"
password = "test-password"
realname = "test-realname"
comment = "test-comment"
client.create_user(username, email, password, realname, comment)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Delete repository
repo_name = "library/cirros"
client.delete_repository(repo_name)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Delete user
user_id = 2
print(client.delete_user(user_id))

View File

@ -0,0 +1,15 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get logs
print(client.get_logs())

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get project id from name
project_name = "library"
print(client.get_project_id_from_name(project_name))

View File

@ -0,0 +1,15 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get all projects
print(client.get_projects())

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get all repositories
project_id = 1
print(client.get_repositories(project_id))

View File

@ -0,0 +1,17 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get repository manifests
repo_name = "library/cirros"
tag = "latest"
client.get_repository_manifests(repo_name, tag)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get repository tags
repo_name = "library/cirros"
client.get_repository_tags(repo_name)

View File

@ -0,0 +1,13 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
print(client.get_statistics())

View File

@ -0,0 +1,19 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get top accessed respositories
print(client.get_top_accessed_repositories())
# Get top accessed respositories with count
count = 1
print(client.get_top_accessed_repositories(count))

View File

@ -0,0 +1,15 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Get all users
print(client.get_users())

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Promote as admin
user_id = 2
client.promote_as_admin(user_id)

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Search with query string
query_string = "library"
print(client.search(query_string))

View File

@ -0,0 +1,17 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Set project publicity
project_id = 1
is_public = True
client.set_project_publicity(project_id, is_public)

View File

@ -0,0 +1,12 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)

View File

@ -0,0 +1,19 @@
#!/usr/bin/env python
import sys
sys.path.append("../")
from harborclient import harborclient
host = "127.0.0.1"
user = "admin"
password = "Harbor12345"
client = harborclient.HarborClient(host, user, password)
# Update user profile
user_id = 2
email = "new@gmail.com"
realname = "new_realname"
comment = "new_comment"
client.update_user_profile(user_id, email, realname, comment)

View File

@ -0,0 +1,5 @@
#!/bin/bash
set -x
find ./ -name "*.py" |xargs sudo yapf -i

View File

@ -0,0 +1,371 @@
#!/usr/bin/env python
import requests
import simplejson
import logging
logging.basicConfig(level=logging.INFO)
class HarborClient(object):
def __init__(self, host, user, password, protocol="http"):
self.host = host
self.user = user
self.password = password
self.protocol = protocol
self.session_id = self.login()
def __del__(self):
self.logout()
def login(self):
login_data = requests.post('%s://%s/login' %
(self.protocol, self.host),
data={'principal': self.user,
'password': self.password})
if login_data.status_code == 200:
session_id = login_data.cookies.get('beegosessionID')
logging.debug("Successfully login, session id: {}".format(
session_id))
return session_id
else:
logging.error("Fail to login, please try again")
return None
def logout(self):
requests.get('%s://%s/logout' % (self.protocol, self.host),
cookies={'beegosessionID': self.session_id})
logging.debug("Successfully logout")
# Get project id
def get_project_id_from_name(self, project_name):
registry_data = requests.get(
'%s://%s/api/projects?project_name=%s' %
(self.protocol, self.host, project_name),
cookies={'beegosessionID': self.session_id})
if registry_data.status_code == 200 and registry_data.json():
project_id = registry_data.json()[0]['project_id']
logging.debug(
"Successfully get project id: {}, project name: {}".format(
project_id, project_name))
return project_id
else:
pritn("Fail to get project id from project name", project_name)
return None
# GET /search
def search(self, query_string):
result = None
path = '%s://%s/api/search?q=%s' % (self.protocol, self.host,
query_string)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug("Successfully get search result: {}".format(result))
else:
logging.error("Fail to get search result")
return result
# GET /projects
def get_projects(self, project_name=None, is_public=None):
# TODO: support parameter
result = None
path = '%s://%s/api/projects' % (self.protocol, self.host)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug("Successfully get projects result: {}".format(
result))
else:
logging.error("Fail to get projects result")
return result
# HEAD /projects
def check_project_exist(self, project_name):
result = False
path = '%s://%s/api/projects?project_name=%s' % (
self.protocol, self.host, project_name)
response = requests.head(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = True
logging.debug(
"Successfully check project exist, result: {}".format(result))
elif response.status_code == 404:
result = False
logging.debug(
"Successfully check project exist, result: {}".format(result))
else:
logging.error("Fail to check project exist")
return result
# POST /projects
def create_project(self, project_name, is_public=False):
result = False
path = '%s://%s/api/projects' % (self.protocol, self.host)
request_body = simplejson.dumps({'project_name': project_name,
'public': is_public})
response = requests.post(path,
cookies={'beegosessionID': self.session_id},
data=request_body)
if response.status_code == 201 or response.status_code == 500:
# TODO: the response return 500 sometimes
result = True
logging.debug(
"Successfully create project with project name: {}".format(
project_name))
else:
logging.error(
"Fail to create project with project name: {}, response code: {}".format(
project_name, response.status_code))
return result
# PUT /projects/{project_id}/publicity
def set_project_publicity(self, project_id, is_public):
result = False
path = '%s://%s/api/projects/%s/publicity?project_id=%s' % (
self.protocol, self.host, project_id, project_id)
request_body = simplejson.dumps({'public': is_public})
response = requests.put(path,
cookies={'beegosessionID': self.session_id},
data=request_body)
if response.status_code == 200:
result = True
logging.debug(
"Success to set project id: {} with publicity: {}".format(
project_id, is_public))
else:
logging.error(
"Fail to set publicity to project id: {} with status code: {}".format(
project_id, response.status_code))
return result
# GET /statistics
def get_statistics(self):
result = None
path = '%s://%s/api/statistics' % (self.protocol, self.host)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug("Successfully get statistics: {}".format(result))
else:
logging.error("Fail to get statistics result")
return result
# GET /users
def get_users(self, user_name=None):
# TODO: support parameter
result = None
path = '%s://%s/api/users' % (self.protocol, self.host)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug("Successfully get users result: {}".format(result))
else:
logging.error("Fail to get users result")
return result
# POST /users
def create_user(self, username, email, password, realname, comment):
result = False
path = '%s://%s/api/users' % (self.protocol, self.host)
request_body = simplejson.dumps({'username': username,
'email': email,
'password': password,
'realname': realname,
'comment': comment})
response = requests.post(path,
cookies={'beegosessionID': self.session_id},
data=request_body)
if response.status_code == 201:
result = True
logging.debug("Successfully create user with username: {}".format(
username))
else:
logging.error(
"Fail to create user with username: {}, response code: {}".format(
username, response.status_code))
return result
# PUT /users/{user_id}
def update_user_profile(self, user_id, email, realname, comment):
# TODO: support not passing comment
result = False
path = '%s://%s/api/users/%s?user_id=%s' % (self.protocol, self.host,
user_id, user_id)
request_body = simplejson.dumps({'email': email,
'realname': realname,
'comment': comment})
response = requests.put(path,
cookies={'beegosessionID': self.session_id},
data=request_body)
if response.status_code == 200:
result = True
logging.debug(
"Successfully update user profile with user id: {}".format(
user_id))
else:
logging.error(
"Fail to update user profile with user id: {}, response code: {}".format(
user_id, response.status_code))
return result
# DELETE /users/{user_id}
def delete_user(self, user_id):
result = False
path = '%s://%s/api/users/%s?user_id=%s' % (self.protocol, self.host,
user_id, user_id)
response = requests.delete(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = True
logging.debug("Successfully delete user with id: {}".format(
user_id))
else:
logging.error("Fail to delete user with id: {}".format(user_id))
return result
# PUT /users/{user_id}/password
def change_password(self, user_id, old_password, new_password):
result = False
path = '%s://%s/api/users/%s/password?user_id=%s' % (
self.protocol, self.host, user_id, user_id)
request_body = simplejson.dumps({'old_password': old_password,
'new_password': new_password})
response = requests.put(path,
cookies={'beegosessionID': self.session_id},
data=request_body)
if response.status_code == 200:
result = True
logging.debug(
"Successfully change password for user id: {}".format(user_id))
else:
logging.error("Fail to change password for user id: {}".format(
user_id))
return result
# PUT /users/{user_id}/sysadmin
def promote_as_admin(self, user_id):
# TODO: always return 404, need more test
result = False
path = '%s://%s/api/users/%s/sysadmin?user_id=%s' % (
self.protocol, self.host, user_id, user_id)
response = requests.put(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = True
logging.debug(
"Successfully promote user as admin with user id: {}".format(
user_id))
else:
logging.error(
"Fail to promote user as admin with user id: {}, response code: {}".format(
user_id, response.status_code))
return result
# GET /repositories
def get_repositories(self, project_id, query_string=None):
# TODO: support parameter
result = None
path = '%s://%s/api/repositories?project_id=%s' % (
self.protocol, self.host, project_id)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug(
"Successfully get repositories with id: {}, result: {}".format(
project_id, result))
else:
logging.error("Fail to get repositories result with id: {}".format(
project_id))
return result
# DELETE /repositories
def delete_repository(self, repo_name, tag=None):
# TODO: support to check tag
# TODO: return 200 but the repo is not deleted, need more test
result = False
path = '%s://%s/api/repositories?repo_name=%s' % (self.protocol,
self.host, repo_name)
response = requests.delete(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = True
logging.debug("Successfully delete repository: {}".format(
repo_name))
else:
logging.error("Fail to delete repository: {}".format(repo_name))
return result
# Get /repositories/tags
def get_repository_tags(self, repo_name):
result = None
path = '%s://%s/api/repositories/tags?repo_name=%s' % (
self.protocol, self.host, repo_name)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug(
"Successfully get tag with repo name: {}, result: {}".format(
repo_name, result))
else:
logging.error("Fail to get tags with repo name: {}".format(
repo_name))
return result
# GET /repositories/manifests
def get_repository_manifests(self, repo_name, tag):
result = None
path = '%s://%s/api/repositories/manifests?repo_name=%s&tag=%s' % (
self.protocol, self.host, repo_name, tag)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug(
"Successfully get manifests with repo name: {}, tag: {}, result: {}".format(
repo_name, tag, result))
else:
logging.error(
"Fail to get manifests with repo name: {}, tag: {}".format(
repo_name, tag))
return result
# GET /repositories/top
def get_top_accessed_repositories(self, count=None):
result = None
path = '%s://%s/api/repositories/top' % (self.protocol, self.host)
if count:
path += "?count=%s" % (count)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug(
"Successfully get top accessed repositories, result: {}".format(
result))
else:
logging.error("Fail to get top accessed repositories")
return result
# GET /logs
def get_logs(self, lines=None, start_time=None, end_time=None):
result = None
path = '%s://%s/api/logs' % (self.protocol, self.host)
response = requests.get(path,
cookies={'beegosessionID': self.session_id})
if response.status_code == 200:
result = response.json()
logging.debug("Successfully get logs")
else:
logging.error("Fail to get logs and response code: {}".format(
response.status_code))
return result

View File

@ -0,0 +1,3 @@
#!/usr/bin/env python
import harborclient

View File

@ -0,0 +1 @@
requests>2.2.0

View File

@ -0,0 +1,103 @@
""" The missing harbor python SDK
See: https://github.com/tobegit3hub/harbor-py
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
setup(
name='harbor-py',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.2.0',
description='The missing harbor python SDK',
# The project's main homepage.
url='https://github.com/tobegit3hub/harbor-py',
# Author details
author='tobe',
author_email='tobeg3oogle@gmail.com',
# Choose your license
license='Apache Software',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: Apache Software License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?
keywords='docker registry distribution harbor python sdk',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
#packages=find_packages(exclude=['contrib', 'docs', 'tests']),
packages=['harborclient'],
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
#install_requires=['peppercorn'],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
#extras_require={
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
#},
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
#package_data={
# 'sample': ['package_data.dat'],
#},
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
# http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa
# In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
#data_files=[('my_data', ['data/data_file'])],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
#entry_points={
# 'console_scripts': [
# 'harbor=harborclient:main',
# ],
#},
)

View File

@ -0,0 +1,7 @@
#!/bin/sh
set -x
set -e
python setup.py install --record files.txt
cat files.txt | xargs rm -rf