Skip to content

Commit

Permalink
Merge pull request #9 from akamai/NEW_FEATURE
Browse files Browse the repository at this point in the history
Adding support for new unified API credentials and Video Manager
  • Loading branch information
vreddhi authored Jun 15, 2021
2 parents 2d3e507 + 7f3218f commit de115b8
Show file tree
Hide file tree
Showing 8 changed files with 348 additions and 230 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ and compiling it yourself.
akamai image-manager [global flags] --policy-set POLICY-SET command
```

```
akamai video-manager [global flags] --policy-set POLICY-SET command
```

## Global Flags
- `--edgerc value` — Location of the credentials file (default: user's directory like "/Users/jgarza") [$AKAMAI_EDGERC]
- `--section value` — Section of the credentials file (default: "default") [$AKAMAI_EDGERC_SECTION]
Expand Down Expand Up @@ -68,6 +72,23 @@ optional arguments:
Output type {json, text}. Default is text
```

```
$ akamai video-manager --section default --policy-set example_com list-policies --help
usage: akamai-video-manager list-policies [-h] [--network network]
[--output-type json/text]
optional arguments:
-h, --help show this help message and exit
--network network, -n network
Network to list from (staging, production or both).
Default is both
--output-type json/text, -t json/text
Output type {json, text}. Default is text
```

#### Below examples are valid for video-manager as well

#### List of all policies (default is both networks and text output)
Retrieve a list of all policies in human readable format using a specific instance of the Image Manager behavior available on both networks:

