Mini Shell
# -*- coding: utf-8 -*-
# CL LICENSE CHECK python lib
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
# CLASSES:
#
# LisenceData - main class for CL licence check
# : check_license
# : get_ip
# : date_format
# : open_letter_template
# : format_letter
#
# FUNCTIONS:
#
# License update cron : update_license_timestamp_file
# License update new key : update license with new key
# Check license : check_license
# Return Last License check date : last_license_check
# Return Template to display : return_template_to_display
from __future__ import print_function
from __future__ import absolute_import
from future.moves.urllib import request, error
import os, sys, subprocess, struct, time, datetime, socket
import cldetectlib as detect
from clcommon.utils import mod_makedirs
RHN_CHECK_FILE = '/usr/sbin/rhn_check'
RHN_UPDATE_NEW_KEY = '/usr/sbin/rhnreg_ks'
LICENSE_TIMESTAMP_FILE = '/var/lve/lveinfo.ver'
LICENSE_TIMESTAMP_DIR = os.path.dirname(LICENSE_TIMESTAMP_FILE)
RHN_SYSTEMID = '/etc/sysconfig/rhn/systemid'
TEMPLATES = {}
TEMPLATES['Email'] = {'template_file': '/usr/share/cloudlinux/license_out_of_date_email.txt', 'error_msg': 'Error: License out of date, email template missing.'}
TEMPLATES['NoValid'] = {'template_file': '/usr/share/cloudlinux/no_valid_license_screen.txt', 'error_msg': 'Error: No valid license found, template is missing.'}
NO_VALID_LICENSE_FOUND_TEMPLATE = '/usr/share/cloudlinux/no_valid_license_screen.txt'
LICENSE_OUT_OF_DATE_EMAIL_TEMPLATE = '/usr/share/cloudlinux/license_out_of_date_email.txt'
SHOW_IP_LINK = 'http://cloudlinux.com/showip.php'
# License Data Class
class LicenseData:
_license_last_timestamp = ''
_server_ip = ''
_letter_template = ''
# Check License
def check_license(self, license_timestamp_file):
try:
# Get timestamp of last license check
data = open(license_timestamp_file, "rb").read()
value = struct.unpack('i', data)
# Set last check timestamp to attr.
self._license_last_timestamp = value[0]
# check if current time < 3 days
if ((int(time.time()) - value[0]) > 259200):
try:
license_file_needs_update = os.path.getmtime(RHN_SYSTEMID) > os.path.getmtime(license_timestamp_file)
except OSError:
license_file_needs_update = True
if license_file_needs_update:
return update_license_timestamp_file()
return False
else:
return True
except (IOError, struct.error):
return False
# Get IP
def get_ip(self):
if not self._server_ip:
try:
self._server_ip = request.urlopen(SHOW_IP_LINK).read().strip()
except error.URLError as e:
print('Error: Get server IP. ' + str(e))
sys.exit(1)
# Format Date
def date_format(self, format):
return datetime.datetime.fromtimestamp(self._license_last_timestamp).strftime(format)
# Open letter template
def open_letter_template(self, template):
try:
self._letter_template = open(template, "r").read()
except IOError as e:
print('Error: Failed to open template file. ' +str(e))
sys.exit(1)
# Format Screen
def format_letter(self):
admin_email = detect.getCPAdminEmail()
if admin_email:
self.get_ip()
if not self._license_last_timestamp:
return self._letter_template.replace('%LIC_DATE%','').replace('%IP%',self._server_ip).replace('%HOSTNAME%',socket.gethostname()).replace('%FROM%',admin_email)
else:
return self._letter_template.replace('%LIC_DATE%',' since ' + self.date_format('%b %d, %y')).replace('%IP%',self._server_ip).replace('%HOSTNAME%',socket.gethostname()).replace('%FROM%',admin_email)
else:
return None
# License Data Class Object
License = LicenseData()
# License update cron
def update_license_timestamp_file():
try:
if not os.path.isdir(LICENSE_TIMESTAMP_DIR):
mod_makedirs(LICENSE_TIMESTAMP_DIR, 0o755)
p = subprocess.Popen([RHN_CHECK_FILE], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(out, err) = p.communicate()
if p.returncode == 0:
f = open(LICENSE_TIMESTAMP_FILE, 'wb')
f.write(struct.pack('i', int(time.time())))
f.close()
return True
return False
except (OSError, IOError):
return False
# update license with new key
def update_license_with_key(key):
try:
if not os.path.isdir(LICENSE_TIMESTAMP_DIR):
mod_makedirs(LICENSE_TIMESTAMP_DIR, 0o755)
p = subprocess.Popen([RHN_UPDATE_NEW_KEY, '--activationkey='+key, '--force'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(out, err) = p.communicate()
if p.returncode == 0:
f = open(LICENSE_TIMESTAMP_FILE, 'wb')
f.write(struct.pack('i', int(time.time())))
f.close()
print('OK')
return True
else:
print(out.strip())
return False
except (OSError, IOError):
print('Error: New key activation failed, please try again later.')
return False
# Returns:
# True == license is Ok
# False == license expired or not found
def check_license():
# Check for license timestamp file in /var/lve/lveinfo.ver
if os.path.isfile(LICENSE_TIMESTAMP_FILE):
return License.check_license(LICENSE_TIMESTAMP_FILE)
else:
return False
# Return Last license check Date
def last_license_check():
# Check for license timestamp file in /var/lve/lveinfo.ver
if os.path.isfile(LICENSE_TIMESTAMP_FILE):
if License.check_license(LICENSE_TIMESTAMP_FILE):
return 'OK'
else:
return 'No valid license found, last successful check was on ' + License.date_format('%b %d, %y')
else:
return 'No valid license found.'
def get_email_template():
return get_template_to_display(TEMPLATES['Email'])
def get_novalid_template():
return get_template_to_display(TEMPLATES['NoValid'])
# Return Template Email, No Valid license found template.
def get_template_to_display(template):
# check for template in /usr/share/cloudlinux
if os.path.isfile(template['template_file']):
if check_license():
return None
else:
# set template text into License class attr.
License.open_letter_template(template['template_file'])
# Return Formatted Template
return License.format_letter()
else:
return template['error_msg']
Zerion Mini Shell 1.0