def mail_birthday(api = None, id = None, links = True): api = api or logic.get_api() employee = api.get_employee(id) if id else api.self_employee() name = employee.get("full_name", None) working = employee.get("working", None) contact_information = employee.get("primary_contact_information", {}) email = contact_information.get("email", None) if not name: raise quorum.OperationalError("No name defined") if not email: raise quorum.OperationalError("No email defined") if not working == 1: raise quorum.OperationalError("No longer working") quorum.debug("Sending birthday email to %s <%s>" % (name, email)) quorum.send_mail( subject = BIRTHDAY_SUBJECT[config.LOCALE], sender = config.SENDER_EMAIL, receivers = ["%s <%s>" % (name, email)], rich = "email/birthday.%s.html.tpl" % config.LOCALE, context = dict( settings = dict( logo = True, links = links ), base_url = config.BASE_URL, omnix_base_url = config.OMNI_URL, commission_rate = config.COMMISSION_RATE ) )
def schedule_tag(tag, quota=QUOTA_USER, initial=0): access_token = flask.session["ig.access_token"] if flask.session else None access_token = storage.get_value("ig.access_token", access_token) if not access_token: return quorum.debug("Starting tag scheduling for '%s'" % tag) scheduler = Scheduler(tag, access_token, quota=quota, initial=initial) scheduler.start()
def schedule_tag(tag, quota = QUOTA_USER, initial = 0): access_token = flask.session["ig.access_token"] if flask.session else None access_token = storage.get_value("ig.access_token", access_token) if not access_token: return quorum.debug("Starting tag scheduling for '%s'" % tag) scheduler = Scheduler(tag, access_token, quota = quota, initial = initial) scheduler.start()
def birthday_mail(month = None, day = None): api = logic.get_api(mode = omni.API.DIRECT_MODE) business.mail_birthday_all( api = api, month = month, day = day, links = False ) quorum.debug("Finished sending birthday emails")
def mail_activity( api = None, id = None, year = None, month = None, validate = False, links = True ): api = api or logic.get_api() employee = api.get_employee(id) if id else api.self_employee() name = employee.get("full_name", None) working = employee.get("working", None) contact_information = employee.get("primary_contact_information", {}) email = contact_information.get("email", None) if not name: raise quorum.OperationalError("No name defined") if not email: raise quorum.OperationalError("No email defined") if not working == 1: raise quorum.OperationalError("No longer working") now = datetime.datetime.utcnow() now_s = now.strftime("%B %d %Y") operations,\ target_s,\ sales_total,\ sales_s,\ returns_s,\ _previous_month,\ _previous_year,\ _next_month,\ _next_year,\ _has_next = get_sales(api = api, id = id, year = year, month = month) if validate and not operations: return quorum.debug("Sending activity email to %s <%s>" % (name, email)) quorum.send_mail( subject = ACTIVITY_SUBJECT[config.LOCALE] % (target_s, now_s), sender = config.SENDER_EMAIL, receivers = ["%s <%s>" % (name, email)], rich = "email/activity.%s.html.tpl" % config.LOCALE, context = dict( settings = dict( logo = True, links = links ), target = target_s, operations = operations, sales_total = sales_total, sales_count = len(sales_s), returns_count = len(returns_s), base_url = config.BASE_URL, omnix_base_url = config.OMNI_URL, commission_rate = config.COMMISSION_RATE ) )
def activity_mail(year = None, month = None): api = logic.get_api(mode = omni.API.DIRECT_MODE) business.mail_activity_all( api = api, year = year, month = month, validate = True, links = False ) quorum.debug("Finished sending activity emails")
def mail_activity(api=None, id=None, year=None, month=None, validate=False, links=True): api = api or logic.get_api() employee = api.get_employee(id) if id else api.self_employee() name = employee.get("full_name", None) working = employee.get("working", None) contact_information = employee.get("primary_contact_information", {}) email = contact_information.get("email", None) if not name: raise quorum.OperationalError("No name defined") if not email: raise quorum.OperationalError("No email defined") if not working == 1: raise quorum.OperationalError("No longer working") now = datetime.datetime.utcnow() now_s = now.strftime("%B %d %Y") operations,\ target_s,\ sales_total,\ sales_s,\ returns_s,\ _previous_month,\ _previous_year,\ _next_month,\ _next_year,\ _has_next = get_sales(api = api, id = id, year = year, month = month) if validate and not operations: return quorum.debug("Sending activity email to %s <%s>" % (name, email)) quorum.send_mail(subject=ACTIVITY_SUBJECT[config.LOCALE] % (target_s, now_s), sender=config.SENDER_EMAIL, receivers=["%s <%s>" % (name, email)], rich="email/activity.%s.html.tpl" % config.LOCALE, context=dict(settings=dict(logo=True, links=links), target=target_s, operations=operations, sales_total=sales_total, sales_count=len(sales_s), returns_count=len(returns_s), base_url=config.BASE_URL, omnix_base_url=config.OMNI_URL, commission_rate=config.COMMISSION_RATE))
def connect(self, queue="default"): if not config.REMOTE: return while True: try: quorum.debug("Starting loop cycle in slave ...") self.connection = quorum.get_amqp(force=True) self.channel = self.connection.channel() self.channel.queue_declare(queue=queue, durable=True) self.channel.basic_qos(prefetch_count=1) self.channel.basic_consume(queue=queue, on_message_callback=self.callback) self.channel.start_consuming() except Exception as exception: quorum.error("Exception while executing - %s" % quorum.legacy.UNICODE(exception), log_trace=True) quorum.info("Sleeping %d seconds before consume retry" % RETRY_TIMEOUT) time.sleep(RETRY_TIMEOUT)
def mail_birthday(api=None, id=None, links=True): api = api or logic.get_api() employee = api.get_employee(id) if id else api.self_employee() name = employee.get("full_name", None) working = employee.get("working", None) contact_information = employee.get("primary_contact_information", {}) email = contact_information.get("email", None) if not name: raise quorum.OperationalError("No name defined") if not email: raise quorum.OperationalError("No email defined") if not working == 1: raise quorum.OperationalError("No longer working") quorum.debug("Sending birthday email to %s <%s>" % (name, email)) quorum.send_mail(subject=BIRTHDAY_SUBJECT[config.LOCALE], sender=config.SENDER_EMAIL, receivers=["%s <%s>" % (name, email)], rich=config.BIRTHDAY_TEMPLATE, context=dict(settings=dict(logo=True, links=links), base_url=config.BASE_URL, omnix_base_url=config.OMNI_URL, commission_rate=config.COMMISSION_RATE))
def load_mail(): if not config.REMOTE: return day_time = quorum.daily_work(birthday_mail, offset = 14400) week_time = quorum.weekly_work(activity_mail, weekday = 4, offset = 14400) month_time = quorum.monthly_work(activity_previous, monthday = 26, offset = 14400) day_date = datetime.datetime.utcfromtimestamp(day_time) week_date = datetime.datetime.utcfromtimestamp(week_time) month_date = datetime.datetime.utcfromtimestamp(month_time) quorum.debug("Scheduled initial daily birthday mail task for %s" % day_date) quorum.debug("Scheduled initial weekly activity mail task for %s" % week_date) quorum.debug("Scheduled initial monthly activity previous task for %s" % month_date)
def load_slack(): if not config.REMOTE: return sales_time = quorum.daily_work(sales_slack, offset = 14400) previous_time = quorum.daily_work(previous_slack, offset = 18000) week_time = quorum.weekly_work(week_slack, weekday = 0, offset = 14400) sales_date = datetime.datetime.utcfromtimestamp(sales_time) previous_date = datetime.datetime.utcfromtimestamp(previous_time) week_date = datetime.datetime.utcfromtimestamp(week_time) quorum.debug("Scheduled initial daily sales slack task for %s" % sales_date) quorum.debug("Scheduled initial daily previous (sales) slack task for %s" % previous_date) quorum.debug("Scheduled initial weekly previous week (sales) slack task for %s" % week_date)
def callback(self, channel, method, properties, body): # prints a debug message about the callback call for the message, this # may be used latter for debugging purposes (as requested) quorum.debug("Received callback for message") # loads the contents of the body that is going to be submitted this # is considered the payload of the document to be submitted document = json.loads(body) # retrieves the various attributes of the document that is going to # be submitted, making sure that the issue date is correctly formatted type = document["_class"] object_id = document["object_id"] representation = document["representation"] issue_date = document["issue_date"] issue_date_d = datetime.datetime.utcfromtimestamp(issue_date) issue_date_s = issue_date_d.strftime("%d %b %Y %H:%M:%S") # verifies if the document is considered to be outdated (timeout passed) # in case it's returns immediately printing a message outdated = not properties.timestamp or\ properties.timestamp < time.time() - MESSAGE_TIMEOUT if outdated: channel.basic_ack(delivery_tag=method.delivery_tag) quorum.info("Canceling/Dropping %s - %s (%s)" % (type, representation, issue_date_s)) return # retrieves the current time and uses it to print debug information # about the current document submission to at quorum.info("Submitting %s - %s (%s)" % (type, representation, issue_date_s)) # resolves the method for the currently retrieved data type (class) # this should raise an exception in case the type is invalid api_method = self._resolve_method(type) try: # calls the proper method for the submission of the document # described by the provided object id, in case there's a problem # in the request an exception should be raised and handled properly api_method(object_id) except Exception as exception: quorum.error("Exception while submitting document - %s" % quorum.legacy.UNICODE(exception)) retries = properties.priority or 0 retries -= 1 properties.priority = retries if retries >= 0: self.channel.basic_publish(exchange="", routing_key=config.QUEUE, body=body, properties=properties) quorum.error( "Re-queueing for latter consumption (%d retries pending)" % retries) else: quorum.error( "No more retries left, the document will be discarded") else: quorum.info("Document submitted with success") # marks the message as acknowledged in the message queue server # and then prints a debug message about the action channel.basic_ack(delivery_tag=method.delivery_tag) quorum.debug("Marked as acknowledged in message queue")
def ping(self): # retrieves the server again to ensure that the data # is correct in it self.server = self.server.reload() # retrieves the various attribute values from the server # that are going to be used in the method instance_id = self.server.instance_id name = self.server.name url = self.server.url method = self.server.val("method", "GET") # parses the provided url values, retrieving the various # components of it to be used in the ping operation url_s = quorum.legacy.urlparse(url) scheme = url_s.scheme hostname = url_s.hostname port = url_s.port path = url_s.path # retrieves the connection class to be used according # to the scheme defined in the url connection_c = quorum.legacy.HTTPSConnection if scheme == "https" else quorum.legacy.HTTPConnection # retrieves the timestamp for the start of the connection # to the remote host and then creates a new connection to # the remote host to proceed with the "ping" operation start_time = time.time() connection = connection_c(hostname, port) try: connection.request(method, path, headers=HEADERS) response = connection.getresponse() except: response = None finally: connection.close() end_time = time.time() latency = int((end_time - start_time) * 1000.0) # retrieves both the status and the reason values # defaulting to "down" values in case the response # is not available status = response and response.status or 0 reason = response and response.reason or "Down" # checks if the current status code is in the # correct range these are considered the "valid" # status codes for an up server up = (status / 100) in (2, 3) # prints a debug message about the ping operation # with the complete diagnostics information quorum.debug("%s :: %s %s / %dms" % (url, status, reason, latency)) # inserts the log document into the data source so that # the information is registered in the proper place _log = dict( enabled=True, instance_id=instance_id, name=name, url=url, up=up, status=status, reason=reason, latency=latency, timestamp=start_time, ) _log = log.Log.new(model=_log) _log.save() # verifies the correct changing orders (from up to down and # from down to up) this will trigger the proper events change_down = not self.server.val("up", True) == up and not up change_up = not self.server.val("up", True) == up and up # updates the server information, so that it matched the last # available information from the last "ping" operation self.server.up = up self.server.latency = latency self.server.timestamp = start_time self.server.save() # in case there's a change from server state up to down, or # down to up (reversed) must trigger the proper event so # that the user is notified about the change if change_down: self.on_down() if change_up: self.on_up() # retrieves the current time and uses that value to # re-insert a new task into the execution thread, this # is considered the re-schedule operation current_time = time.time() self.server.enabled and quorum.run_back(self.ping, target_time=current_time + self.timeout)
def load(): if not config.SCHEDULE: return quorum.debug("Loading scheduling tasks ...") load_slack() load_mail()