Expand Down
250 changes: 27 additions & 223 deletions bin/akamai-image-manager
Original file line number Diff line number Diff line change
Expand Up @@ -23,227 +23,31 @@
"""
# Libraries commmon to python 2 and 3
from __future__ import print_function
import sys
import os
import logging
import random
import re
import requests
import json
import urllib
import texttable as tt
from future import standard_library
from future.builtins import next
from future.builtins import object
from http_calls import EdgeGridHttpCaller
from akamai.edgegrid import EdgeGridAuth
from config import EdgeGridConfig
from subprocess import call
standard_library.install_aliases()
#! /usr/bin/env python

""" Copyright 2021 Akamai Technologies, Inc. All Rights Reserved.
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.
****************************************************************
* Image Manager CLI module by Javier Garza (jgarza@akamai.com) *
* Based on https://github.com/brassic-lint/cli-imgman *
* from Gareth Hughes *
****************************************************************
"""

import common

if sys.version_info[0] >= 3:
# python3
from urllib.parse import urljoin
else:
# python2.7
from urlparse import urljoin

session = requests.Session()
debug = False
verbose = False
cache = False
format = "json"
section_name = "default"
network = "production"

# If all parameters are set already, use them. Otherwise
# use the config
config = EdgeGridConfig({"verbose": False}, section_name)

if hasattr(config, "debug") and config.debug:
debug = True

if hasattr(config, "verbose") and config.verbose:
verbose = True

if hasattr(config, "cache") and config.cache:
cache = True


# Set the config options
session.auth = EdgeGridAuth(
client_token=config.client_token,
client_secret=config.client_secret,
access_token=config.access_token
)

if hasattr(config, 'headers'):
session.headers.update(config.headers)

session.headers.update({'User-Agent': "AkamaiCLI"})

baseurl_prd = '%s://%s/' % ('https', config.host)
baseurl_stg = '%s://%s/' % ('https', config.host.replace(".imaging.",
".imaging-staging."))

prdHttpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl_prd)
stgHttpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl_stg)


def listPolicies(lunaToken, network):
""" List the policies on a given network """
session.headers.update({'Luna-Token': lunaToken})

if network == "staging":
listResult = stgHttpCaller.getResult("/imaging/v2/policies")
if network == "production":
listResult = prdHttpCaller.getResult("/imaging/v2/policies")

return(listResult)


def getPolicy(lunaToken, policyName, network):
""" Gets a specific policy on a given network in JSON format """
session.headers.update({'Luna-Token': lunaToken})

print("Retrieving: " + policyName + " from " + network)

if network == "staging" :
policyResult = stgHttpCaller.getResult("/imaging/v2/policies/"
+ policyName)
else:
policyResult = prdHttpCaller.getResult("/imaging/v2/policies/"
+ policyName)

return(policyResult)


def setPolicy(lunaToken, policyName, policyData, network):
""" Creates or updates a policy in a given network (or both) out of
a JSON input file """
session.headers.update({'Luna-Token': lunaToken, "Content-Type":
"application/json"})

print("Updating " + policyName)

if network == "staging":
policyResult = stgHttpCaller.putResult("/imaging/v2/policies/"
+ policyName, policyData)
else:
policyResult = prdHttpCaller.putResult("/imaging/v2/policies/"
+ policyName, policyData)

return(policyResult)


def deletePolicy(lunaToken, policyName, network):
""" Deletes a policy in a given network (or both) """
session.headers.update({'Luna-Token': lunaToken})

print("deleting " + policyName + " on " + network + " networks")
if network == "both":
policyResultStg = stgHttpCaller.deleteResult("/imaging/v2/policies/"
+ policyName)
policyResultPrd = prdHttpCaller.deleteResult("/imaging/v2/policies/"
+ policyName)
policyResult = {"staging": policyResultStg, "production":
policyResultPrd}
if network == "staging":
policyResultStg = stgHttpCaller.deleteResult("/imaging/v2/policies/"
+ policyName)
policyResult = {"staging": policyResultStg}
if network == "production":
policyResultPrd = prdHttpCaller.deleteResult("/imaging/v2/policies/"
+ policyName)
policyResult = {"production": policyResultPrd}

return(policyResult)


def formatOutput(policyList, output_type):
""" Formats the output on a given format (json or text) """
if output_type == "json":
# Let's print the JSON
print(json.dumps(policyList, indent=2))

if output_type == "text":
# Iterate over the dictionary and print the selected information
ParentTable = tt.Texttable()
ParentTable.set_cols_width([30,25,25])
ParentTable.set_cols_align(['c','c','c'])
ParentTable.set_cols_valign(['m','m','m'])
Parentheader = ['Policy name','Date Created','User']
ParentTable.header(Parentheader)
for my_item in policyList["items"]:
Parentrow = [ my_item["id"], my_item["dateCreated"], my_item["user"]]
ParentTable.add_row(Parentrow)
MainParentTable = ParentTable.draw()
print(MainParentTable)
"""print('%30s | %25s | %20s' % ("Policy name", "Date Created", "User"))
print('='*81)
for my_item in policyList["items"]:
print('%30s | %25s | %20s' % (my_item["id"],
my_item["dateCreated"],
my_item["user"]))
"""


def main():
""" Processes the right command (list, get, set or delete) """
if config.command == "list-policies":
# Get the list of policies in JSON format for the given network
print("Policy:", config.policy_set, "\tNetwork:", config.network,
"\tOutput:", config.output_type)

if config.network == "both":
print("\nSTAGING:")
policyList = listPolicies(config.policy_set, "staging")
formatOutput(policyList, config.output_type)
print("\nPRODUCTION:")
policyList = listPolicies(config.policy_set, "production")
formatOutput(policyList, config.output_type)
else:
policyList = listPolicies(config.policy_set, config.network)
formatOutput(policyList, config.output_type)

elif config.command == "get-policy":

policyDetail = getPolicy(config.policy_set, config.name,
config.network)
print("Policy:", config.policy_set, "\tNetwork:", config.network,
"\tOutput:", config.output_file)
if hasattr(config, 'output_file') and config.output_file is not None:
config.output_file.write(json.dumps(policyDetail, indent=2))
config.output_file.close()
else:
print(json.dumps(policyDetail, indent=2))

elif config.command == "set-policy":
policyJSON = config.input_file.read()
config.input_file.close()
if config.network == "both":
print("STAGING:")
policyDetail = setPolicy(config.policy_set, config.name,
policyJSON, "staging")
print(json.dumps(policyDetail, indent=2))
print("PRODUCTION:")
policyDetail = setPolicy(config.policy_set, config.name,
policyJSON, "production")
print(json.dumps(policyDetail, indent=2))
else:
print(config.network)
policyDetail = setPolicy(config.policy_set, config.name,
policyJSON, config.network)
print(json.dumps(policyDetail, indent=2))

elif config.command == "delete-policy":
cmdResult = deletePolicy(config.policy_set, config.name,
config.network)
print(json.dumps(cmdResult, indent=2))
else:
config.parser.print_help(sys.stderr)


if __name__ == "__main__":
main()
common.main()
28 changes: 28 additions & 0 deletions bin/akamai-video-manager
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#! /usr/bin/env python

""" Copyright 2021 Akamai Technologies, Inc. All Rights Reserved.
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.
****************************************************************
* Image Manager CLI module by Javier Garza (jgarza@akamai.com) *
* Based on https://github.com/brassic-lint/cli-imgman *
* from Gareth Hughes *
****************************************************************
"""

import common

common.main()
Loading

0 comments on commit de115b8

Please sign in to comment.